es6.js 5.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059
  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 result = new Color3(0.0, 0.0, 0.0);
  1754. Color3.LerpToRef(start, end, amount, result);
  1755. return result;
  1756. };
  1757. /**
  1758. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1759. * @param left defines the start value
  1760. * @param right defines the end value
  1761. * @param amount defines the gradient factor
  1762. * @param result defines the Color3 object where to store the result
  1763. */
  1764. Color3.LerpToRef = function (left, right, amount, result) {
  1765. result.r = left.r + ((right.r - left.r) * amount);
  1766. result.g = left.g + ((right.g - left.g) * amount);
  1767. result.b = left.b + ((right.b - left.b) * amount);
  1768. };
  1769. /**
  1770. * Returns a Color3 value containing a red color
  1771. * @returns a new Color3 object
  1772. */
  1773. Color3.Red = function () { return new Color3(1, 0, 0); };
  1774. /**
  1775. * Returns a Color3 value containing a green color
  1776. * @returns a new Color3 object
  1777. */
  1778. Color3.Green = function () { return new Color3(0, 1, 0); };
  1779. /**
  1780. * Returns a Color3 value containing a blue color
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1784. /**
  1785. * Returns a Color3 value containing a black color
  1786. * @returns a new Color3 object
  1787. */
  1788. Color3.Black = function () { return new Color3(0, 0, 0); };
  1789. /**
  1790. * Returns a Color3 value containing a white color
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.White = function () { return new Color3(1, 1, 1); };
  1794. /**
  1795. * Returns a Color3 value containing a purple color
  1796. * @returns a new Color3 object
  1797. */
  1798. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1799. /**
  1800. * Returns a Color3 value containing a magenta color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1804. /**
  1805. * Returns a Color3 value containing a yellow color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1809. /**
  1810. * Returns a Color3 value containing a gray color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1814. /**
  1815. * Returns a Color3 value containing a teal color
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1819. /**
  1820. * Returns a Color3 value containing a random color
  1821. * @returns a new Color3 object
  1822. */
  1823. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1824. return Color3;
  1825. }());
  1826. BABYLON.Color3 = Color3;
  1827. /**
  1828. * Class used to hold a RBGA color
  1829. */
  1830. var Color4 = /** @class */ (function () {
  1831. /**
  1832. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1833. * @param r defines the red component (between 0 and 1, default is 0)
  1834. * @param g defines the green component (between 0 and 1, default is 0)
  1835. * @param b defines the blue component (between 0 and 1, default is 0)
  1836. * @param a defines the alpha component (between 0 and 1, default is 1)
  1837. */
  1838. function Color4(
  1839. /**
  1840. * Defines the red component (between 0 and 1, default is 0)
  1841. */
  1842. r,
  1843. /**
  1844. * Defines the green component (between 0 and 1, default is 0)
  1845. */
  1846. g,
  1847. /**
  1848. * Defines the blue component (between 0 and 1, default is 0)
  1849. */
  1850. b,
  1851. /**
  1852. * Defines the alpha component (between 0 and 1, default is 1)
  1853. */
  1854. a) {
  1855. if (r === void 0) { r = 0; }
  1856. if (g === void 0) { g = 0; }
  1857. if (b === void 0) { b = 0; }
  1858. if (a === void 0) { a = 1; }
  1859. this.r = r;
  1860. this.g = g;
  1861. this.b = b;
  1862. this.a = a;
  1863. }
  1864. // Operators
  1865. /**
  1866. * Adds in place the given Color4 values to the current Color4 object
  1867. * @param right defines the second operand
  1868. * @returns the current updated Color4 object
  1869. */
  1870. Color4.prototype.addInPlace = function (right) {
  1871. this.r += right.r;
  1872. this.g += right.g;
  1873. this.b += right.b;
  1874. this.a += right.a;
  1875. return this;
  1876. };
  1877. /**
  1878. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1879. * @returns the new array
  1880. */
  1881. Color4.prototype.asArray = function () {
  1882. var result = new Array();
  1883. this.toArray(result, 0);
  1884. return result;
  1885. };
  1886. /**
  1887. * Stores from the starting index in the given array the Color4 successive values
  1888. * @param array defines the array where to store the r,g,b components
  1889. * @param index defines an optional index in the target array to define where to start storing values
  1890. * @returns the current Color4 object
  1891. */
  1892. Color4.prototype.toArray = function (array, index) {
  1893. if (index === undefined) {
  1894. index = 0;
  1895. }
  1896. array[index] = this.r;
  1897. array[index + 1] = this.g;
  1898. array[index + 2] = this.b;
  1899. array[index + 3] = this.a;
  1900. return this;
  1901. };
  1902. /**
  1903. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1904. * @param right defines the second operand
  1905. * @returns a new Color4 object
  1906. */
  1907. Color4.prototype.add = function (right) {
  1908. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1909. };
  1910. /**
  1911. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1912. * @param right defines the second operand
  1913. * @returns a new Color4 object
  1914. */
  1915. Color4.prototype.subtract = function (right) {
  1916. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1917. };
  1918. /**
  1919. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1920. * @param right defines the second operand
  1921. * @param result defines the Color4 object where to store the result
  1922. * @returns the current Color4 object
  1923. */
  1924. Color4.prototype.subtractToRef = function (right, result) {
  1925. result.r = this.r - right.r;
  1926. result.g = this.g - right.g;
  1927. result.b = this.b - right.b;
  1928. result.a = this.a - right.a;
  1929. return this;
  1930. };
  1931. /**
  1932. * Creates a new Color4 with the current Color4 values multiplied by scale
  1933. * @param scale defines the scaling factor to apply
  1934. * @returns a new Color4 object
  1935. */
  1936. Color4.prototype.scale = function (scale) {
  1937. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1938. };
  1939. /**
  1940. * Multiplies the current Color4 values by scale and stores the result in "result"
  1941. * @param scale defines the scaling factor to apply
  1942. * @param result defines the Color4 object where to store the result
  1943. * @returns the current unmodified Color4
  1944. */
  1945. Color4.prototype.scaleToRef = function (scale, result) {
  1946. result.r = this.r * scale;
  1947. result.g = this.g * scale;
  1948. result.b = this.b * scale;
  1949. result.a = this.a * scale;
  1950. return this;
  1951. };
  1952. /**
  1953. * Scale the current Color4 values by a factor and add the result to a given Color4
  1954. * @param scale defines the scale factor
  1955. * @param result defines the Color4 object where to store the result
  1956. * @returns the unmodified current Color4
  1957. */
  1958. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1959. result.r += this.r * scale;
  1960. result.g += this.g * scale;
  1961. result.b += this.b * scale;
  1962. result.a += this.a * scale;
  1963. return this;
  1964. };
  1965. /**
  1966. * Clamps the rgb values by the min and max values and stores the result into "result"
  1967. * @param min defines minimum clamping value (default is 0)
  1968. * @param max defines maximum clamping value (default is 1)
  1969. * @param result defines color to store the result into.
  1970. * @returns the cuurent Color4
  1971. */
  1972. Color4.prototype.clampToRef = function (min, max, result) {
  1973. if (min === void 0) { min = 0; }
  1974. if (max === void 0) { max = 1; }
  1975. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1976. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1977. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1978. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1979. return this;
  1980. };
  1981. /**
  1982. * Multipy an Color4 value by another and return a new Color4 object
  1983. * @param color defines the Color4 value to multiply by
  1984. * @returns a new Color4 object
  1985. */
  1986. Color4.prototype.multiply = function (color) {
  1987. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1988. };
  1989. /**
  1990. * Multipy a Color4 value by another and push the result in a reference value
  1991. * @param color defines the Color4 value to multiply by
  1992. * @param result defines the Color4 to fill the result in
  1993. * @returns the result Color4
  1994. */
  1995. Color4.prototype.multiplyToRef = function (color, result) {
  1996. result.r = this.r * color.r;
  1997. result.g = this.g * color.g;
  1998. result.b = this.b * color.b;
  1999. result.a = this.a * color.a;
  2000. return result;
  2001. };
  2002. /**
  2003. * Creates a string with the Color4 current values
  2004. * @returns the string representation of the Color4 object
  2005. */
  2006. Color4.prototype.toString = function () {
  2007. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2008. };
  2009. /**
  2010. * Returns the string "Color4"
  2011. * @returns "Color4"
  2012. */
  2013. Color4.prototype.getClassName = function () {
  2014. return "Color4";
  2015. };
  2016. /**
  2017. * Compute the Color4 hash code
  2018. * @returns an unique number that can be used to hash Color4 objects
  2019. */
  2020. Color4.prototype.getHashCode = function () {
  2021. var hash = this.r || 0;
  2022. hash = (hash * 397) ^ (this.g || 0);
  2023. hash = (hash * 397) ^ (this.b || 0);
  2024. hash = (hash * 397) ^ (this.a || 0);
  2025. return hash;
  2026. };
  2027. /**
  2028. * Creates a new Color4 copied from the current one
  2029. * @returns a new Color4 object
  2030. */
  2031. Color4.prototype.clone = function () {
  2032. return new Color4(this.r, this.g, this.b, this.a);
  2033. };
  2034. /**
  2035. * Copies the given Color4 values into the current one
  2036. * @param source defines the source Color4 object
  2037. * @returns the current updated Color4 object
  2038. */
  2039. Color4.prototype.copyFrom = function (source) {
  2040. this.r = source.r;
  2041. this.g = source.g;
  2042. this.b = source.b;
  2043. this.a = source.a;
  2044. return this;
  2045. };
  2046. /**
  2047. * Copies the given float values into the current one
  2048. * @param r defines the red component to read from
  2049. * @param g defines the green component to read from
  2050. * @param b defines the blue component to read from
  2051. * @param a defines the alpha component to read from
  2052. * @returns the current updated Color4 object
  2053. */
  2054. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2055. this.r = r;
  2056. this.g = g;
  2057. this.b = b;
  2058. this.a = a;
  2059. return this;
  2060. };
  2061. /**
  2062. * Copies the given float values into the current one
  2063. * @param r defines the red component to read from
  2064. * @param g defines the green component to read from
  2065. * @param b defines the blue component to read from
  2066. * @param a defines the alpha component to read from
  2067. * @returns the current updated Color4 object
  2068. */
  2069. Color4.prototype.set = function (r, g, b, a) {
  2070. return this.copyFromFloats(r, g, b, a);
  2071. };
  2072. /**
  2073. * Compute the Color4 hexadecimal code as a string
  2074. * @returns a string containing the hexadecimal representation of the Color4 object
  2075. */
  2076. Color4.prototype.toHexString = function () {
  2077. var intR = (this.r * 255) | 0;
  2078. var intG = (this.g * 255) | 0;
  2079. var intB = (this.b * 255) | 0;
  2080. var intA = (this.a * 255) | 0;
  2081. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2082. };
  2083. /**
  2084. * Computes a new Color4 converted from the current one to linear space
  2085. * @returns a new Color4 object
  2086. */
  2087. Color4.prototype.toLinearSpace = function () {
  2088. var convertedColor = new Color4();
  2089. this.toLinearSpaceToRef(convertedColor);
  2090. return convertedColor;
  2091. };
  2092. /**
  2093. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2094. * @param convertedColor defines the Color4 object where to store the linear space version
  2095. * @returns the unmodified Color4
  2096. */
  2097. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2098. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2099. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2100. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2101. convertedColor.a = this.a;
  2102. return this;
  2103. };
  2104. /**
  2105. * Computes a new Color4 converted from the current one to gamma space
  2106. * @returns a new Color4 object
  2107. */
  2108. Color4.prototype.toGammaSpace = function () {
  2109. var convertedColor = new Color4();
  2110. this.toGammaSpaceToRef(convertedColor);
  2111. return convertedColor;
  2112. };
  2113. /**
  2114. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2115. * @param convertedColor defines the Color4 object where to store the gamma space version
  2116. * @returns the unmodified Color4
  2117. */
  2118. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2119. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2120. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2121. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2122. convertedColor.a = this.a;
  2123. return this;
  2124. };
  2125. // Statics
  2126. /**
  2127. * Creates a new Color4 from the string containing valid hexadecimal values
  2128. * @param hex defines a string containing valid hexadecimal values
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.FromHexString = function (hex) {
  2132. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2133. return new Color4(0.0, 0.0, 0.0, 0.0);
  2134. }
  2135. var r = parseInt(hex.substring(1, 3), 16);
  2136. var g = parseInt(hex.substring(3, 5), 16);
  2137. var b = parseInt(hex.substring(5, 7), 16);
  2138. var a = parseInt(hex.substring(7, 9), 16);
  2139. return Color4.FromInts(r, g, b, a);
  2140. };
  2141. /**
  2142. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2143. * @param left defines the start value
  2144. * @param right defines the end value
  2145. * @param amount defines the gradient factor
  2146. * @returns a new Color4 object
  2147. */
  2148. Color4.Lerp = function (left, right, amount) {
  2149. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2150. Color4.LerpToRef(left, right, amount, result);
  2151. return result;
  2152. };
  2153. /**
  2154. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2155. * @param left defines the start value
  2156. * @param right defines the end value
  2157. * @param amount defines the gradient factor
  2158. * @param result defines the Color4 object where to store data
  2159. */
  2160. Color4.LerpToRef = function (left, right, amount, result) {
  2161. result.r = left.r + (right.r - left.r) * amount;
  2162. result.g = left.g + (right.g - left.g) * amount;
  2163. result.b = left.b + (right.b - left.b) * amount;
  2164. result.a = left.a + (right.a - left.a) * amount;
  2165. };
  2166. /**
  2167. * Creates a new Color4 from a Color3 and an alpha value
  2168. * @param color3 defines the source Color3 to read from
  2169. * @param alpha defines the alpha component (1.0 by default)
  2170. * @returns a new Color4 object
  2171. */
  2172. Color4.FromColor3 = function (color3, alpha) {
  2173. if (alpha === void 0) { alpha = 1.0; }
  2174. return new Color4(color3.r, color3.g, color3.b, alpha);
  2175. };
  2176. /**
  2177. * Creates a new Color4 from the starting index element of the given array
  2178. * @param array defines the source array to read from
  2179. * @param offset defines the offset in the source array
  2180. * @returns a new Color4 object
  2181. */
  2182. Color4.FromArray = function (array, offset) {
  2183. if (offset === void 0) { offset = 0; }
  2184. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2185. };
  2186. /**
  2187. * Creates a new Color3 from integer values (< 256)
  2188. * @param r defines the red component to read from (value between 0 and 255)
  2189. * @param g defines the green component to read from (value between 0 and 255)
  2190. * @param b defines the blue component to read from (value between 0 and 255)
  2191. * @param a defines the alpha component to read from (value between 0 and 255)
  2192. * @returns a new Color3 object
  2193. */
  2194. Color4.FromInts = function (r, g, b, a) {
  2195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2196. };
  2197. /**
  2198. * Check the content of a given array and convert it to an array containing RGBA data
  2199. * If the original array was already containing count * 4 values then it is returned directly
  2200. * @param colors defines the array to check
  2201. * @param count defines the number of RGBA data to expect
  2202. * @returns an array containing count * 4 values (RGBA)
  2203. */
  2204. Color4.CheckColors4 = function (colors, count) {
  2205. // Check if color3 was used
  2206. if (colors.length === count * 3) {
  2207. var colors4 = [];
  2208. for (var index = 0; index < colors.length; index += 3) {
  2209. var newIndex = (index / 3) * 4;
  2210. colors4[newIndex] = colors[index];
  2211. colors4[newIndex + 1] = colors[index + 1];
  2212. colors4[newIndex + 2] = colors[index + 2];
  2213. colors4[newIndex + 3] = 1.0;
  2214. }
  2215. return colors4;
  2216. }
  2217. return colors;
  2218. };
  2219. return Color4;
  2220. }());
  2221. BABYLON.Color4 = Color4;
  2222. /**
  2223. * Class representing a vector containing 2 coordinates
  2224. */
  2225. var Vector2 = /** @class */ (function () {
  2226. /**
  2227. * Creates a new Vector2 from the given x and y coordinates
  2228. * @param x defines the first coordinate
  2229. * @param y defines the second coordinate
  2230. */
  2231. function Vector2(
  2232. /** defines the first coordinate */
  2233. x,
  2234. /** defines the second coordinate */
  2235. y) {
  2236. if (x === void 0) { x = 0; }
  2237. if (y === void 0) { y = 0; }
  2238. this.x = x;
  2239. this.y = y;
  2240. }
  2241. /**
  2242. * Gets a string with the Vector2 coordinates
  2243. * @returns a string with the Vector2 coordinates
  2244. */
  2245. Vector2.prototype.toString = function () {
  2246. return "{X: " + this.x + " Y:" + this.y + "}";
  2247. };
  2248. /**
  2249. * Gets class name
  2250. * @returns the string "Vector2"
  2251. */
  2252. Vector2.prototype.getClassName = function () {
  2253. return "Vector2";
  2254. };
  2255. /**
  2256. * Gets current vector hash code
  2257. * @returns the Vector2 hash code as a number
  2258. */
  2259. Vector2.prototype.getHashCode = function () {
  2260. var hash = this.x || 0;
  2261. hash = (hash * 397) ^ (this.y || 0);
  2262. return hash;
  2263. };
  2264. // Operators
  2265. /**
  2266. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2267. * @param array defines the source array
  2268. * @param index defines the offset in source array
  2269. * @returns the current Vector2
  2270. */
  2271. Vector2.prototype.toArray = function (array, index) {
  2272. if (index === void 0) { index = 0; }
  2273. array[index] = this.x;
  2274. array[index + 1] = this.y;
  2275. return this;
  2276. };
  2277. /**
  2278. * Copy the current vector to an array
  2279. * @returns a new array with 2 elements: the Vector2 coordinates.
  2280. */
  2281. Vector2.prototype.asArray = function () {
  2282. var result = new Array();
  2283. this.toArray(result, 0);
  2284. return result;
  2285. };
  2286. /**
  2287. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2288. * @param source defines the source Vector2
  2289. * @returns the current updated Vector2
  2290. */
  2291. Vector2.prototype.copyFrom = function (source) {
  2292. this.x = source.x;
  2293. this.y = source.y;
  2294. return this;
  2295. };
  2296. /**
  2297. * Sets the Vector2 coordinates with the given floats
  2298. * @param x defines the first coordinate
  2299. * @param y defines the second coordinate
  2300. * @returns the current updated Vector2
  2301. */
  2302. Vector2.prototype.copyFromFloats = function (x, y) {
  2303. this.x = x;
  2304. this.y = y;
  2305. return this;
  2306. };
  2307. /**
  2308. * Sets the Vector2 coordinates with the given floats
  2309. * @param x defines the first coordinate
  2310. * @param y defines the second coordinate
  2311. * @returns the current updated Vector2
  2312. */
  2313. Vector2.prototype.set = function (x, y) {
  2314. return this.copyFromFloats(x, y);
  2315. };
  2316. /**
  2317. * Add another vector with the current one
  2318. * @param otherVector defines the other vector
  2319. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2320. */
  2321. Vector2.prototype.add = function (otherVector) {
  2322. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2323. };
  2324. /**
  2325. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2326. * @param otherVector defines the other vector
  2327. * @param result defines the target vector
  2328. * @returns the unmodified current Vector2
  2329. */
  2330. Vector2.prototype.addToRef = function (otherVector, result) {
  2331. result.x = this.x + otherVector.x;
  2332. result.y = this.y + otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.addInPlace = function (otherVector) {
  2341. this.x += otherVector.x;
  2342. this.y += otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.addVector3 = function (otherVector) {
  2351. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2352. };
  2353. /**
  2354. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2355. * @param otherVector defines the other vector
  2356. * @returns a new Vector2
  2357. */
  2358. Vector2.prototype.subtract = function (otherVector) {
  2359. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2360. };
  2361. /**
  2362. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2363. * @param otherVector defines the other vector
  2364. * @param result defines the target vector
  2365. * @returns the unmodified current Vector2
  2366. */
  2367. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2368. result.x = this.x - otherVector.x;
  2369. result.y = this.y - otherVector.y;
  2370. return this;
  2371. };
  2372. /**
  2373. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @returns the current updated Vector2
  2376. */
  2377. Vector2.prototype.subtractInPlace = function (otherVector) {
  2378. this.x -= otherVector.x;
  2379. this.y -= otherVector.y;
  2380. return this;
  2381. };
  2382. /**
  2383. * Multiplies in place the current Vector2 coordinates by the given ones
  2384. * @param otherVector defines the other vector
  2385. * @returns the current updated Vector2
  2386. */
  2387. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2388. this.x *= otherVector.x;
  2389. this.y *= otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2394. * @param otherVector defines the other vector
  2395. * @returns a new Vector2
  2396. */
  2397. Vector2.prototype.multiply = function (otherVector) {
  2398. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2399. };
  2400. /**
  2401. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2402. * @param otherVector defines the other vector
  2403. * @param result defines the target vector
  2404. * @returns the unmodified current Vector2
  2405. */
  2406. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2407. result.x = this.x * otherVector.x;
  2408. result.y = this.y * otherVector.y;
  2409. return this;
  2410. };
  2411. /**
  2412. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2413. * @param x defines the first coordinate
  2414. * @param y defines the second coordinate
  2415. * @returns a new Vector2
  2416. */
  2417. Vector2.prototype.multiplyByFloats = function (x, y) {
  2418. return new Vector2(this.x * x, this.y * y);
  2419. };
  2420. /**
  2421. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns a new Vector2
  2424. */
  2425. Vector2.prototype.divide = function (otherVector) {
  2426. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2427. };
  2428. /**
  2429. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2430. * @param otherVector defines the other vector
  2431. * @param result defines the target vector
  2432. * @returns the unmodified current Vector2
  2433. */
  2434. Vector2.prototype.divideToRef = function (otherVector, result) {
  2435. result.x = this.x / otherVector.x;
  2436. result.y = this.y / otherVector.y;
  2437. return this;
  2438. };
  2439. /**
  2440. * Divides the current Vector2 coordinates by the given ones
  2441. * @param otherVector defines the other vector
  2442. * @returns the current updated Vector2
  2443. */
  2444. Vector2.prototype.divideInPlace = function (otherVector) {
  2445. return this.divideToRef(otherVector, this);
  2446. };
  2447. /**
  2448. * Gets a new Vector2 with current Vector2 negated coordinates
  2449. * @returns a new Vector2
  2450. */
  2451. Vector2.prototype.negate = function () {
  2452. return new Vector2(-this.x, -this.y);
  2453. };
  2454. /**
  2455. * Multiply the Vector2 coordinates by scale
  2456. * @param scale defines the scaling factor
  2457. * @returns the current updated Vector2
  2458. */
  2459. Vector2.prototype.scaleInPlace = function (scale) {
  2460. this.x *= scale;
  2461. this.y *= scale;
  2462. return this;
  2463. };
  2464. /**
  2465. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2466. * @param scale defines the scaling factor
  2467. * @returns a new Vector2
  2468. */
  2469. Vector2.prototype.scale = function (scale) {
  2470. var result = new Vector2(0, 0);
  2471. this.scaleToRef(scale, result);
  2472. return result;
  2473. };
  2474. /**
  2475. * Scale the current Vector2 values by a factor to a given Vector2
  2476. * @param scale defines the scale factor
  2477. * @param result defines the Vector2 object where to store the result
  2478. * @returns the unmodified current Vector2
  2479. */
  2480. Vector2.prototype.scaleToRef = function (scale, result) {
  2481. result.x = this.x * scale;
  2482. result.y = this.y * scale;
  2483. return this;
  2484. };
  2485. /**
  2486. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2487. * @param scale defines the scale factor
  2488. * @param result defines the Vector2 object where to store the result
  2489. * @returns the unmodified current Vector2
  2490. */
  2491. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2492. result.x += this.x * scale;
  2493. result.y += this.y * scale;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a boolean if two vectors are equals
  2498. * @param otherVector defines the other vector
  2499. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2500. */
  2501. Vector2.prototype.equals = function (otherVector) {
  2502. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2503. };
  2504. /**
  2505. * Gets a boolean if two vectors are equals (using an epsilon value)
  2506. * @param otherVector defines the other vector
  2507. * @param epsilon defines the minimal distance to consider equality
  2508. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2509. */
  2510. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2511. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2512. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2513. };
  2514. /**
  2515. * Gets a new Vector2 from current Vector2 floored values
  2516. * @returns a new Vector2
  2517. */
  2518. Vector2.prototype.floor = function () {
  2519. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2520. };
  2521. /**
  2522. * Gets a new Vector2 from current Vector2 floored values
  2523. * @returns a new Vector2
  2524. */
  2525. Vector2.prototype.fract = function () {
  2526. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2527. };
  2528. // Properties
  2529. /**
  2530. * Gets the length of the vector
  2531. * @returns the vector length (float)
  2532. */
  2533. Vector2.prototype.length = function () {
  2534. return Math.sqrt(this.x * this.x + this.y * this.y);
  2535. };
  2536. /**
  2537. * Gets the vector squared length
  2538. * @returns the vector squared length (float)
  2539. */
  2540. Vector2.prototype.lengthSquared = function () {
  2541. return (this.x * this.x + this.y * this.y);
  2542. };
  2543. // Methods
  2544. /**
  2545. * Normalize the vector
  2546. * @returns the current updated Vector2
  2547. */
  2548. Vector2.prototype.normalize = function () {
  2549. var len = this.length();
  2550. if (len === 0)
  2551. return this;
  2552. var num = 1.0 / len;
  2553. this.x *= num;
  2554. this.y *= num;
  2555. return this;
  2556. };
  2557. /**
  2558. * Gets a new Vector2 copied from the Vector2
  2559. * @returns a new Vector2
  2560. */
  2561. Vector2.prototype.clone = function () {
  2562. return new Vector2(this.x, this.y);
  2563. };
  2564. // Statics
  2565. /**
  2566. * Gets a new Vector2(0, 0)
  2567. * @returns a new Vector2
  2568. */
  2569. Vector2.Zero = function () {
  2570. return new Vector2(0, 0);
  2571. };
  2572. /**
  2573. * Gets a new Vector2(1, 1)
  2574. * @returns a new Vector2
  2575. */
  2576. Vector2.One = function () {
  2577. return new Vector2(1, 1);
  2578. };
  2579. /**
  2580. * Gets a new Vector2 set from the given index element of the given array
  2581. * @param array defines the data source
  2582. * @param offset defines the offset in the data source
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.FromArray = function (array, offset) {
  2586. if (offset === void 0) { offset = 0; }
  2587. return new Vector2(array[offset], array[offset + 1]);
  2588. };
  2589. /**
  2590. * Sets "result" from the given index element of the given array
  2591. * @param array defines the data source
  2592. * @param offset defines the offset in the data source
  2593. * @param result defines the target vector
  2594. */
  2595. Vector2.FromArrayToRef = function (array, offset, result) {
  2596. result.x = array[offset];
  2597. result.y = array[offset + 1];
  2598. };
  2599. /**
  2600. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2601. * @param value1 defines 1st point of control
  2602. * @param value2 defines 2nd point of control
  2603. * @param value3 defines 3rd point of control
  2604. * @param value4 defines 4th point of control
  2605. * @param amount defines the interpolation factor
  2606. * @returns a new Vector2
  2607. */
  2608. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2609. var squared = amount * amount;
  2610. var cubed = amount * squared;
  2611. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2612. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2613. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2614. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2615. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2616. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2617. return new Vector2(x, y);
  2618. };
  2619. /**
  2620. * 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".
  2621. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2622. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2623. * @param value defines the value to clamp
  2624. * @param min defines the lower limit
  2625. * @param max defines the upper limit
  2626. * @returns a new Vector2
  2627. */
  2628. Vector2.Clamp = function (value, min, max) {
  2629. var x = value.x;
  2630. x = (x > max.x) ? max.x : x;
  2631. x = (x < min.x) ? min.x : x;
  2632. var y = value.y;
  2633. y = (y > max.y) ? max.y : y;
  2634. y = (y < min.y) ? min.y : y;
  2635. return new Vector2(x, y);
  2636. };
  2637. /**
  2638. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2639. * @param value1 defines the 1st control point
  2640. * @param tangent1 defines the outgoing tangent
  2641. * @param value2 defines the 2nd control point
  2642. * @param tangent2 defines the incoming tangent
  2643. * @param amount defines the interpolation factor
  2644. * @returns a new Vector2
  2645. */
  2646. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2647. var squared = amount * amount;
  2648. var cubed = amount * squared;
  2649. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2650. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2651. var part3 = (cubed - (2.0 * squared)) + amount;
  2652. var part4 = cubed - squared;
  2653. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2654. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2655. return new Vector2(x, y);
  2656. };
  2657. /**
  2658. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2659. * @param start defines the start vector
  2660. * @param end defines the end vector
  2661. * @param amount defines the interpolation factor
  2662. * @returns a new Vector2
  2663. */
  2664. Vector2.Lerp = function (start, end, amount) {
  2665. var x = start.x + ((end.x - start.x) * amount);
  2666. var y = start.y + ((end.y - start.y) * amount);
  2667. return new Vector2(x, y);
  2668. };
  2669. /**
  2670. * Gets the dot product of the vector "left" and the vector "right"
  2671. * @param left defines first vector
  2672. * @param right defines second vector
  2673. * @returns the dot product (float)
  2674. */
  2675. Vector2.Dot = function (left, right) {
  2676. return left.x * right.x + left.y * right.y;
  2677. };
  2678. /**
  2679. * Returns a new Vector2 equal to the normalized given vector
  2680. * @param vector defines the vector to normalize
  2681. * @returns a new Vector2
  2682. */
  2683. Vector2.Normalize = function (vector) {
  2684. var newVector = vector.clone();
  2685. newVector.normalize();
  2686. return newVector;
  2687. };
  2688. /**
  2689. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2690. * @param left defines 1st vector
  2691. * @param right defines 2nd vector
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Minimize = function (left, right) {
  2695. var x = (left.x < right.x) ? left.x : right.x;
  2696. var y = (left.y < right.y) ? left.y : right.y;
  2697. return new Vector2(x, y);
  2698. };
  2699. /**
  2700. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2701. * @param left defines 1st vector
  2702. * @param right defines 2nd vector
  2703. * @returns a new Vector2
  2704. */
  2705. Vector2.Maximize = function (left, right) {
  2706. var x = (left.x > right.x) ? left.x : right.x;
  2707. var y = (left.y > right.y) ? left.y : right.y;
  2708. return new Vector2(x, y);
  2709. };
  2710. /**
  2711. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2712. * @param vector defines the vector to transform
  2713. * @param transformation defines the matrix to apply
  2714. * @returns a new Vector2
  2715. */
  2716. Vector2.Transform = function (vector, transformation) {
  2717. var r = Vector2.Zero();
  2718. Vector2.TransformToRef(vector, transformation, r);
  2719. return r;
  2720. };
  2721. /**
  2722. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2723. * @param vector defines the vector to transform
  2724. * @param transformation defines the matrix to apply
  2725. * @param result defines the target vector
  2726. */
  2727. Vector2.TransformToRef = function (vector, transformation, result) {
  2728. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2729. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2730. result.x = x;
  2731. result.y = y;
  2732. };
  2733. /**
  2734. * Determines if a given vector is included in a triangle
  2735. * @param p defines the vector to test
  2736. * @param p0 defines 1st triangle point
  2737. * @param p1 defines 2nd triangle point
  2738. * @param p2 defines 3rd triangle point
  2739. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2740. */
  2741. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2742. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2743. var sign = a < 0 ? -1 : 1;
  2744. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2745. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2746. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2747. };
  2748. /**
  2749. * Gets the distance between the vectors "value1" and "value2"
  2750. * @param value1 defines first vector
  2751. * @param value2 defines second vector
  2752. * @returns the distance between vectors
  2753. */
  2754. Vector2.Distance = function (value1, value2) {
  2755. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2756. };
  2757. /**
  2758. * Returns the squared distance between the vectors "value1" and "value2"
  2759. * @param value1 defines first vector
  2760. * @param value2 defines second vector
  2761. * @returns the squared distance between vectors
  2762. */
  2763. Vector2.DistanceSquared = function (value1, value2) {
  2764. var x = value1.x - value2.x;
  2765. var y = value1.y - value2.y;
  2766. return (x * x) + (y * y);
  2767. };
  2768. /**
  2769. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2770. * @param value1 defines first vector
  2771. * @param value2 defines second vector
  2772. * @returns a new Vector2
  2773. */
  2774. Vector2.Center = function (value1, value2) {
  2775. var center = value1.add(value2);
  2776. center.scaleInPlace(0.5);
  2777. return center;
  2778. };
  2779. /**
  2780. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2781. * @param p defines the middle point
  2782. * @param segA defines one point of the segment
  2783. * @param segB defines the other point of the segment
  2784. * @returns the shortest distance
  2785. */
  2786. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2787. var l2 = Vector2.DistanceSquared(segA, segB);
  2788. if (l2 === 0.0) {
  2789. return Vector2.Distance(p, segA);
  2790. }
  2791. var v = segB.subtract(segA);
  2792. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2793. var proj = segA.add(v.multiplyByFloats(t, t));
  2794. return Vector2.Distance(p, proj);
  2795. };
  2796. return Vector2;
  2797. }());
  2798. BABYLON.Vector2 = Vector2;
  2799. /**
  2800. * Classed used to store (x,y,z) vector representation
  2801. * A Vector3 is the main object used in 3D geometry
  2802. * It can represent etiher the coordinates of a point the space, either a direction
  2803. * Reminder: Babylon.js uses a left handed forward facing system
  2804. */
  2805. var Vector3 = /** @class */ (function () {
  2806. /**
  2807. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2808. * @param x defines the first coordinates (on X axis)
  2809. * @param y defines the second coordinates (on Y axis)
  2810. * @param z defines the third coordinates (on Z axis)
  2811. */
  2812. function Vector3(
  2813. /**
  2814. * Defines the first coordinates (on X axis)
  2815. */
  2816. x,
  2817. /**
  2818. * Defines the second coordinates (on Y axis)
  2819. */
  2820. y,
  2821. /**
  2822. * Defines the third coordinates (on Z axis)
  2823. */
  2824. z) {
  2825. if (x === void 0) { x = 0; }
  2826. if (y === void 0) { y = 0; }
  2827. if (z === void 0) { z = 0; }
  2828. this.x = x;
  2829. this.y = y;
  2830. this.z = z;
  2831. }
  2832. /**
  2833. * Creates a string representation of the Vector3
  2834. * @returns a string with the Vector3 coordinates.
  2835. */
  2836. Vector3.prototype.toString = function () {
  2837. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2838. };
  2839. /**
  2840. * Gets the class name
  2841. * @returns the string "Vector3"
  2842. */
  2843. Vector3.prototype.getClassName = function () {
  2844. return "Vector3";
  2845. };
  2846. /**
  2847. * Creates the Vector3 hash code
  2848. * @returns a number which tends to be unique between Vector3 instances
  2849. */
  2850. Vector3.prototype.getHashCode = function () {
  2851. var hash = this.x || 0;
  2852. hash = (hash * 397) ^ (this.y || 0);
  2853. hash = (hash * 397) ^ (this.z || 0);
  2854. return hash;
  2855. };
  2856. // Operators
  2857. /**
  2858. * Creates an array containing three elements : the coordinates of the Vector3
  2859. * @returns a new array of numbers
  2860. */
  2861. Vector3.prototype.asArray = function () {
  2862. var result = [];
  2863. this.toArray(result, 0);
  2864. return result;
  2865. };
  2866. /**
  2867. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2868. * @param array defines the destination array
  2869. * @param index defines the offset in the destination array
  2870. * @returns the current Vector3
  2871. */
  2872. Vector3.prototype.toArray = function (array, index) {
  2873. if (index === void 0) { index = 0; }
  2874. array[index] = this.x;
  2875. array[index + 1] = this.y;
  2876. array[index + 2] = this.z;
  2877. return this;
  2878. };
  2879. /**
  2880. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2881. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2882. */
  2883. Vector3.prototype.toQuaternion = function () {
  2884. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2885. };
  2886. /**
  2887. * Adds the given vector to the current Vector3
  2888. * @param otherVector defines the second operand
  2889. * @returns the current updated Vector3
  2890. */
  2891. Vector3.prototype.addInPlace = function (otherVector) {
  2892. this.x += otherVector.x;
  2893. this.y += otherVector.y;
  2894. this.z += otherVector.z;
  2895. return this;
  2896. };
  2897. /**
  2898. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2899. * @param otherVector defines the second operand
  2900. * @returns the resulting Vector3
  2901. */
  2902. Vector3.prototype.add = function (otherVector) {
  2903. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2904. };
  2905. /**
  2906. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2907. * @param otherVector defines the second operand
  2908. * @param result defines the Vector3 object where to store the result
  2909. * @returns the current Vector3
  2910. */
  2911. Vector3.prototype.addToRef = function (otherVector, result) {
  2912. result.x = this.x + otherVector.x;
  2913. result.y = this.y + otherVector.y;
  2914. result.z = this.z + otherVector.z;
  2915. return this;
  2916. };
  2917. /**
  2918. * Subtract the given vector from the current Vector3
  2919. * @param otherVector defines the second operand
  2920. * @returns the current updated Vector3
  2921. */
  2922. Vector3.prototype.subtractInPlace = function (otherVector) {
  2923. this.x -= otherVector.x;
  2924. this.y -= otherVector.y;
  2925. this.z -= otherVector.z;
  2926. return this;
  2927. };
  2928. /**
  2929. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2930. * @param otherVector defines the second operand
  2931. * @returns the resulting Vector3
  2932. */
  2933. Vector3.prototype.subtract = function (otherVector) {
  2934. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2935. };
  2936. /**
  2937. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2938. * @param otherVector defines the second operand
  2939. * @param result defines the Vector3 object where to store the result
  2940. * @returns the current Vector3
  2941. */
  2942. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2943. result.x = this.x - otherVector.x;
  2944. result.y = this.y - otherVector.y;
  2945. result.z = this.z - otherVector.z;
  2946. return this;
  2947. };
  2948. /**
  2949. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2950. * @param x defines the x coordinate of the operand
  2951. * @param y defines the y coordinate of the operand
  2952. * @param z defines the z coordinate of the operand
  2953. * @returns the resulting Vector3
  2954. */
  2955. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2956. return new Vector3(this.x - x, this.y - y, this.z - z);
  2957. };
  2958. /**
  2959. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2960. * @param x defines the x coordinate of the operand
  2961. * @param y defines the y coordinate of the operand
  2962. * @param z defines the z coordinate of the operand
  2963. * @param result defines the Vector3 object where to store the result
  2964. * @returns the current Vector3
  2965. */
  2966. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2967. result.x = this.x - x;
  2968. result.y = this.y - y;
  2969. result.z = this.z - z;
  2970. return this;
  2971. };
  2972. /**
  2973. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2974. * @returns a new Vector3
  2975. */
  2976. Vector3.prototype.negate = function () {
  2977. return new Vector3(-this.x, -this.y, -this.z);
  2978. };
  2979. /**
  2980. * Multiplies the Vector3 coordinates by the float "scale"
  2981. * @param scale defines the multiplier factor
  2982. * @returns the current updated Vector3
  2983. */
  2984. Vector3.prototype.scaleInPlace = function (scale) {
  2985. this.x *= scale;
  2986. this.y *= scale;
  2987. this.z *= scale;
  2988. return this;
  2989. };
  2990. /**
  2991. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2992. * @param scale defines the multiplier factor
  2993. * @returns a new Vector3
  2994. */
  2995. Vector3.prototype.scale = function (scale) {
  2996. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2997. };
  2998. /**
  2999. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3000. * @param scale defines the multiplier factor
  3001. * @param result defines the Vector3 object where to store the result
  3002. * @returns the current Vector3
  3003. */
  3004. Vector3.prototype.scaleToRef = function (scale, result) {
  3005. result.x = this.x * scale;
  3006. result.y = this.y * scale;
  3007. result.z = this.z * scale;
  3008. return this;
  3009. };
  3010. /**
  3011. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3012. * @param scale defines the scale factor
  3013. * @param result defines the Vector3 object where to store the result
  3014. * @returns the unmodified current Vector3
  3015. */
  3016. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3017. result.x += this.x * scale;
  3018. result.y += this.y * scale;
  3019. result.z += this.z * scale;
  3020. return this;
  3021. };
  3022. /**
  3023. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3024. * @param otherVector defines the second operand
  3025. * @returns true if both vectors are equals
  3026. */
  3027. Vector3.prototype.equals = function (otherVector) {
  3028. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3029. };
  3030. /**
  3031. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3032. * @param otherVector defines the second operand
  3033. * @param epsilon defines the minimal distance to define values as equals
  3034. * @returns true if both vectors are distant less than epsilon
  3035. */
  3036. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3037. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3038. 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);
  3039. };
  3040. /**
  3041. * Returns true if the current Vector3 coordinates equals the given floats
  3042. * @param x defines the x coordinate of the operand
  3043. * @param y defines the y coordinate of the operand
  3044. * @param z defines the z coordinate of the operand
  3045. * @returns true if both vectors are equals
  3046. */
  3047. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3048. return this.x === x && this.y === y && this.z === z;
  3049. };
  3050. /**
  3051. * Multiplies the current Vector3 coordinates by the given ones
  3052. * @param otherVector defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3056. this.x *= otherVector.x;
  3057. this.y *= otherVector.y;
  3058. this.z *= otherVector.z;
  3059. return this;
  3060. };
  3061. /**
  3062. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3063. * @param otherVector defines the second operand
  3064. * @returns the new Vector3
  3065. */
  3066. Vector3.prototype.multiply = function (otherVector) {
  3067. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3068. };
  3069. /**
  3070. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3071. * @param otherVector defines the second operand
  3072. * @param result defines the Vector3 object where to store the result
  3073. * @returns the current Vector3
  3074. */
  3075. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3076. result.x = this.x * otherVector.x;
  3077. result.y = this.y * otherVector.y;
  3078. result.z = this.z * otherVector.z;
  3079. return this;
  3080. };
  3081. /**
  3082. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3083. * @param x defines the x coordinate of the operand
  3084. * @param y defines the y coordinate of the operand
  3085. * @param z defines the z coordinate of the operand
  3086. * @returns the new Vector3
  3087. */
  3088. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3089. return new Vector3(this.x * x, this.y * y, this.z * z);
  3090. };
  3091. /**
  3092. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3093. * @param otherVector defines the second operand
  3094. * @returns the new Vector3
  3095. */
  3096. Vector3.prototype.divide = function (otherVector) {
  3097. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3098. };
  3099. /**
  3100. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3101. * @param otherVector defines the second operand
  3102. * @param result defines the Vector3 object where to store the result
  3103. * @returns the current Vector3
  3104. */
  3105. Vector3.prototype.divideToRef = function (otherVector, result) {
  3106. result.x = this.x / otherVector.x;
  3107. result.y = this.y / otherVector.y;
  3108. result.z = this.z / otherVector.z;
  3109. return this;
  3110. };
  3111. /**
  3112. * Divides the current Vector3 coordinates by the given ones.
  3113. * @param otherVector defines the second operand
  3114. * @returns the current updated Vector3
  3115. */
  3116. Vector3.prototype.divideInPlace = function (otherVector) {
  3117. return this.divideToRef(otherVector, this);
  3118. };
  3119. /**
  3120. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3121. * @param other defines the second operand
  3122. * @returns the current updated Vector3
  3123. */
  3124. Vector3.prototype.minimizeInPlace = function (other) {
  3125. if (other.x < this.x)
  3126. this.x = other.x;
  3127. if (other.y < this.y)
  3128. this.y = other.y;
  3129. if (other.z < this.z)
  3130. this.z = other.z;
  3131. return this;
  3132. };
  3133. /**
  3134. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3135. * @param other defines the second operand
  3136. * @returns the current updated Vector3
  3137. */
  3138. Vector3.prototype.maximizeInPlace = function (other) {
  3139. if (other.x > this.x)
  3140. this.x = other.x;
  3141. if (other.y > this.y)
  3142. this.y = other.y;
  3143. if (other.z > this.z)
  3144. this.z = other.z;
  3145. return this;
  3146. };
  3147. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3148. /**
  3149. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3150. */
  3151. get: function () {
  3152. var absX = Math.abs(this.x);
  3153. var absY = Math.abs(this.y);
  3154. if (absX !== absY) {
  3155. return true;
  3156. }
  3157. var absZ = Math.abs(this.z);
  3158. if (absX !== absZ) {
  3159. return true;
  3160. }
  3161. if (absY !== absZ) {
  3162. return true;
  3163. }
  3164. return false;
  3165. },
  3166. enumerable: true,
  3167. configurable: true
  3168. });
  3169. /**
  3170. * Gets a new Vector3 from current Vector3 floored values
  3171. * @returns a new Vector3
  3172. */
  3173. Vector3.prototype.floor = function () {
  3174. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3175. };
  3176. /**
  3177. * Gets a new Vector3 from current Vector3 floored values
  3178. * @returns a new Vector3
  3179. */
  3180. Vector3.prototype.fract = function () {
  3181. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3182. };
  3183. // Properties
  3184. /**
  3185. * Gets the length of the Vector3
  3186. * @returns the length of the Vecto3
  3187. */
  3188. Vector3.prototype.length = function () {
  3189. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3190. };
  3191. /**
  3192. * Gets the squared length of the Vector3
  3193. * @returns squared length of the Vector3
  3194. */
  3195. Vector3.prototype.lengthSquared = function () {
  3196. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3197. };
  3198. /**
  3199. * Normalize the current Vector3.
  3200. * Please note that this is an in place operation.
  3201. * @returns the current updated Vector3
  3202. */
  3203. Vector3.prototype.normalize = function () {
  3204. var len = this.length();
  3205. if (len === 0 || len === 1.0)
  3206. return this;
  3207. var num = 1.0 / len;
  3208. this.x *= num;
  3209. this.y *= num;
  3210. this.z *= num;
  3211. return this;
  3212. };
  3213. /**
  3214. * Normalize the current Vector3 to a new vector
  3215. * @returns the new Vector3
  3216. */
  3217. Vector3.prototype.normalizeToNew = function () {
  3218. var normalized = new Vector3(0, 0, 0);
  3219. this.normalizeToRef(normalized);
  3220. return normalized;
  3221. };
  3222. /**
  3223. * Normalize the current Vector3 to the reference
  3224. * @param reference define the Vector3 to update
  3225. * @returns the updated Vector3
  3226. */
  3227. Vector3.prototype.normalizeToRef = function (reference) {
  3228. var len = this.length();
  3229. if (len === 0 || len === 1.0) {
  3230. reference.set(this.x, this.y, this.z);
  3231. return reference;
  3232. }
  3233. var scale = 1.0 / len;
  3234. this.scaleToRef(scale, reference);
  3235. return reference;
  3236. };
  3237. /**
  3238. * Creates a new Vector3 copied from the current Vector3
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.prototype.clone = function () {
  3242. return new Vector3(this.x, this.y, this.z);
  3243. };
  3244. /**
  3245. * Copies the given vector coordinates to the current Vector3 ones
  3246. * @param source defines the source Vector3
  3247. * @returns the current updated Vector3
  3248. */
  3249. Vector3.prototype.copyFrom = function (source) {
  3250. this.x = source.x;
  3251. this.y = source.y;
  3252. this.z = source.z;
  3253. return this;
  3254. };
  3255. /**
  3256. * Copies the given floats to the current Vector3 coordinates
  3257. * @param x defines the x coordinate of the operand
  3258. * @param y defines the y coordinate of the operand
  3259. * @param z defines the z coordinate of the operand
  3260. * @returns the current updated Vector3
  3261. */
  3262. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3263. this.x = x;
  3264. this.y = y;
  3265. this.z = z;
  3266. return this;
  3267. };
  3268. /**
  3269. * Copies the given floats to the current Vector3 coordinates
  3270. * @param x defines the x coordinate of the operand
  3271. * @param y defines the y coordinate of the operand
  3272. * @param z defines the z coordinate of the operand
  3273. * @returns the current updated Vector3
  3274. */
  3275. Vector3.prototype.set = function (x, y, z) {
  3276. return this.copyFromFloats(x, y, z);
  3277. };
  3278. // Statics
  3279. /**
  3280. * Get the clip factor between two vectors
  3281. * @param vector0 defines the first operand
  3282. * @param vector1 defines the second operand
  3283. * @param axis defines the axis to use
  3284. * @param size defines the size along the axis
  3285. * @returns the clip factor
  3286. */
  3287. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3288. var d0 = Vector3.Dot(vector0, axis) - size;
  3289. var d1 = Vector3.Dot(vector1, axis) - size;
  3290. var s = d0 / (d0 - d1);
  3291. return s;
  3292. };
  3293. /**
  3294. * Get angle between two vectors
  3295. * @param vector0 angle between vector0 and vector1
  3296. * @param vector1 angle between vector0 and vector1
  3297. * @param normal direction of the normal
  3298. * @return the angle between vector0 and vector1
  3299. */
  3300. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3301. var v0 = vector0.clone().normalize();
  3302. var v1 = vector1.clone().normalize();
  3303. var dot = Vector3.Dot(v0, v1);
  3304. var n = Vector3.Cross(v0, v1);
  3305. if (Vector3.Dot(n, normal) > 0) {
  3306. return Math.acos(dot);
  3307. }
  3308. return -Math.acos(dot);
  3309. };
  3310. /**
  3311. * Returns a new Vector3 set from the index "offset" of the given array
  3312. * @param array defines the source array
  3313. * @param offset defines the offset in the source array
  3314. * @returns the new Vector3
  3315. */
  3316. Vector3.FromArray = function (array, offset) {
  3317. if (!offset) {
  3318. offset = 0;
  3319. }
  3320. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3321. };
  3322. /**
  3323. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3324. * This function is deprecated. Use FromArray instead
  3325. * @param array defines the source array
  3326. * @param offset defines the offset in the source array
  3327. * @returns the new Vector3
  3328. */
  3329. Vector3.FromFloatArray = function (array, offset) {
  3330. return Vector3.FromArray(array, offset);
  3331. };
  3332. /**
  3333. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3334. * @param array defines the source array
  3335. * @param offset defines the offset in the source array
  3336. * @param result defines the Vector3 where to store the result
  3337. */
  3338. Vector3.FromArrayToRef = function (array, offset, result) {
  3339. result.x = array[offset];
  3340. result.y = array[offset + 1];
  3341. result.z = array[offset + 2];
  3342. };
  3343. /**
  3344. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3345. * This function is deprecated. Use FromArrayToRef instead.
  3346. * @param array defines the source array
  3347. * @param offset defines the offset in the source array
  3348. * @param result defines the Vector3 where to store the result
  3349. */
  3350. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3351. return Vector3.FromArrayToRef(array, offset, result);
  3352. };
  3353. /**
  3354. * Sets the given vector "result" with the given floats.
  3355. * @param x defines the x coordinate of the source
  3356. * @param y defines the y coordinate of the source
  3357. * @param z defines the z coordinate of the source
  3358. * @param result defines the Vector3 where to store the result
  3359. */
  3360. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3361. result.x = x;
  3362. result.y = y;
  3363. result.z = z;
  3364. };
  3365. /**
  3366. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3367. * @returns a new empty Vector3
  3368. */
  3369. Vector3.Zero = function () {
  3370. return new Vector3(0.0, 0.0, 0.0);
  3371. };
  3372. /**
  3373. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3374. * @returns a new unit Vector3
  3375. */
  3376. Vector3.One = function () {
  3377. return new Vector3(1.0, 1.0, 1.0);
  3378. };
  3379. /**
  3380. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3381. * @returns a new up Vector3
  3382. */
  3383. Vector3.Up = function () {
  3384. return new Vector3(0.0, 1.0, 0.0);
  3385. };
  3386. /**
  3387. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3388. * @returns a new down Vector3
  3389. */
  3390. Vector3.Down = function () {
  3391. return new Vector3(0.0, -1.0, 0.0);
  3392. };
  3393. /**
  3394. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3395. * @returns a new forward Vector3
  3396. */
  3397. Vector3.Forward = function () {
  3398. return new Vector3(0.0, 0.0, 1.0);
  3399. };
  3400. /**
  3401. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3402. * @returns a new forward Vector3
  3403. */
  3404. Vector3.Backward = function () {
  3405. return new Vector3(0.0, 0.0, -1.0);
  3406. };
  3407. /**
  3408. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3409. * @returns a new right Vector3
  3410. */
  3411. Vector3.Right = function () {
  3412. return new Vector3(1.0, 0.0, 0.0);
  3413. };
  3414. /**
  3415. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3416. * @returns a new left Vector3
  3417. */
  3418. Vector3.Left = function () {
  3419. return new Vector3(-1.0, 0.0, 0.0);
  3420. };
  3421. /**
  3422. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3423. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3424. * @param vector defines the Vector3 to transform
  3425. * @param transformation defines the transformation matrix
  3426. * @returns the transformed Vector3
  3427. */
  3428. Vector3.TransformCoordinates = function (vector, transformation) {
  3429. var result = Vector3.Zero();
  3430. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3431. return result;
  3432. };
  3433. /**
  3434. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3435. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3436. * @param vector defines the Vector3 to transform
  3437. * @param transformation defines the transformation matrix
  3438. * @param result defines the Vector3 where to store the result
  3439. */
  3440. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3441. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3442. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3443. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3444. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3445. result.x = x / w;
  3446. result.y = y / w;
  3447. result.z = z / w;
  3448. };
  3449. /**
  3450. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3451. * This method computes tranformed coordinates only, not transformed direction vectors
  3452. * @param x define the x coordinate of the source vector
  3453. * @param y define the y coordinate of the source vector
  3454. * @param z define the z coordinate of the source vector
  3455. * @param transformation defines the transformation matrix
  3456. * @param result defines the Vector3 where to store the result
  3457. */
  3458. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3459. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3460. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3461. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3462. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3463. result.x = rx / rw;
  3464. result.y = ry / rw;
  3465. result.z = rz / rw;
  3466. };
  3467. /**
  3468. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3469. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3470. * @param vector defines the Vector3 to transform
  3471. * @param transformation defines the transformation matrix
  3472. * @returns the new Vector3
  3473. */
  3474. Vector3.TransformNormal = function (vector, transformation) {
  3475. var result = Vector3.Zero();
  3476. Vector3.TransformNormalToRef(vector, transformation, result);
  3477. return result;
  3478. };
  3479. /**
  3480. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3481. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3482. * @param vector defines the Vector3 to transform
  3483. * @param transformation defines the transformation matrix
  3484. * @param result defines the Vector3 where to store the result
  3485. */
  3486. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3487. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3488. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3489. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3490. result.x = x;
  3491. result.y = y;
  3492. result.z = z;
  3493. };
  3494. /**
  3495. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3496. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3497. * @param x define the x coordinate of the source vector
  3498. * @param y define the y coordinate of the source vector
  3499. * @param z define the z coordinate of the source vector
  3500. * @param transformation defines the transformation matrix
  3501. * @param result defines the Vector3 where to store the result
  3502. */
  3503. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3504. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3505. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3506. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3507. };
  3508. /**
  3509. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3510. * @param value1 defines the first control point
  3511. * @param value2 defines the second control point
  3512. * @param value3 defines the third control point
  3513. * @param value4 defines the fourth control point
  3514. * @param amount defines the amount on the spline to use
  3515. * @returns the new Vector3
  3516. */
  3517. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3518. var squared = amount * amount;
  3519. var cubed = amount * squared;
  3520. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3521. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3522. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3523. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3524. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3525. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3526. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3527. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3528. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3529. return new Vector3(x, y, z);
  3530. };
  3531. /**
  3532. * 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"
  3533. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3534. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3535. * @param value defines the current value
  3536. * @param min defines the lower range value
  3537. * @param max defines the upper range value
  3538. * @returns the new Vector3
  3539. */
  3540. Vector3.Clamp = function (value, min, max) {
  3541. var x = value.x;
  3542. x = (x > max.x) ? max.x : x;
  3543. x = (x < min.x) ? min.x : x;
  3544. var y = value.y;
  3545. y = (y > max.y) ? max.y : y;
  3546. y = (y < min.y) ? min.y : y;
  3547. var z = value.z;
  3548. z = (z > max.z) ? max.z : z;
  3549. z = (z < min.z) ? min.z : z;
  3550. return new Vector3(x, y, z);
  3551. };
  3552. /**
  3553. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3554. * @param value1 defines the first control point
  3555. * @param tangent1 defines the first tangent vector
  3556. * @param value2 defines the second control point
  3557. * @param tangent2 defines the second tangent vector
  3558. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3559. * @returns the new Vector3
  3560. */
  3561. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3562. var squared = amount * amount;
  3563. var cubed = amount * squared;
  3564. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3565. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3566. var part3 = (cubed - (2.0 * squared)) + amount;
  3567. var part4 = cubed - squared;
  3568. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3569. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3570. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3571. return new Vector3(x, y, z);
  3572. };
  3573. /**
  3574. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3575. * @param start defines the start value
  3576. * @param end defines the end value
  3577. * @param amount max defines amount between both (between 0 and 1)
  3578. * @returns the new Vector3
  3579. */
  3580. Vector3.Lerp = function (start, end, amount) {
  3581. var result = new Vector3(0, 0, 0);
  3582. Vector3.LerpToRef(start, end, amount, result);
  3583. return result;
  3584. };
  3585. /**
  3586. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3587. * @param start defines the start value
  3588. * @param end defines the end value
  3589. * @param amount max defines amount between both (between 0 and 1)
  3590. * @param result defines the Vector3 where to store the result
  3591. */
  3592. Vector3.LerpToRef = function (start, end, amount, result) {
  3593. result.x = start.x + ((end.x - start.x) * amount);
  3594. result.y = start.y + ((end.y - start.y) * amount);
  3595. result.z = start.z + ((end.z - start.z) * amount);
  3596. };
  3597. /**
  3598. * Returns the dot product (float) between the vectors "left" and "right"
  3599. * @param left defines the left operand
  3600. * @param right defines the right operand
  3601. * @returns the dot product
  3602. */
  3603. Vector3.Dot = function (left, right) {
  3604. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3605. };
  3606. /**
  3607. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3608. * The cross product is then orthogonal to both "left" and "right"
  3609. * @param left defines the left operand
  3610. * @param right defines the right operand
  3611. * @returns the cross product
  3612. */
  3613. Vector3.Cross = function (left, right) {
  3614. var result = Vector3.Zero();
  3615. Vector3.CrossToRef(left, right, result);
  3616. return result;
  3617. };
  3618. /**
  3619. * Sets the given vector "result" with the cross product of "left" and "right"
  3620. * The cross product is then orthogonal to both "left" and "right"
  3621. * @param left defines the left operand
  3622. * @param right defines the right operand
  3623. * @param result defines the Vector3 where to store the result
  3624. */
  3625. Vector3.CrossToRef = function (left, right, result) {
  3626. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3627. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3628. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3629. result.copyFrom(MathTmp.Vector3[0]);
  3630. };
  3631. /**
  3632. * Returns a new Vector3 as the normalization of the given vector
  3633. * @param vector defines the Vector3 to normalize
  3634. * @returns the new Vector3
  3635. */
  3636. Vector3.Normalize = function (vector) {
  3637. var result = Vector3.Zero();
  3638. Vector3.NormalizeToRef(vector, result);
  3639. return result;
  3640. };
  3641. /**
  3642. * Sets the given vector "result" with the normalization of the given first vector
  3643. * @param vector defines the Vector3 to normalize
  3644. * @param result defines the Vector3 where to store the result
  3645. */
  3646. Vector3.NormalizeToRef = function (vector, result) {
  3647. result.copyFrom(vector);
  3648. result.normalize();
  3649. };
  3650. /**
  3651. * Project a Vector3 onto screen space
  3652. * @param vector defines the Vector3 to project
  3653. * @param world defines the world matrix to use
  3654. * @param transform defines the transform (view x projection) matrix to use
  3655. * @param viewport defines the screen viewport to use
  3656. * @returns the new Vector3
  3657. */
  3658. Vector3.Project = function (vector, world, transform, viewport) {
  3659. var cw = viewport.width;
  3660. var ch = viewport.height;
  3661. var cx = viewport.x;
  3662. var cy = viewport.y;
  3663. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3664. 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);
  3665. var matrix = MathTmp.Matrix[0];
  3666. world.multiplyToRef(transform, matrix);
  3667. matrix.multiplyToRef(viewportMatrix, matrix);
  3668. return Vector3.TransformCoordinates(vector, matrix);
  3669. };
  3670. /**
  3671. * Unproject from screen space to object space
  3672. * @param source defines the screen space Vector3 to use
  3673. * @param viewportWidth defines the current width of the viewport
  3674. * @param viewportHeight defines the current height of the viewport
  3675. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3676. * @param transform defines the transform (view x projection) matrix to use
  3677. * @returns the new Vector3
  3678. */
  3679. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3680. var matrix = MathTmp.Matrix[0];
  3681. world.multiplyToRef(transform, matrix);
  3682. matrix.invert();
  3683. source.x = source.x / viewportWidth * 2 - 1;
  3684. source.y = -(source.y / viewportHeight * 2 - 1);
  3685. var vector = Vector3.TransformCoordinates(source, matrix);
  3686. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3687. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3688. vector = vector.scale(1.0 / num);
  3689. }
  3690. return vector;
  3691. };
  3692. /**
  3693. * Unproject from screen space to object space
  3694. * @param source defines the screen space Vector3 to use
  3695. * @param viewportWidth defines the current width of the viewport
  3696. * @param viewportHeight defines the current height of the viewport
  3697. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3698. * @param view defines the view matrix to use
  3699. * @param projection defines the projection matrix to use
  3700. * @returns the new Vector3
  3701. */
  3702. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3703. var result = Vector3.Zero();
  3704. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3705. return result;
  3706. };
  3707. /**
  3708. * Unproject from screen space to object space
  3709. * @param source defines the screen space Vector3 to use
  3710. * @param viewportWidth defines the current width of the viewport
  3711. * @param viewportHeight defines the current height of the viewport
  3712. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3713. * @param view defines the view matrix to use
  3714. * @param projection defines the projection matrix to use
  3715. * @param result defines the Vector3 where to store the result
  3716. */
  3717. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3718. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3719. };
  3720. /**
  3721. * Unproject from screen space to object space
  3722. * @param sourceX defines the screen space x coordinate to use
  3723. * @param sourceY defines the screen space y coordinate to use
  3724. * @param sourceZ defines the screen space z coordinate to use
  3725. * @param viewportWidth defines the current width of the viewport
  3726. * @param viewportHeight defines the current height of the viewport
  3727. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3728. * @param view defines the view matrix to use
  3729. * @param projection defines the projection matrix to use
  3730. * @param result defines the Vector3 where to store the result
  3731. */
  3732. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3733. var matrix = MathTmp.Matrix[0];
  3734. world.multiplyToRef(view, matrix);
  3735. matrix.multiplyToRef(projection, matrix);
  3736. matrix.invert();
  3737. var screenSource = MathTmp.Vector3[0];
  3738. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3739. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3740. screenSource.z = 2 * sourceZ - 1.0;
  3741. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3742. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3743. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3744. result.scaleInPlace(1.0 / num);
  3745. }
  3746. };
  3747. /**
  3748. * Gets the minimal coordinate values between two Vector3
  3749. * @param left defines the first operand
  3750. * @param right defines the second operand
  3751. * @returns the new Vector3
  3752. */
  3753. Vector3.Minimize = function (left, right) {
  3754. var min = left.clone();
  3755. min.minimizeInPlace(right);
  3756. return min;
  3757. };
  3758. /**
  3759. * Gets the maximal coordinate values between two Vector3
  3760. * @param left defines the first operand
  3761. * @param right defines the second operand
  3762. * @returns the new Vector3
  3763. */
  3764. Vector3.Maximize = function (left, right) {
  3765. var max = left.clone();
  3766. max.maximizeInPlace(right);
  3767. return max;
  3768. };
  3769. /**
  3770. * Returns the distance between the vectors "value1" and "value2"
  3771. * @param value1 defines the first operand
  3772. * @param value2 defines the second operand
  3773. * @returns the distance
  3774. */
  3775. Vector3.Distance = function (value1, value2) {
  3776. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3777. };
  3778. /**
  3779. * Returns the squared distance between the vectors "value1" and "value2"
  3780. * @param value1 defines the first operand
  3781. * @param value2 defines the second operand
  3782. * @returns the squared distance
  3783. */
  3784. Vector3.DistanceSquared = function (value1, value2) {
  3785. var x = value1.x - value2.x;
  3786. var y = value1.y - value2.y;
  3787. var z = value1.z - value2.z;
  3788. return (x * x) + (y * y) + (z * z);
  3789. };
  3790. /**
  3791. * Returns a new Vector3 located at the center between "value1" and "value2"
  3792. * @param value1 defines the first operand
  3793. * @param value2 defines the second operand
  3794. * @returns the new Vector3
  3795. */
  3796. Vector3.Center = function (value1, value2) {
  3797. var center = value1.add(value2);
  3798. center.scaleInPlace(0.5);
  3799. return center;
  3800. };
  3801. /**
  3802. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3803. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3804. * to something in order to rotate it from its local system to the given target system
  3805. * Note: axis1, axis2 and axis3 are normalized during this operation
  3806. * @param axis1 defines the first axis
  3807. * @param axis2 defines the second axis
  3808. * @param axis3 defines the third axis
  3809. * @returns a new Vector3
  3810. */
  3811. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3812. var rotation = Vector3.Zero();
  3813. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3814. return rotation;
  3815. };
  3816. /**
  3817. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3818. * @param axis1 defines the first axis
  3819. * @param axis2 defines the second axis
  3820. * @param axis3 defines the third axis
  3821. * @param ref defines the Vector3 where to store the result
  3822. */
  3823. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3824. var quat = MathTmp.Quaternion[0];
  3825. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3826. quat.toEulerAnglesToRef(ref);
  3827. };
  3828. return Vector3;
  3829. }());
  3830. BABYLON.Vector3 = Vector3;
  3831. //Vector4 class created for EulerAngle class conversion to Quaternion
  3832. var Vector4 = /** @class */ (function () {
  3833. /**
  3834. * Creates a Vector4 object from the given floats.
  3835. */
  3836. function Vector4(x, y, z, w) {
  3837. this.x = x;
  3838. this.y = y;
  3839. this.z = z;
  3840. this.w = w;
  3841. }
  3842. /**
  3843. * Returns the string with the Vector4 coordinates.
  3844. */
  3845. Vector4.prototype.toString = function () {
  3846. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3847. };
  3848. /**
  3849. * Returns the string "Vector4".
  3850. */
  3851. Vector4.prototype.getClassName = function () {
  3852. return "Vector4";
  3853. };
  3854. /**
  3855. * Returns the Vector4 hash code.
  3856. */
  3857. Vector4.prototype.getHashCode = function () {
  3858. var hash = this.x || 0;
  3859. hash = (hash * 397) ^ (this.y || 0);
  3860. hash = (hash * 397) ^ (this.z || 0);
  3861. hash = (hash * 397) ^ (this.w || 0);
  3862. return hash;
  3863. };
  3864. // Operators
  3865. /**
  3866. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3867. */
  3868. Vector4.prototype.asArray = function () {
  3869. var result = new Array();
  3870. this.toArray(result, 0);
  3871. return result;
  3872. };
  3873. /**
  3874. * Populates the given array from the given index with the Vector4 coordinates.
  3875. * Returns the Vector4.
  3876. */
  3877. Vector4.prototype.toArray = function (array, index) {
  3878. if (index === undefined) {
  3879. index = 0;
  3880. }
  3881. array[index] = this.x;
  3882. array[index + 1] = this.y;
  3883. array[index + 2] = this.z;
  3884. array[index + 3] = this.w;
  3885. return this;
  3886. };
  3887. /**
  3888. * Adds the given vector to the current Vector4.
  3889. * Returns the updated Vector4.
  3890. */
  3891. Vector4.prototype.addInPlace = 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 as the result of the addition of the current Vector4 and the given one.
  3900. */
  3901. Vector4.prototype.add = 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. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3906. * Returns the current Vector4.
  3907. */
  3908. Vector4.prototype.addToRef = 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. * Subtract in place the given vector from the current Vector4.
  3917. * Returns the updated Vector4.
  3918. */
  3919. Vector4.prototype.subtractInPlace = function (otherVector) {
  3920. this.x -= otherVector.x;
  3921. this.y -= otherVector.y;
  3922. this.z -= otherVector.z;
  3923. this.w -= otherVector.w;
  3924. return this;
  3925. };
  3926. /**
  3927. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3928. */
  3929. Vector4.prototype.subtract = function (otherVector) {
  3930. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3931. };
  3932. /**
  3933. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3934. * Returns the current Vector4.
  3935. */
  3936. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3937. result.x = this.x - otherVector.x;
  3938. result.y = this.y - otherVector.y;
  3939. result.z = this.z - otherVector.z;
  3940. result.w = this.w - otherVector.w;
  3941. return this;
  3942. };
  3943. /**
  3944. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3945. */
  3946. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3947. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3948. };
  3949. /**
  3950. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3951. * Returns the current Vector4.
  3952. */
  3953. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3954. result.x = this.x - x;
  3955. result.y = this.y - y;
  3956. result.z = this.z - z;
  3957. result.w = this.w - w;
  3958. return this;
  3959. };
  3960. /**
  3961. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3962. */
  3963. Vector4.prototype.negate = function () {
  3964. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3965. };
  3966. /**
  3967. * Multiplies the current Vector4 coordinates by scale (float).
  3968. * Returns the updated Vector4.
  3969. */
  3970. Vector4.prototype.scaleInPlace = function (scale) {
  3971. this.x *= scale;
  3972. this.y *= scale;
  3973. this.z *= scale;
  3974. this.w *= scale;
  3975. return this;
  3976. };
  3977. /**
  3978. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3979. */
  3980. Vector4.prototype.scale = function (scale) {
  3981. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3982. };
  3983. /**
  3984. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3985. * Returns the current Vector4.
  3986. */
  3987. Vector4.prototype.scaleToRef = function (scale, result) {
  3988. result.x = this.x * scale;
  3989. result.y = this.y * scale;
  3990. result.z = this.z * scale;
  3991. result.w = this.w * scale;
  3992. return this;
  3993. };
  3994. /**
  3995. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3996. * @param scale defines the scale factor
  3997. * @param result defines the Vector4 object where to store the result
  3998. * @returns the unmodified current Vector4
  3999. */
  4000. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4001. result.x += this.x * scale;
  4002. result.y += this.y * scale;
  4003. result.z += this.z * scale;
  4004. result.w += this.w * scale;
  4005. return this;
  4006. };
  4007. /**
  4008. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4009. */
  4010. Vector4.prototype.equals = function (otherVector) {
  4011. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4012. };
  4013. /**
  4014. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4015. */
  4016. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4017. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4018. return otherVector
  4019. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4020. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4021. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4022. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4023. };
  4024. /**
  4025. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4026. */
  4027. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4028. return this.x === x && this.y === y && this.z === z && this.w === w;
  4029. };
  4030. /**
  4031. * Multiplies in place the current Vector4 by the given one.
  4032. * Returns the updated Vector4.
  4033. */
  4034. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4035. this.x *= otherVector.x;
  4036. this.y *= otherVector.y;
  4037. this.z *= otherVector.z;
  4038. this.w *= otherVector.w;
  4039. return this;
  4040. };
  4041. /**
  4042. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4043. */
  4044. Vector4.prototype.multiply = function (otherVector) {
  4045. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4046. };
  4047. /**
  4048. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4049. * Returns the current Vector4.
  4050. */
  4051. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4052. result.x = this.x * otherVector.x;
  4053. result.y = this.y * otherVector.y;
  4054. result.z = this.z * otherVector.z;
  4055. result.w = this.w * otherVector.w;
  4056. return this;
  4057. };
  4058. /**
  4059. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4060. */
  4061. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4062. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4063. };
  4064. /**
  4065. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4066. */
  4067. Vector4.prototype.divide = function (otherVector) {
  4068. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4069. };
  4070. /**
  4071. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4072. * Returns the current Vector4.
  4073. */
  4074. Vector4.prototype.divideToRef = function (otherVector, result) {
  4075. result.x = this.x / otherVector.x;
  4076. result.y = this.y / otherVector.y;
  4077. result.z = this.z / otherVector.z;
  4078. result.w = this.w / otherVector.w;
  4079. return this;
  4080. };
  4081. /**
  4082. * Divides the current Vector3 coordinates by the given ones.
  4083. * @returns the updated Vector3.
  4084. */
  4085. Vector4.prototype.divideInPlace = function (otherVector) {
  4086. return this.divideToRef(otherVector, this);
  4087. };
  4088. /**
  4089. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4090. * @param other defines the second operand
  4091. * @returns the current updated Vector4
  4092. */
  4093. Vector4.prototype.minimizeInPlace = function (other) {
  4094. if (other.x < this.x)
  4095. this.x = other.x;
  4096. if (other.y < this.y)
  4097. this.y = other.y;
  4098. if (other.z < this.z)
  4099. this.z = other.z;
  4100. if (other.w < this.w)
  4101. this.w = other.w;
  4102. return this;
  4103. };
  4104. /**
  4105. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4106. * @param other defines the second operand
  4107. * @returns the current updated Vector4
  4108. */
  4109. Vector4.prototype.maximizeInPlace = function (other) {
  4110. if (other.x > this.x)
  4111. this.x = other.x;
  4112. if (other.y > this.y)
  4113. this.y = other.y;
  4114. if (other.z > this.z)
  4115. this.z = other.z;
  4116. if (other.w > this.w)
  4117. this.w = other.w;
  4118. return this;
  4119. };
  4120. /**
  4121. * Gets a new Vector4 from current Vector4 floored values
  4122. * @returns a new Vector4
  4123. */
  4124. Vector4.prototype.floor = function () {
  4125. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4126. };
  4127. /**
  4128. * Gets a new Vector4 from current Vector3 floored values
  4129. * @returns a new Vector4
  4130. */
  4131. Vector4.prototype.fract = function () {
  4132. 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));
  4133. };
  4134. // Properties
  4135. /**
  4136. * Returns the Vector4 length (float).
  4137. */
  4138. Vector4.prototype.length = function () {
  4139. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4140. };
  4141. /**
  4142. * Returns the Vector4 squared length (float).
  4143. */
  4144. Vector4.prototype.lengthSquared = function () {
  4145. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4146. };
  4147. // Methods
  4148. /**
  4149. * Normalizes in place the Vector4.
  4150. * Returns the updated Vector4.
  4151. */
  4152. Vector4.prototype.normalize = function () {
  4153. var len = this.length();
  4154. if (len === 0)
  4155. return this;
  4156. var num = 1.0 / len;
  4157. this.x *= num;
  4158. this.y *= num;
  4159. this.z *= num;
  4160. this.w *= num;
  4161. return this;
  4162. };
  4163. /**
  4164. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4165. */
  4166. Vector4.prototype.toVector3 = function () {
  4167. return new Vector3(this.x, this.y, this.z);
  4168. };
  4169. /**
  4170. * Returns a new Vector4 copied from the current one.
  4171. */
  4172. Vector4.prototype.clone = function () {
  4173. return new Vector4(this.x, this.y, this.z, this.w);
  4174. };
  4175. /**
  4176. * Updates the current Vector4 with the given one coordinates.
  4177. * Returns the updated Vector4.
  4178. */
  4179. Vector4.prototype.copyFrom = function (source) {
  4180. this.x = source.x;
  4181. this.y = source.y;
  4182. this.z = source.z;
  4183. this.w = source.w;
  4184. return this;
  4185. };
  4186. /**
  4187. * Updates the current Vector4 coordinates with the given floats.
  4188. * Returns the updated Vector4.
  4189. */
  4190. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4191. this.x = x;
  4192. this.y = y;
  4193. this.z = z;
  4194. this.w = w;
  4195. return this;
  4196. };
  4197. /**
  4198. * Updates the current Vector4 coordinates with the given floats.
  4199. * Returns the updated Vector4.
  4200. */
  4201. Vector4.prototype.set = function (x, y, z, w) {
  4202. return this.copyFromFloats(x, y, z, w);
  4203. };
  4204. // Statics
  4205. /**
  4206. * Returns a new Vector4 set from the starting index of the given array.
  4207. */
  4208. Vector4.FromArray = function (array, offset) {
  4209. if (!offset) {
  4210. offset = 0;
  4211. }
  4212. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4213. };
  4214. /**
  4215. * Updates the given vector "result" from the starting index of the given array.
  4216. */
  4217. Vector4.FromArrayToRef = function (array, offset, result) {
  4218. result.x = array[offset];
  4219. result.y = array[offset + 1];
  4220. result.z = array[offset + 2];
  4221. result.w = array[offset + 3];
  4222. };
  4223. /**
  4224. * Updates the given vector "result" from the starting index of the given Float32Array.
  4225. */
  4226. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4227. Vector4.FromArrayToRef(array, offset, result);
  4228. };
  4229. /**
  4230. * Updates the given vector "result" coordinates from the given floats.
  4231. */
  4232. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4233. result.x = x;
  4234. result.y = y;
  4235. result.z = z;
  4236. result.w = w;
  4237. };
  4238. /**
  4239. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4240. */
  4241. Vector4.Zero = function () {
  4242. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4243. };
  4244. /**
  4245. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4246. */
  4247. Vector4.One = function () {
  4248. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4249. };
  4250. /**
  4251. * Returns a new normalized Vector4 from the given one.
  4252. */
  4253. Vector4.Normalize = function (vector) {
  4254. var result = Vector4.Zero();
  4255. Vector4.NormalizeToRef(vector, result);
  4256. return result;
  4257. };
  4258. /**
  4259. * Updates the given vector "result" from the normalization of the given one.
  4260. */
  4261. Vector4.NormalizeToRef = function (vector, result) {
  4262. result.copyFrom(vector);
  4263. result.normalize();
  4264. };
  4265. Vector4.Minimize = function (left, right) {
  4266. var min = left.clone();
  4267. min.minimizeInPlace(right);
  4268. return min;
  4269. };
  4270. Vector4.Maximize = function (left, right) {
  4271. var max = left.clone();
  4272. max.maximizeInPlace(right);
  4273. return max;
  4274. };
  4275. /**
  4276. * Returns the distance (float) between the vectors "value1" and "value2".
  4277. */
  4278. Vector4.Distance = function (value1, value2) {
  4279. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4280. };
  4281. /**
  4282. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4283. */
  4284. Vector4.DistanceSquared = function (value1, value2) {
  4285. var x = value1.x - value2.x;
  4286. var y = value1.y - value2.y;
  4287. var z = value1.z - value2.z;
  4288. var w = value1.w - value2.w;
  4289. return (x * x) + (y * y) + (z * z) + (w * w);
  4290. };
  4291. /**
  4292. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4293. */
  4294. Vector4.Center = function (value1, value2) {
  4295. var center = value1.add(value2);
  4296. center.scaleInPlace(0.5);
  4297. return center;
  4298. };
  4299. /**
  4300. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4301. * This methods computes transformed normalized direction vectors only.
  4302. */
  4303. Vector4.TransformNormal = function (vector, transformation) {
  4304. var result = Vector4.Zero();
  4305. Vector4.TransformNormalToRef(vector, transformation, result);
  4306. return result;
  4307. };
  4308. /**
  4309. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4310. * This methods computes transformed normalized direction vectors only.
  4311. */
  4312. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4313. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4314. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4315. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4316. result.x = x;
  4317. result.y = y;
  4318. result.z = z;
  4319. result.w = vector.w;
  4320. };
  4321. /**
  4322. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4323. * This methods computes transformed normalized direction vectors only.
  4324. */
  4325. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4326. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4327. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4328. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4329. result.w = w;
  4330. };
  4331. return Vector4;
  4332. }());
  4333. BABYLON.Vector4 = Vector4;
  4334. var Size = /** @class */ (function () {
  4335. /**
  4336. * Creates a Size object from the given width and height (floats).
  4337. */
  4338. function Size(width, height) {
  4339. this.width = width;
  4340. this.height = height;
  4341. }
  4342. // Returns a string with the Size width and height.
  4343. Size.prototype.toString = function () {
  4344. return "{W: " + this.width + ", H: " + this.height + "}";
  4345. };
  4346. /**
  4347. * Returns the string "Size"
  4348. */
  4349. Size.prototype.getClassName = function () {
  4350. return "Size";
  4351. };
  4352. /**
  4353. * Returns the Size hash code.
  4354. */
  4355. Size.prototype.getHashCode = function () {
  4356. var hash = this.width || 0;
  4357. hash = (hash * 397) ^ (this.height || 0);
  4358. return hash;
  4359. };
  4360. /**
  4361. * Updates the current size from the given one.
  4362. * Returns the updated Size.
  4363. */
  4364. Size.prototype.copyFrom = function (src) {
  4365. this.width = src.width;
  4366. this.height = src.height;
  4367. };
  4368. /**
  4369. * Updates in place the current Size from the given floats.
  4370. * Returns the updated Size.
  4371. */
  4372. Size.prototype.copyFromFloats = function (width, height) {
  4373. this.width = width;
  4374. this.height = height;
  4375. return this;
  4376. };
  4377. /**
  4378. * Updates in place the current Size from the given floats.
  4379. * Returns the updated Size.
  4380. */
  4381. Size.prototype.set = function (width, height) {
  4382. return this.copyFromFloats(width, height);
  4383. };
  4384. /**
  4385. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4386. */
  4387. Size.prototype.multiplyByFloats = function (w, h) {
  4388. return new Size(this.width * w, this.height * h);
  4389. };
  4390. /**
  4391. * Returns a new Size copied from the given one.
  4392. */
  4393. Size.prototype.clone = function () {
  4394. return new Size(this.width, this.height);
  4395. };
  4396. /**
  4397. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4398. */
  4399. Size.prototype.equals = function (other) {
  4400. if (!other) {
  4401. return false;
  4402. }
  4403. return (this.width === other.width) && (this.height === other.height);
  4404. };
  4405. Object.defineProperty(Size.prototype, "surface", {
  4406. /**
  4407. * Returns the surface of the Size : width * height (float).
  4408. */
  4409. get: function () {
  4410. return this.width * this.height;
  4411. },
  4412. enumerable: true,
  4413. configurable: true
  4414. });
  4415. /**
  4416. * Returns a new Size set to (0.0, 0.0)
  4417. */
  4418. Size.Zero = function () {
  4419. return new Size(0.0, 0.0);
  4420. };
  4421. /**
  4422. * Returns a new Size set as the addition result of the current Size and the given one.
  4423. */
  4424. Size.prototype.add = function (otherSize) {
  4425. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4426. return r;
  4427. };
  4428. /**
  4429. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4430. */
  4431. Size.prototype.subtract = function (otherSize) {
  4432. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4433. return r;
  4434. };
  4435. /**
  4436. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4437. */
  4438. Size.Lerp = function (start, end, amount) {
  4439. var w = start.width + ((end.width - start.width) * amount);
  4440. var h = start.height + ((end.height - start.height) * amount);
  4441. return new Size(w, h);
  4442. };
  4443. return Size;
  4444. }());
  4445. BABYLON.Size = Size;
  4446. /**
  4447. * Class used to store quaternion data
  4448. * @see https://en.wikipedia.org/wiki/Quaternion
  4449. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4450. */
  4451. var Quaternion = /** @class */ (function () {
  4452. /**
  4453. * Creates a new Quaternion from the given floats
  4454. * @param x defines the first component (0 by default)
  4455. * @param y defines the second component (0 by default)
  4456. * @param z defines the third component (0 by default)
  4457. * @param w defines the fourth component (1.0 by default)
  4458. */
  4459. function Quaternion(
  4460. /** defines the first component (0 by default) */
  4461. x,
  4462. /** defines the second component (0 by default) */
  4463. y,
  4464. /** defines the third component (0 by default) */
  4465. z,
  4466. /** defines the fourth component (1.0 by default) */
  4467. w) {
  4468. if (x === void 0) { x = 0.0; }
  4469. if (y === void 0) { y = 0.0; }
  4470. if (z === void 0) { z = 0.0; }
  4471. if (w === void 0) { w = 1.0; }
  4472. this.x = x;
  4473. this.y = y;
  4474. this.z = z;
  4475. this.w = w;
  4476. }
  4477. /**
  4478. * Gets a string representation for the current quaternion
  4479. * @returns a string with the Quaternion coordinates
  4480. */
  4481. Quaternion.prototype.toString = function () {
  4482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4483. };
  4484. /**
  4485. * Gets the class name of the quaternion
  4486. * @returns the string "Quaternion"
  4487. */
  4488. Quaternion.prototype.getClassName = function () {
  4489. return "Quaternion";
  4490. };
  4491. /**
  4492. * Gets a hash code for this quaternion
  4493. * @returns the quaternion hash code
  4494. */
  4495. Quaternion.prototype.getHashCode = function () {
  4496. var hash = this.x || 0;
  4497. hash = (hash * 397) ^ (this.y || 0);
  4498. hash = (hash * 397) ^ (this.z || 0);
  4499. hash = (hash * 397) ^ (this.w || 0);
  4500. return hash;
  4501. };
  4502. /**
  4503. * Copy the quaternion to an array
  4504. * @returns a new array populated with 4 elements from the quaternion coordinates
  4505. */
  4506. Quaternion.prototype.asArray = function () {
  4507. return [this.x, this.y, this.z, this.w];
  4508. };
  4509. /**
  4510. * Check if two quaternions are equals
  4511. * @param otherQuaternion defines the second operand
  4512. * @return true if the current quaternion and the given one coordinates are strictly equals
  4513. */
  4514. Quaternion.prototype.equals = function (otherQuaternion) {
  4515. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4516. };
  4517. /**
  4518. * Clone the current quaternion
  4519. * @returns a new quaternion copied from the current one
  4520. */
  4521. Quaternion.prototype.clone = function () {
  4522. return new Quaternion(this.x, this.y, this.z, this.w);
  4523. };
  4524. /**
  4525. * Copy a quaternion to the current one
  4526. * @param other defines the other quaternion
  4527. * @returns the updated current quaternion
  4528. */
  4529. Quaternion.prototype.copyFrom = function (other) {
  4530. this.x = other.x;
  4531. this.y = other.y;
  4532. this.z = other.z;
  4533. this.w = other.w;
  4534. return this;
  4535. };
  4536. /**
  4537. * Updates the current quaternion with the given float coordinates
  4538. * @param x defines the x coordinate
  4539. * @param y defines the y coordinate
  4540. * @param z defines the z coordinate
  4541. * @param w defines the w coordinate
  4542. * @returns the updated current quaternion
  4543. */
  4544. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4545. this.x = x;
  4546. this.y = y;
  4547. this.z = z;
  4548. this.w = w;
  4549. return this;
  4550. };
  4551. /**
  4552. * Updates the current quaternion from the given float coordinates
  4553. * @param x defines the x coordinate
  4554. * @param y defines the y coordinate
  4555. * @param z defines the z coordinate
  4556. * @param w defines the w coordinate
  4557. * @returns the updated current quaternion
  4558. */
  4559. Quaternion.prototype.set = function (x, y, z, w) {
  4560. return this.copyFromFloats(x, y, z, w);
  4561. };
  4562. /**
  4563. * Adds two quaternions
  4564. * @param other defines the second operand
  4565. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4566. */
  4567. Quaternion.prototype.add = function (other) {
  4568. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4569. };
  4570. /**
  4571. * Add a quaternion to the current one
  4572. * @param other defines the quaternion to add
  4573. * @returns the current quaternion
  4574. */
  4575. Quaternion.prototype.addInPlace = function (other) {
  4576. this.x += other.x;
  4577. this.y += other.y;
  4578. this.z += other.z;
  4579. this.w += other.w;
  4580. return this;
  4581. };
  4582. /**
  4583. * Subtract two quaternions
  4584. * @param other defines the second operand
  4585. * @returns a new quaternion as the subtraction result of the given one from the current one
  4586. */
  4587. Quaternion.prototype.subtract = function (other) {
  4588. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4589. };
  4590. /**
  4591. * Multiplies the current quaternion by a scale factor
  4592. * @param value defines the scale factor
  4593. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4594. */
  4595. Quaternion.prototype.scale = function (value) {
  4596. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4597. };
  4598. /**
  4599. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4600. * @param scale defines the scale factor
  4601. * @param result defines the Quaternion object where to store the result
  4602. * @returns the unmodified current quaternion
  4603. */
  4604. Quaternion.prototype.scaleToRef = function (scale, result) {
  4605. result.x = this.x * scale;
  4606. result.y = this.y * scale;
  4607. result.z = this.z * scale;
  4608. result.w = this.w * scale;
  4609. return this;
  4610. };
  4611. /**
  4612. * Multiplies in place the current quaternion by a scale factor
  4613. * @param value defines the scale factor
  4614. * @returns the current modified quaternion
  4615. */
  4616. Quaternion.prototype.scaleInPlace = function (value) {
  4617. this.x *= value;
  4618. this.y *= value;
  4619. this.z *= value;
  4620. this.w *= value;
  4621. return this;
  4622. };
  4623. /**
  4624. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4625. * @param scale defines the scale factor
  4626. * @param result defines the Quaternion object where to store the result
  4627. * @returns the unmodified current quaternion
  4628. */
  4629. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4630. result.x += this.x * scale;
  4631. result.y += this.y * scale;
  4632. result.z += this.z * scale;
  4633. result.w += this.w * scale;
  4634. return this;
  4635. };
  4636. /**
  4637. * Multiplies two quaternions
  4638. * @param q1 defines the second operand
  4639. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4640. */
  4641. Quaternion.prototype.multiply = function (q1) {
  4642. var result = new Quaternion(0, 0, 0, 1.0);
  4643. this.multiplyToRef(q1, result);
  4644. return result;
  4645. };
  4646. /**
  4647. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4648. * @param q1 defines the second operand
  4649. * @param result defines the target quaternion
  4650. * @returns the current quaternion
  4651. */
  4652. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4653. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4654. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4655. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4656. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4657. result.copyFromFloats(x, y, z, w);
  4658. return this;
  4659. };
  4660. /**
  4661. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4662. * @param q1 defines the second operand
  4663. * @returns the currentupdated quaternion
  4664. */
  4665. Quaternion.prototype.multiplyInPlace = function (q1) {
  4666. this.multiplyToRef(q1, this);
  4667. return this;
  4668. };
  4669. /**
  4670. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4671. * @param ref defines the target quaternion
  4672. * @returns the current quaternion
  4673. */
  4674. Quaternion.prototype.conjugateToRef = function (ref) {
  4675. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4676. return this;
  4677. };
  4678. /**
  4679. * Conjugates in place (1-q) the current quaternion
  4680. * @returns the current updated quaternion
  4681. */
  4682. Quaternion.prototype.conjugateInPlace = function () {
  4683. this.x *= -1;
  4684. this.y *= -1;
  4685. this.z *= -1;
  4686. return this;
  4687. };
  4688. /**
  4689. * Conjugates in place (1-q) the current quaternion
  4690. * @returns a new quaternion
  4691. */
  4692. Quaternion.prototype.conjugate = function () {
  4693. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4694. return result;
  4695. };
  4696. /**
  4697. * Gets length of current quaternion
  4698. * @returns the quaternion length (float)
  4699. */
  4700. Quaternion.prototype.length = function () {
  4701. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4702. };
  4703. /**
  4704. * Normalize in place the current quaternion
  4705. * @returns the current updated quaternion
  4706. */
  4707. Quaternion.prototype.normalize = function () {
  4708. var length = 1.0 / this.length();
  4709. this.x *= length;
  4710. this.y *= length;
  4711. this.z *= length;
  4712. this.w *= length;
  4713. return this;
  4714. };
  4715. /**
  4716. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4717. * @param order is a reserved parameter and is ignore for now
  4718. * @returns a new Vector3 containing the Euler angles
  4719. */
  4720. Quaternion.prototype.toEulerAngles = function (order) {
  4721. if (order === void 0) { order = "YZX"; }
  4722. var result = Vector3.Zero();
  4723. this.toEulerAnglesToRef(result, order);
  4724. return result;
  4725. };
  4726. /**
  4727. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4728. * @param result defines the vector which will be filled with the Euler angles
  4729. * @param order is a reserved parameter and is ignore for now
  4730. * @returns the current unchanged quaternion
  4731. */
  4732. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4733. if (order === void 0) { order = "YZX"; }
  4734. var qz = this.z;
  4735. var qx = this.x;
  4736. var qy = this.y;
  4737. var qw = this.w;
  4738. var sqw = qw * qw;
  4739. var sqz = qz * qz;
  4740. var sqx = qx * qx;
  4741. var sqy = qy * qy;
  4742. var zAxisY = qy * qz - qx * qw;
  4743. var limit = .4999999;
  4744. if (zAxisY < -limit) {
  4745. result.y = 2 * Math.atan2(qy, qw);
  4746. result.x = Math.PI / 2;
  4747. result.z = 0;
  4748. }
  4749. else if (zAxisY > limit) {
  4750. result.y = 2 * Math.atan2(qy, qw);
  4751. result.x = -Math.PI / 2;
  4752. result.z = 0;
  4753. }
  4754. else {
  4755. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4756. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4757. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4758. }
  4759. return this;
  4760. };
  4761. /**
  4762. * Updates the given rotation matrix with the current quaternion values
  4763. * @param result defines the target matrix
  4764. * @returns the current unchanged quaternion
  4765. */
  4766. Quaternion.prototype.toRotationMatrix = function (result) {
  4767. var xx = this.x * this.x;
  4768. var yy = this.y * this.y;
  4769. var zz = this.z * this.z;
  4770. var xy = this.x * this.y;
  4771. var zw = this.z * this.w;
  4772. var zx = this.z * this.x;
  4773. var yw = this.y * this.w;
  4774. var yz = this.y * this.z;
  4775. var xw = this.x * this.w;
  4776. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4777. result.m[1] = 2.0 * (xy + zw);
  4778. result.m[2] = 2.0 * (zx - yw);
  4779. result.m[3] = 0;
  4780. result.m[4] = 2.0 * (xy - zw);
  4781. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4782. result.m[6] = 2.0 * (yz + xw);
  4783. result.m[7] = 0;
  4784. result.m[8] = 2.0 * (zx + yw);
  4785. result.m[9] = 2.0 * (yz - xw);
  4786. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4787. result.m[11] = 0;
  4788. result.m[12] = 0;
  4789. result.m[13] = 0;
  4790. result.m[14] = 0;
  4791. result.m[15] = 1.0;
  4792. result._markAsUpdated();
  4793. return this;
  4794. };
  4795. /**
  4796. * Updates the current quaternion from the given rotation matrix values
  4797. * @param matrix defines the source matrix
  4798. * @returns the current updated quaternion
  4799. */
  4800. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4801. Quaternion.FromRotationMatrixToRef(matrix, this);
  4802. return this;
  4803. };
  4804. // Statics
  4805. /**
  4806. * Creates a new quaternion from a rotation matrix
  4807. * @param matrix defines the source matrix
  4808. * @returns a new quaternion created from the given rotation matrix values
  4809. */
  4810. Quaternion.FromRotationMatrix = function (matrix) {
  4811. var result = new Quaternion();
  4812. Quaternion.FromRotationMatrixToRef(matrix, result);
  4813. return result;
  4814. };
  4815. /**
  4816. * Updates the given quaternion with the given rotation matrix values
  4817. * @param matrix defines the source matrix
  4818. * @param result defines the target quaternion
  4819. */
  4820. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4821. var data = matrix.m;
  4822. var m11 = data[0], m12 = data[4], m13 = data[8];
  4823. var m21 = data[1], m22 = data[5], m23 = data[9];
  4824. var m31 = data[2], m32 = data[6], m33 = data[10];
  4825. var trace = m11 + m22 + m33;
  4826. var s;
  4827. if (trace > 0) {
  4828. s = 0.5 / Math.sqrt(trace + 1.0);
  4829. result.w = 0.25 / s;
  4830. result.x = (m32 - m23) * s;
  4831. result.y = (m13 - m31) * s;
  4832. result.z = (m21 - m12) * s;
  4833. }
  4834. else if (m11 > m22 && m11 > m33) {
  4835. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4836. result.w = (m32 - m23) / s;
  4837. result.x = 0.25 * s;
  4838. result.y = (m12 + m21) / s;
  4839. result.z = (m13 + m31) / s;
  4840. }
  4841. else if (m22 > m33) {
  4842. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4843. result.w = (m13 - m31) / s;
  4844. result.x = (m12 + m21) / s;
  4845. result.y = 0.25 * s;
  4846. result.z = (m23 + m32) / s;
  4847. }
  4848. else {
  4849. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4850. result.w = (m21 - m12) / s;
  4851. result.x = (m13 + m31) / s;
  4852. result.y = (m23 + m32) / s;
  4853. result.z = 0.25 * s;
  4854. }
  4855. };
  4856. /**
  4857. * Returns the dot product (float) between the quaternions "left" and "right"
  4858. * @param left defines the left operand
  4859. * @param right defines the right operand
  4860. * @returns the dot product
  4861. */
  4862. Quaternion.Dot = function (left, right) {
  4863. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4864. };
  4865. /**
  4866. * Checks if the two quaternions are close to each other
  4867. * @param quat0 defines the first quaternion to check
  4868. * @param quat1 defines the second quaternion to check
  4869. * @returns true if the two quaternions are close to each other
  4870. */
  4871. Quaternion.AreClose = function (quat0, quat1) {
  4872. var dot = Quaternion.Dot(quat0, quat1);
  4873. return dot >= 0;
  4874. };
  4875. /**
  4876. * Creates an empty quaternion
  4877. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4878. */
  4879. Quaternion.Zero = function () {
  4880. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4881. };
  4882. /**
  4883. * Inverse a given quaternion
  4884. * @param q defines the source quaternion
  4885. * @returns a new quaternion as the inverted current quaternion
  4886. */
  4887. Quaternion.Inverse = function (q) {
  4888. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4889. };
  4890. /**
  4891. * Creates an identity quaternion
  4892. * @returns the identity quaternion
  4893. */
  4894. Quaternion.Identity = function () {
  4895. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4896. };
  4897. /**
  4898. * Gets a boolean indicating if the given quaternion is identity
  4899. * @param quaternion defines the quaternion to check
  4900. * @returns true if the quaternion is identity
  4901. */
  4902. Quaternion.IsIdentity = function (quaternion) {
  4903. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4904. };
  4905. /**
  4906. * Creates a quaternion from a rotation around an axis
  4907. * @param axis defines the axis to use
  4908. * @param angle defines the angle to use
  4909. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4910. */
  4911. Quaternion.RotationAxis = function (axis, angle) {
  4912. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4913. };
  4914. /**
  4915. * Creates a rotation around an axis and stores it into the given quaternion
  4916. * @param axis defines the axis to use
  4917. * @param angle defines the angle to use
  4918. * @param result defines the target quaternion
  4919. * @returns the target quaternion
  4920. */
  4921. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4922. var sin = Math.sin(angle / 2);
  4923. axis.normalize();
  4924. result.w = Math.cos(angle / 2);
  4925. result.x = axis.x * sin;
  4926. result.y = axis.y * sin;
  4927. result.z = axis.z * sin;
  4928. return result;
  4929. };
  4930. /**
  4931. * Creates a new quaternion from data stored into an array
  4932. * @param array defines the data source
  4933. * @param offset defines the offset in the source array where the data starts
  4934. * @returns a new quaternion
  4935. */
  4936. Quaternion.FromArray = function (array, offset) {
  4937. if (!offset) {
  4938. offset = 0;
  4939. }
  4940. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4941. };
  4942. /**
  4943. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4944. * @param yaw defines the rotation around Y axis
  4945. * @param pitch defines the rotation around X axis
  4946. * @param roll defines the rotation around Z axis
  4947. * @returns the new quaternion
  4948. */
  4949. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4950. var q = new Quaternion();
  4951. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4952. return q;
  4953. };
  4954. /**
  4955. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4956. * @param yaw defines the rotation around Y axis
  4957. * @param pitch defines the rotation around X axis
  4958. * @param roll defines the rotation around Z axis
  4959. * @param result defines the target quaternion
  4960. */
  4961. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4962. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4963. var halfRoll = roll * 0.5;
  4964. var halfPitch = pitch * 0.5;
  4965. var halfYaw = yaw * 0.5;
  4966. var sinRoll = Math.sin(halfRoll);
  4967. var cosRoll = Math.cos(halfRoll);
  4968. var sinPitch = Math.sin(halfPitch);
  4969. var cosPitch = Math.cos(halfPitch);
  4970. var sinYaw = Math.sin(halfYaw);
  4971. var cosYaw = Math.cos(halfYaw);
  4972. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4973. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4974. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4975. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4976. };
  4977. /**
  4978. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4979. * @param alpha defines the rotation around first axis
  4980. * @param beta defines the rotation around second axis
  4981. * @param gamma defines the rotation around third axis
  4982. * @returns the new quaternion
  4983. */
  4984. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4985. var result = new Quaternion();
  4986. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4987. return result;
  4988. };
  4989. /**
  4990. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4991. * @param alpha defines the rotation around first axis
  4992. * @param beta defines the rotation around second axis
  4993. * @param gamma defines the rotation around third axis
  4994. * @param result defines the target quaternion
  4995. */
  4996. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4997. // Produces a quaternion from Euler angles in the z-x-z orientation
  4998. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4999. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5000. var halfBeta = beta * 0.5;
  5001. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5002. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5003. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5004. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5005. };
  5006. /**
  5007. * 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)
  5008. * @param axis1 defines the first axis
  5009. * @param axis2 defines the second axis
  5010. * @param axis3 defines the third axis
  5011. * @returns the new quaternion
  5012. */
  5013. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5014. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5015. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5016. return quat;
  5017. };
  5018. /**
  5019. * 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
  5020. * @param axis1 defines the first axis
  5021. * @param axis2 defines the second axis
  5022. * @param axis3 defines the third axis
  5023. * @param ref defines the target quaternion
  5024. */
  5025. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5026. var rotMat = MathTmp.Matrix[0];
  5027. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5028. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5029. };
  5030. /**
  5031. * Interpolates between two quaternions
  5032. * @param left defines first quaternion
  5033. * @param right defines second quaternion
  5034. * @param amount defines the gradient to use
  5035. * @returns the new interpolated quaternion
  5036. */
  5037. Quaternion.Slerp = function (left, right, amount) {
  5038. var result = Quaternion.Identity();
  5039. Quaternion.SlerpToRef(left, right, amount, result);
  5040. return result;
  5041. };
  5042. /**
  5043. * Interpolates between two quaternions and stores it into a target quaternion
  5044. * @param left defines first quaternion
  5045. * @param right defines second quaternion
  5046. * @param amount defines the gradient to use
  5047. * @param result defines the target quaternion
  5048. */
  5049. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5050. var num2;
  5051. var num3;
  5052. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5053. var flag = false;
  5054. if (num4 < 0) {
  5055. flag = true;
  5056. num4 = -num4;
  5057. }
  5058. if (num4 > 0.999999) {
  5059. num3 = 1 - amount;
  5060. num2 = flag ? -amount : amount;
  5061. }
  5062. else {
  5063. var num5 = Math.acos(num4);
  5064. var num6 = (1.0 / Math.sin(num5));
  5065. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5066. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5067. }
  5068. result.x = (num3 * left.x) + (num2 * right.x);
  5069. result.y = (num3 * left.y) + (num2 * right.y);
  5070. result.z = (num3 * left.z) + (num2 * right.z);
  5071. result.w = (num3 * left.w) + (num2 * right.w);
  5072. };
  5073. /**
  5074. * Interpolate between two quaternions using Hermite interpolation
  5075. * @param value1 defines first quaternion
  5076. * @param tangent1 defines the incoming tangent
  5077. * @param value2 defines second quaternion
  5078. * @param tangent2 defines the outgoing tangent
  5079. * @param amount defines the target quaternion
  5080. * @returns the new interpolated quaternion
  5081. */
  5082. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5083. var squared = amount * amount;
  5084. var cubed = amount * squared;
  5085. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5086. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5087. var part3 = (cubed - (2.0 * squared)) + amount;
  5088. var part4 = cubed - squared;
  5089. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5090. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5091. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5092. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5093. return new Quaternion(x, y, z, w);
  5094. };
  5095. return Quaternion;
  5096. }());
  5097. BABYLON.Quaternion = Quaternion;
  5098. /**
  5099. * Class used to store matrix data (4x4)
  5100. */
  5101. var Matrix = /** @class */ (function () {
  5102. /**
  5103. * Creates an empty matrix (filled with zeros)
  5104. */
  5105. function Matrix() {
  5106. this._isIdentity = false;
  5107. this._isIdentityDirty = true;
  5108. /**
  5109. * Gets or sets the internal data of the matrix
  5110. */
  5111. this.m = new Float32Array(16);
  5112. this._markAsUpdated();
  5113. }
  5114. /** @hidden */
  5115. Matrix.prototype._markAsUpdated = function () {
  5116. this.updateFlag = Matrix._updateFlagSeed++;
  5117. this._isIdentityDirty = true;
  5118. };
  5119. // Properties
  5120. /**
  5121. * Check if the current matrix is indentity
  5122. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5123. * @returns true is the matrix is the identity matrix
  5124. */
  5125. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5126. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5127. if (this._isIdentityDirty) {
  5128. this._isIdentityDirty = false;
  5129. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5130. this._isIdentity = false;
  5131. }
  5132. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5133. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5134. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5135. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5136. this._isIdentity = false;
  5137. }
  5138. else {
  5139. this._isIdentity = true;
  5140. }
  5141. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5142. this._isIdentity = false;
  5143. }
  5144. }
  5145. return this._isIdentity;
  5146. };
  5147. /**
  5148. * Gets the determinant of the matrix
  5149. * @returns the matrix determinant
  5150. */
  5151. Matrix.prototype.determinant = function () {
  5152. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5153. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5154. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5155. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5156. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5157. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5158. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5159. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5160. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5161. };
  5162. // Methods
  5163. /**
  5164. * Returns the matrix as a Float32Array
  5165. * @returns the matrix underlying array
  5166. */
  5167. Matrix.prototype.toArray = function () {
  5168. return this.m;
  5169. };
  5170. /**
  5171. * Returns the matrix as a Float32Array
  5172. * @returns the matrix underlying array.
  5173. */
  5174. Matrix.prototype.asArray = function () {
  5175. return this.toArray();
  5176. };
  5177. /**
  5178. * Inverts the current matrix in place
  5179. * @returns the current inverted matrix
  5180. */
  5181. Matrix.prototype.invert = function () {
  5182. this.invertToRef(this);
  5183. return this;
  5184. };
  5185. /**
  5186. * Sets all the matrix elements to zero
  5187. * @returns the current matrix
  5188. */
  5189. Matrix.prototype.reset = function () {
  5190. for (var index = 0; index < 16; index++) {
  5191. this.m[index] = 0.0;
  5192. }
  5193. this._markAsUpdated();
  5194. return this;
  5195. };
  5196. /**
  5197. * Adds the current matrix with a second one
  5198. * @param other defines the matrix to add
  5199. * @returns a new matrix as the addition of the current matrix and the given one
  5200. */
  5201. Matrix.prototype.add = function (other) {
  5202. var result = new Matrix();
  5203. this.addToRef(other, result);
  5204. return result;
  5205. };
  5206. /**
  5207. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5208. * @param other defines the matrix to add
  5209. * @param result defines the target matrix
  5210. * @returns the current matrix
  5211. */
  5212. Matrix.prototype.addToRef = function (other, result) {
  5213. for (var index = 0; index < 16; index++) {
  5214. result.m[index] = this.m[index] + other.m[index];
  5215. }
  5216. result._markAsUpdated();
  5217. return this;
  5218. };
  5219. /**
  5220. * Adds in place the given matrix to the current matrix
  5221. * @param other defines the second operand
  5222. * @returns the current updated matrix
  5223. */
  5224. Matrix.prototype.addToSelf = function (other) {
  5225. for (var index = 0; index < 16; index++) {
  5226. this.m[index] += other.m[index];
  5227. }
  5228. this._markAsUpdated();
  5229. return this;
  5230. };
  5231. /**
  5232. * Sets the given matrix to the current inverted Matrix
  5233. * @param other defines the target matrix
  5234. * @returns the unmodified current matrix
  5235. */
  5236. Matrix.prototype.invertToRef = function (other) {
  5237. var l1 = this.m[0];
  5238. var l2 = this.m[1];
  5239. var l3 = this.m[2];
  5240. var l4 = this.m[3];
  5241. var l5 = this.m[4];
  5242. var l6 = this.m[5];
  5243. var l7 = this.m[6];
  5244. var l8 = this.m[7];
  5245. var l9 = this.m[8];
  5246. var l10 = this.m[9];
  5247. var l11 = this.m[10];
  5248. var l12 = this.m[11];
  5249. var l13 = this.m[12];
  5250. var l14 = this.m[13];
  5251. var l15 = this.m[14];
  5252. var l16 = this.m[15];
  5253. var l17 = (l11 * l16) - (l12 * l15);
  5254. var l18 = (l10 * l16) - (l12 * l14);
  5255. var l19 = (l10 * l15) - (l11 * l14);
  5256. var l20 = (l9 * l16) - (l12 * l13);
  5257. var l21 = (l9 * l15) - (l11 * l13);
  5258. var l22 = (l9 * l14) - (l10 * l13);
  5259. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5260. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5261. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5262. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5263. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5264. var l28 = (l7 * l16) - (l8 * l15);
  5265. var l29 = (l6 * l16) - (l8 * l14);
  5266. var l30 = (l6 * l15) - (l7 * l14);
  5267. var l31 = (l5 * l16) - (l8 * l13);
  5268. var l32 = (l5 * l15) - (l7 * l13);
  5269. var l33 = (l5 * l14) - (l6 * l13);
  5270. var l34 = (l7 * l12) - (l8 * l11);
  5271. var l35 = (l6 * l12) - (l8 * l10);
  5272. var l36 = (l6 * l11) - (l7 * l10);
  5273. var l37 = (l5 * l12) - (l8 * l9);
  5274. var l38 = (l5 * l11) - (l7 * l9);
  5275. var l39 = (l5 * l10) - (l6 * l9);
  5276. other.m[0] = l23 * l27;
  5277. other.m[4] = l24 * l27;
  5278. other.m[8] = l25 * l27;
  5279. other.m[12] = l26 * l27;
  5280. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5281. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5282. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5283. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5284. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5285. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5286. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5287. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5288. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5289. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5290. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5291. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5292. other._markAsUpdated();
  5293. return this;
  5294. };
  5295. /**
  5296. * Inserts the translation vector (using 3 floats) in the current matrix
  5297. * @param x defines the 1st component of the translation
  5298. * @param y defines the 2nd component of the translation
  5299. * @param z defines the 3rd component of the translation
  5300. * @returns the current updated matrix
  5301. */
  5302. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5303. this.m[12] = x;
  5304. this.m[13] = y;
  5305. this.m[14] = z;
  5306. this._markAsUpdated();
  5307. return this;
  5308. };
  5309. /**
  5310. * Inserts the translation vector in the current matrix
  5311. * @param vector3 defines the translation to insert
  5312. * @returns the current updated matrix
  5313. */
  5314. Matrix.prototype.setTranslation = function (vector3) {
  5315. this.m[12] = vector3.x;
  5316. this.m[13] = vector3.y;
  5317. this.m[14] = vector3.z;
  5318. this._markAsUpdated();
  5319. return this;
  5320. };
  5321. /**
  5322. * Gets the translation value of the current matrix
  5323. * @returns a new Vector3 as the extracted translation from the matrix
  5324. */
  5325. Matrix.prototype.getTranslation = function () {
  5326. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5327. };
  5328. /**
  5329. * Fill a Vector3 with the extracted translation from the matrix
  5330. * @param result defines the Vector3 where to store the translation
  5331. * @returns the current matrix
  5332. */
  5333. Matrix.prototype.getTranslationToRef = function (result) {
  5334. result.x = this.m[12];
  5335. result.y = this.m[13];
  5336. result.z = this.m[14];
  5337. return this;
  5338. };
  5339. /**
  5340. * Remove rotation and scaling part from the matrix
  5341. * @returns the updated matrix
  5342. */
  5343. Matrix.prototype.removeRotationAndScaling = function () {
  5344. this.setRowFromFloats(0, 1, 0, 0, 0);
  5345. this.setRowFromFloats(1, 0, 1, 0, 0);
  5346. this.setRowFromFloats(2, 0, 0, 1, 0);
  5347. return this;
  5348. };
  5349. /**
  5350. * Multiply two matrices
  5351. * @param other defines the second operand
  5352. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5353. */
  5354. Matrix.prototype.multiply = function (other) {
  5355. var result = new Matrix();
  5356. this.multiplyToRef(other, result);
  5357. return result;
  5358. };
  5359. /**
  5360. * Copy the current matrix from the given one
  5361. * @param other defines the source matrix
  5362. * @returns the current updated matrix
  5363. */
  5364. Matrix.prototype.copyFrom = function (other) {
  5365. for (var index = 0; index < 16; index++) {
  5366. this.m[index] = other.m[index];
  5367. }
  5368. this._markAsUpdated();
  5369. return this;
  5370. };
  5371. /**
  5372. * Populates the given array from the starting index with the current matrix values
  5373. * @param array defines the target array
  5374. * @param offset defines the offset in the target array where to start storing values
  5375. * @returns the current matrix
  5376. */
  5377. Matrix.prototype.copyToArray = function (array, offset) {
  5378. if (offset === void 0) { offset = 0; }
  5379. for (var index = 0; index < 16; index++) {
  5380. array[offset + index] = this.m[index];
  5381. }
  5382. return this;
  5383. };
  5384. /**
  5385. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5386. * @param other defines the second operand
  5387. * @param result defines the matrix where to store the multiplication
  5388. * @returns the current matrix
  5389. */
  5390. Matrix.prototype.multiplyToRef = function (other, result) {
  5391. this.multiplyToArray(other, result.m, 0);
  5392. result._markAsUpdated();
  5393. return this;
  5394. };
  5395. /**
  5396. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5397. * @param other defines the second operand
  5398. * @param result defines the array where to store the multiplication
  5399. * @param offset defines the offset in the target array where to start storing values
  5400. * @returns the current matrix
  5401. */
  5402. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5403. var tm0 = this.m[0];
  5404. var tm1 = this.m[1];
  5405. var tm2 = this.m[2];
  5406. var tm3 = this.m[3];
  5407. var tm4 = this.m[4];
  5408. var tm5 = this.m[5];
  5409. var tm6 = this.m[6];
  5410. var tm7 = this.m[7];
  5411. var tm8 = this.m[8];
  5412. var tm9 = this.m[9];
  5413. var tm10 = this.m[10];
  5414. var tm11 = this.m[11];
  5415. var tm12 = this.m[12];
  5416. var tm13 = this.m[13];
  5417. var tm14 = this.m[14];
  5418. var tm15 = this.m[15];
  5419. var om0 = other.m[0];
  5420. var om1 = other.m[1];
  5421. var om2 = other.m[2];
  5422. var om3 = other.m[3];
  5423. var om4 = other.m[4];
  5424. var om5 = other.m[5];
  5425. var om6 = other.m[6];
  5426. var om7 = other.m[7];
  5427. var om8 = other.m[8];
  5428. var om9 = other.m[9];
  5429. var om10 = other.m[10];
  5430. var om11 = other.m[11];
  5431. var om12 = other.m[12];
  5432. var om13 = other.m[13];
  5433. var om14 = other.m[14];
  5434. var om15 = other.m[15];
  5435. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5436. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5437. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5438. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5439. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5440. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5441. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5442. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5443. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5444. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5445. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5446. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5447. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5448. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5449. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5450. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5451. return this;
  5452. };
  5453. /**
  5454. * Check equality between this matrix and a second one
  5455. * @param value defines the second matrix to compare
  5456. * @returns true is the current matrix and the given one values are strictly equal
  5457. */
  5458. Matrix.prototype.equals = function (value) {
  5459. return value &&
  5460. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5461. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5462. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5463. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5464. };
  5465. /**
  5466. * Clone the current matrix
  5467. * @returns a new matrix from the current matrix
  5468. */
  5469. Matrix.prototype.clone = function () {
  5470. 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]);
  5471. };
  5472. /**
  5473. * Returns the name of the current matrix class
  5474. * @returns the string "Matrix"
  5475. */
  5476. Matrix.prototype.getClassName = function () {
  5477. return "Matrix";
  5478. };
  5479. /**
  5480. * Gets the hash code of the current matrix
  5481. * @returns the hash code
  5482. */
  5483. Matrix.prototype.getHashCode = function () {
  5484. var hash = this.m[0] || 0;
  5485. for (var i = 1; i < 16; i++) {
  5486. hash = (hash * 397) ^ (this.m[i] || 0);
  5487. }
  5488. return hash;
  5489. };
  5490. /**
  5491. * Decomposes the current Matrix into a translation, rotation and scaling components
  5492. * @param scale defines the scale vector3 given as a reference to update
  5493. * @param rotation defines the rotation quaternion given as a reference to update
  5494. * @param translation defines the translation vector3 given as a reference to update
  5495. * @returns true if operation was successful
  5496. */
  5497. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5498. if (translation) {
  5499. translation.x = this.m[12];
  5500. translation.y = this.m[13];
  5501. translation.z = this.m[14];
  5502. }
  5503. scale = scale || MathTmp.Vector3[0];
  5504. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5505. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5506. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5507. if (this.determinant() <= 0) {
  5508. scale.y *= -1;
  5509. }
  5510. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5511. if (rotation) {
  5512. rotation.x = 0;
  5513. rotation.y = 0;
  5514. rotation.z = 0;
  5515. rotation.w = 1;
  5516. }
  5517. return false;
  5518. }
  5519. if (rotation) {
  5520. 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]);
  5521. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5522. }
  5523. return true;
  5524. };
  5525. /**
  5526. * Gets specific row of the matrix
  5527. * @param index defines the number of the row to get
  5528. * @returns the index-th row of the current matrix as a new Vector4
  5529. */
  5530. Matrix.prototype.getRow = function (index) {
  5531. if (index < 0 || index > 3) {
  5532. return null;
  5533. }
  5534. var i = index * 4;
  5535. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5536. };
  5537. /**
  5538. * Sets the index-th row of the current matrix to the vector4 values
  5539. * @param index defines the number of the row to set
  5540. * @param row defines the target vector4
  5541. * @returns the updated current matrix
  5542. */
  5543. Matrix.prototype.setRow = function (index, row) {
  5544. if (index < 0 || index > 3) {
  5545. return this;
  5546. }
  5547. var i = index * 4;
  5548. this.m[i + 0] = row.x;
  5549. this.m[i + 1] = row.y;
  5550. this.m[i + 2] = row.z;
  5551. this.m[i + 3] = row.w;
  5552. this._markAsUpdated();
  5553. return this;
  5554. };
  5555. /**
  5556. * Compute the transpose of the matrix
  5557. * @returns the new transposed matrix
  5558. */
  5559. Matrix.prototype.transpose = function () {
  5560. return Matrix.Transpose(this);
  5561. };
  5562. /**
  5563. * Compute the transpose of the matrix and store it in a given matrix
  5564. * @param result defines the target matrix
  5565. * @returns the current matrix
  5566. */
  5567. Matrix.prototype.transposeToRef = function (result) {
  5568. Matrix.TransposeToRef(this, result);
  5569. return this;
  5570. };
  5571. /**
  5572. * Sets the index-th row of the current matrix with the given 4 x float values
  5573. * @param index defines the row index
  5574. * @param x defines the x component to set
  5575. * @param y defines the y component to set
  5576. * @param z defines the z component to set
  5577. * @param w defines the w component to set
  5578. * @returns the updated current matrix
  5579. */
  5580. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5581. if (index < 0 || index > 3) {
  5582. return this;
  5583. }
  5584. var i = index * 4;
  5585. this.m[i + 0] = x;
  5586. this.m[i + 1] = y;
  5587. this.m[i + 2] = z;
  5588. this.m[i + 3] = w;
  5589. this._markAsUpdated();
  5590. return this;
  5591. };
  5592. /**
  5593. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5594. * @param scale defines the scale factor
  5595. * @returns a new matrix
  5596. */
  5597. Matrix.prototype.scale = function (scale) {
  5598. var result = new Matrix();
  5599. this.scaleToRef(scale, result);
  5600. return result;
  5601. };
  5602. /**
  5603. * Scale the current matrix values by a factor to a given result matrix
  5604. * @param scale defines the scale factor
  5605. * @param result defines the matrix to store the result
  5606. * @returns the current matrix
  5607. */
  5608. Matrix.prototype.scaleToRef = function (scale, result) {
  5609. for (var index = 0; index < 16; index++) {
  5610. result.m[index] = this.m[index] * scale;
  5611. }
  5612. result._markAsUpdated();
  5613. return this;
  5614. };
  5615. /**
  5616. * Scale the current matrix values by a factor and add the result to a given matrix
  5617. * @param scale defines the scale factor
  5618. * @param result defines the Matrix to store the result
  5619. * @returns the current matrix
  5620. */
  5621. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5622. for (var index = 0; index < 16; index++) {
  5623. result.m[index] += this.m[index] * scale;
  5624. }
  5625. result._markAsUpdated();
  5626. return this;
  5627. };
  5628. /**
  5629. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5630. * @param ref matrix to store the result
  5631. */
  5632. Matrix.prototype.toNormalMatrix = function (ref) {
  5633. this.invertToRef(ref);
  5634. ref.transpose();
  5635. var m = ref.m;
  5636. 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);
  5637. };
  5638. /**
  5639. * Gets only rotation part of the current matrix
  5640. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5641. */
  5642. Matrix.prototype.getRotationMatrix = function () {
  5643. var result = Matrix.Identity();
  5644. this.getRotationMatrixToRef(result);
  5645. return result;
  5646. };
  5647. /**
  5648. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5649. * @param result defines the target matrix to store data to
  5650. * @returns the current matrix
  5651. */
  5652. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5653. var m = this.m;
  5654. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5655. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5656. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5657. if (this.determinant() <= 0) {
  5658. sy *= -1;
  5659. }
  5660. if (sx === 0 || sy === 0 || sz === 0) {
  5661. Matrix.IdentityToRef(result);
  5662. }
  5663. else {
  5664. 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);
  5665. }
  5666. return this;
  5667. };
  5668. // Statics
  5669. /**
  5670. * Creates a matrix from an array
  5671. * @param array defines the source array
  5672. * @param offset defines an offset in the source array
  5673. * @returns a new Matrix set from the starting index of the given array
  5674. */
  5675. Matrix.FromArray = function (array, offset) {
  5676. var result = new Matrix();
  5677. if (!offset) {
  5678. offset = 0;
  5679. }
  5680. Matrix.FromArrayToRef(array, offset, result);
  5681. return result;
  5682. };
  5683. /**
  5684. * Copy the content of an array into a given matrix
  5685. * @param array defines the source array
  5686. * @param offset defines an offset in the source array
  5687. * @param result defines the target matrix
  5688. */
  5689. Matrix.FromArrayToRef = function (array, offset, result) {
  5690. for (var index = 0; index < 16; index++) {
  5691. result.m[index] = array[index + offset];
  5692. }
  5693. result._markAsUpdated();
  5694. };
  5695. /**
  5696. * Stores an array into a matrix after having multiplied each component by a given factor
  5697. * @param array defines the source array
  5698. * @param offset defines the offset in the source array
  5699. * @param scale defines the scaling factor
  5700. * @param result defines the target matrix
  5701. */
  5702. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5703. for (var index = 0; index < 16; index++) {
  5704. result.m[index] = array[index + offset] * scale;
  5705. }
  5706. result._markAsUpdated();
  5707. };
  5708. /**
  5709. * Stores a list of values (16) inside a given matrix
  5710. * @param initialM11 defines 1st value of 1st row
  5711. * @param initialM12 defines 2nd value of 1st row
  5712. * @param initialM13 defines 3rd value of 1st row
  5713. * @param initialM14 defines 4th value of 1st row
  5714. * @param initialM21 defines 1st value of 2nd row
  5715. * @param initialM22 defines 2nd value of 2nd row
  5716. * @param initialM23 defines 3rd value of 2nd row
  5717. * @param initialM24 defines 4th value of 2nd row
  5718. * @param initialM31 defines 1st value of 3rd row
  5719. * @param initialM32 defines 2nd value of 3rd row
  5720. * @param initialM33 defines 3rd value of 3rd row
  5721. * @param initialM34 defines 4th value of 3rd row
  5722. * @param initialM41 defines 1st value of 4th row
  5723. * @param initialM42 defines 2nd value of 4th row
  5724. * @param initialM43 defines 3rd value of 4th row
  5725. * @param initialM44 defines 4th value of 4th row
  5726. * @param result defines the target matrix
  5727. */
  5728. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5729. result.m[0] = initialM11;
  5730. result.m[1] = initialM12;
  5731. result.m[2] = initialM13;
  5732. result.m[3] = initialM14;
  5733. result.m[4] = initialM21;
  5734. result.m[5] = initialM22;
  5735. result.m[6] = initialM23;
  5736. result.m[7] = initialM24;
  5737. result.m[8] = initialM31;
  5738. result.m[9] = initialM32;
  5739. result.m[10] = initialM33;
  5740. result.m[11] = initialM34;
  5741. result.m[12] = initialM41;
  5742. result.m[13] = initialM42;
  5743. result.m[14] = initialM43;
  5744. result.m[15] = initialM44;
  5745. result._markAsUpdated();
  5746. };
  5747. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5748. /**
  5749. * Gets an identity matrix that must not be updated
  5750. */
  5751. get: function () {
  5752. return Matrix._identityReadOnly;
  5753. },
  5754. enumerable: true,
  5755. configurable: true
  5756. });
  5757. /**
  5758. * Creates new matrix from a list of values (16)
  5759. * @param initialM11 defines 1st value of 1st row
  5760. * @param initialM12 defines 2nd value of 1st row
  5761. * @param initialM13 defines 3rd value of 1st row
  5762. * @param initialM14 defines 4th value of 1st row
  5763. * @param initialM21 defines 1st value of 2nd row
  5764. * @param initialM22 defines 2nd value of 2nd row
  5765. * @param initialM23 defines 3rd value of 2nd row
  5766. * @param initialM24 defines 4th value of 2nd row
  5767. * @param initialM31 defines 1st value of 3rd row
  5768. * @param initialM32 defines 2nd value of 3rd row
  5769. * @param initialM33 defines 3rd value of 3rd row
  5770. * @param initialM34 defines 4th value of 3rd row
  5771. * @param initialM41 defines 1st value of 4th row
  5772. * @param initialM42 defines 2nd value of 4th row
  5773. * @param initialM43 defines 3rd value of 4th row
  5774. * @param initialM44 defines 4th value of 4th row
  5775. * @returns the new matrix
  5776. */
  5777. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5778. var result = new Matrix();
  5779. result.m[0] = initialM11;
  5780. result.m[1] = initialM12;
  5781. result.m[2] = initialM13;
  5782. result.m[3] = initialM14;
  5783. result.m[4] = initialM21;
  5784. result.m[5] = initialM22;
  5785. result.m[6] = initialM23;
  5786. result.m[7] = initialM24;
  5787. result.m[8] = initialM31;
  5788. result.m[9] = initialM32;
  5789. result.m[10] = initialM33;
  5790. result.m[11] = initialM34;
  5791. result.m[12] = initialM41;
  5792. result.m[13] = initialM42;
  5793. result.m[14] = initialM43;
  5794. result.m[15] = initialM44;
  5795. return result;
  5796. };
  5797. /**
  5798. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5799. * @param scale defines the scale vector3
  5800. * @param rotation defines the rotation quaternion
  5801. * @param translation defines the translation vector3
  5802. * @returns a new matrix
  5803. */
  5804. Matrix.Compose = function (scale, rotation, translation) {
  5805. var result = Matrix.Identity();
  5806. Matrix.ComposeToRef(scale, rotation, translation, result);
  5807. return result;
  5808. };
  5809. /**
  5810. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5811. * @param scale defines the scale vector3
  5812. * @param rotation defines the rotation quaternion
  5813. * @param translation defines the translation vector3
  5814. * @param result defines the target matrix
  5815. */
  5816. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5817. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5818. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5819. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5820. result.setTranslation(translation);
  5821. };
  5822. /**
  5823. * Creates a new identity matrix
  5824. * @returns a new identity matrix
  5825. */
  5826. Matrix.Identity = function () {
  5827. 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);
  5828. };
  5829. /**
  5830. * Creates a new identity matrix and stores the result in a given matrix
  5831. * @param result defines the target matrix
  5832. */
  5833. Matrix.IdentityToRef = function (result) {
  5834. 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);
  5835. };
  5836. /**
  5837. * Creates a new zero matrix
  5838. * @returns a new zero matrix
  5839. */
  5840. Matrix.Zero = function () {
  5841. 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);
  5842. };
  5843. /**
  5844. * Creates a new rotation matrix for "angle" radians around the X axis
  5845. * @param angle defines the angle (in radians) to use
  5846. * @return the new matrix
  5847. */
  5848. Matrix.RotationX = function (angle) {
  5849. var result = new Matrix();
  5850. Matrix.RotationXToRef(angle, result);
  5851. return result;
  5852. };
  5853. /**
  5854. * Creates a new matrix as the invert of a given matrix
  5855. * @param source defines the source matrix
  5856. * @returns the new matrix
  5857. */
  5858. Matrix.Invert = function (source) {
  5859. var result = new Matrix();
  5860. source.invertToRef(result);
  5861. return result;
  5862. };
  5863. /**
  5864. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5865. * @param angle defines the angle (in radians) to use
  5866. * @param result defines the target matrix
  5867. */
  5868. Matrix.RotationXToRef = function (angle, result) {
  5869. var s = Math.sin(angle);
  5870. var c = Math.cos(angle);
  5871. result.m[0] = 1.0;
  5872. result.m[15] = 1.0;
  5873. result.m[5] = c;
  5874. result.m[10] = c;
  5875. result.m[9] = -s;
  5876. result.m[6] = s;
  5877. result.m[1] = 0.0;
  5878. result.m[2] = 0.0;
  5879. result.m[3] = 0.0;
  5880. result.m[4] = 0.0;
  5881. result.m[7] = 0.0;
  5882. result.m[8] = 0.0;
  5883. result.m[11] = 0.0;
  5884. result.m[12] = 0.0;
  5885. result.m[13] = 0.0;
  5886. result.m[14] = 0.0;
  5887. result._markAsUpdated();
  5888. };
  5889. /**
  5890. * Creates a new rotation matrix for "angle" radians around the Y axis
  5891. * @param angle defines the angle (in radians) to use
  5892. * @return the new matrix
  5893. */
  5894. Matrix.RotationY = function (angle) {
  5895. var result = new Matrix();
  5896. Matrix.RotationYToRef(angle, result);
  5897. return result;
  5898. };
  5899. /**
  5900. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5901. * @param angle defines the angle (in radians) to use
  5902. * @param result defines the target matrix
  5903. */
  5904. Matrix.RotationYToRef = function (angle, result) {
  5905. var s = Math.sin(angle);
  5906. var c = Math.cos(angle);
  5907. result.m[5] = 1.0;
  5908. result.m[15] = 1.0;
  5909. result.m[0] = c;
  5910. result.m[2] = -s;
  5911. result.m[8] = s;
  5912. result.m[10] = c;
  5913. result.m[1] = 0.0;
  5914. result.m[3] = 0.0;
  5915. result.m[4] = 0.0;
  5916. result.m[6] = 0.0;
  5917. result.m[7] = 0.0;
  5918. result.m[9] = 0.0;
  5919. result.m[11] = 0.0;
  5920. result.m[12] = 0.0;
  5921. result.m[13] = 0.0;
  5922. result.m[14] = 0.0;
  5923. result._markAsUpdated();
  5924. };
  5925. /**
  5926. * Creates a new rotation matrix for "angle" radians around the Z axis
  5927. * @param angle defines the angle (in radians) to use
  5928. * @return the new matrix
  5929. */
  5930. Matrix.RotationZ = function (angle) {
  5931. var result = new Matrix();
  5932. Matrix.RotationZToRef(angle, result);
  5933. return result;
  5934. };
  5935. /**
  5936. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5937. * @param angle defines the angle (in radians) to use
  5938. * @param result defines the target matrix
  5939. */
  5940. Matrix.RotationZToRef = function (angle, result) {
  5941. var s = Math.sin(angle);
  5942. var c = Math.cos(angle);
  5943. result.m[10] = 1.0;
  5944. result.m[15] = 1.0;
  5945. result.m[0] = c;
  5946. result.m[1] = s;
  5947. result.m[4] = -s;
  5948. result.m[5] = c;
  5949. result.m[2] = 0.0;
  5950. result.m[3] = 0.0;
  5951. result.m[6] = 0.0;
  5952. result.m[7] = 0.0;
  5953. result.m[8] = 0.0;
  5954. result.m[9] = 0.0;
  5955. result.m[11] = 0.0;
  5956. result.m[12] = 0.0;
  5957. result.m[13] = 0.0;
  5958. result.m[14] = 0.0;
  5959. result._markAsUpdated();
  5960. };
  5961. /**
  5962. * Creates a new rotation matrix for "angle" radians around the given axis
  5963. * @param axis defines the axis to use
  5964. * @param angle defines the angle (in radians) to use
  5965. * @return the new matrix
  5966. */
  5967. Matrix.RotationAxis = function (axis, angle) {
  5968. var result = Matrix.Zero();
  5969. Matrix.RotationAxisToRef(axis, angle, result);
  5970. return result;
  5971. };
  5972. /**
  5973. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5974. * @param axis defines the axis to use
  5975. * @param angle defines the angle (in radians) to use
  5976. * @param result defines the target matrix
  5977. */
  5978. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5979. var s = Math.sin(-angle);
  5980. var c = Math.cos(-angle);
  5981. var c1 = 1 - c;
  5982. axis.normalize();
  5983. result.m[0] = (axis.x * axis.x) * c1 + c;
  5984. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5985. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5986. result.m[3] = 0.0;
  5987. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5988. result.m[5] = (axis.y * axis.y) * c1 + c;
  5989. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5990. result.m[7] = 0.0;
  5991. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5992. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5993. result.m[10] = (axis.z * axis.z) * c1 + c;
  5994. result.m[11] = 0.0;
  5995. result.m[15] = 1.0;
  5996. result._markAsUpdated();
  5997. };
  5998. /**
  5999. * Creates a rotation matrix
  6000. * @param yaw defines the yaw angle in radians (Y axis)
  6001. * @param pitch defines the pitch angle in radians (X axis)
  6002. * @param roll defines the roll angle in radians (X axis)
  6003. * @returns the new rotation matrix
  6004. */
  6005. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6006. var result = new Matrix();
  6007. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6008. return result;
  6009. };
  6010. /**
  6011. * Creates a rotation matrix and stores it in a given matrix
  6012. * @param yaw defines the yaw angle in radians (Y axis)
  6013. * @param pitch defines the pitch angle in radians (X axis)
  6014. * @param roll defines the roll angle in radians (X axis)
  6015. * @param result defines the target matrix
  6016. */
  6017. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6018. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6019. this._tempQuaternion.toRotationMatrix(result);
  6020. };
  6021. /**
  6022. * Creates a scaling matrix
  6023. * @param x defines the scale factor on X axis
  6024. * @param y defines the scale factor on Y axis
  6025. * @param z defines the scale factor on Z axis
  6026. * @returns the new matrix
  6027. */
  6028. Matrix.Scaling = function (x, y, z) {
  6029. var result = Matrix.Zero();
  6030. Matrix.ScalingToRef(x, y, z, result);
  6031. return result;
  6032. };
  6033. /**
  6034. * Creates a scaling matrix and stores it in a given matrix
  6035. * @param x defines the scale factor on X axis
  6036. * @param y defines the scale factor on Y axis
  6037. * @param z defines the scale factor on Z axis
  6038. * @param result defines the target matrix
  6039. */
  6040. Matrix.ScalingToRef = function (x, y, z, result) {
  6041. result.m[0] = x;
  6042. result.m[1] = 0.0;
  6043. result.m[2] = 0.0;
  6044. result.m[3] = 0.0;
  6045. result.m[4] = 0.0;
  6046. result.m[5] = y;
  6047. result.m[6] = 0.0;
  6048. result.m[7] = 0.0;
  6049. result.m[8] = 0.0;
  6050. result.m[9] = 0.0;
  6051. result.m[10] = z;
  6052. result.m[11] = 0.0;
  6053. result.m[12] = 0.0;
  6054. result.m[13] = 0.0;
  6055. result.m[14] = 0.0;
  6056. result.m[15] = 1.0;
  6057. result._markAsUpdated();
  6058. };
  6059. /**
  6060. * Creates a translation matrix
  6061. * @param x defines the translation on X axis
  6062. * @param y defines the translation on Y axis
  6063. * @param z defines the translationon Z axis
  6064. * @returns the new matrix
  6065. */
  6066. Matrix.Translation = function (x, y, z) {
  6067. var result = Matrix.Identity();
  6068. Matrix.TranslationToRef(x, y, z, result);
  6069. return result;
  6070. };
  6071. /**
  6072. * Creates a translation matrix and stores it in a given matrix
  6073. * @param x defines the translation on X axis
  6074. * @param y defines the translation on Y axis
  6075. * @param z defines the translationon Z axis
  6076. * @param result defines the target matrix
  6077. */
  6078. Matrix.TranslationToRef = function (x, y, z, result) {
  6079. 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);
  6080. };
  6081. /**
  6082. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6083. * @param startValue defines the start value
  6084. * @param endValue defines the end value
  6085. * @param gradient defines the gradient factor
  6086. * @returns the new matrix
  6087. */
  6088. Matrix.Lerp = function (startValue, endValue, gradient) {
  6089. var result = Matrix.Zero();
  6090. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6091. return result;
  6092. };
  6093. /**
  6094. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6095. * @param startValue defines the start value
  6096. * @param endValue defines the end value
  6097. * @param gradient defines the gradient factor
  6098. * @param result defines the Matrix object where to store data
  6099. */
  6100. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6101. for (var index = 0; index < 16; index++) {
  6102. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6103. }
  6104. result._markAsUpdated();
  6105. };
  6106. /**
  6107. * Builds a new matrix whose values are computed by:
  6108. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6109. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6110. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6111. * @param startValue defines the first matrix
  6112. * @param endValue defines the second matrix
  6113. * @param gradient defines the gradient between the two matrices
  6114. * @returns the new matrix
  6115. */
  6116. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6117. var result = Matrix.Zero();
  6118. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6119. return result;
  6120. };
  6121. /**
  6122. * Update a matrix to values which are computed by:
  6123. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6124. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6125. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6126. * @param startValue defines the first matrix
  6127. * @param endValue defines the second matrix
  6128. * @param gradient defines the gradient between the two matrices
  6129. * @param result defines the target matrix
  6130. */
  6131. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6132. var startScale = MathTmp.Vector3[0];
  6133. var startRotation = MathTmp.Quaternion[0];
  6134. var startTranslation = MathTmp.Vector3[1];
  6135. startValue.decompose(startScale, startRotation, startTranslation);
  6136. var endScale = MathTmp.Vector3[2];
  6137. var endRotation = MathTmp.Quaternion[1];
  6138. var endTranslation = MathTmp.Vector3[3];
  6139. endValue.decompose(endScale, endRotation, endTranslation);
  6140. var resultScale = MathTmp.Vector3[4];
  6141. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6142. var resultRotation = MathTmp.Quaternion[2];
  6143. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6144. var resultTranslation = MathTmp.Vector3[5];
  6145. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6146. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6147. };
  6148. /**
  6149. * 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"
  6150. * This function works in left handed mode
  6151. * @param eye defines the final position of the entity
  6152. * @param target defines where the entity should look at
  6153. * @param up defines the up vector for the entity
  6154. * @returns the new matrix
  6155. */
  6156. Matrix.LookAtLH = function (eye, target, up) {
  6157. var result = Matrix.Zero();
  6158. Matrix.LookAtLHToRef(eye, target, up, result);
  6159. return result;
  6160. };
  6161. /**
  6162. * 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".
  6163. * This function works in left handed mode
  6164. * @param eye defines the final position of the entity
  6165. * @param target defines where the entity should look at
  6166. * @param up defines the up vector for the entity
  6167. * @param result defines the target matrix
  6168. */
  6169. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6170. // Z axis
  6171. target.subtractToRef(eye, this._zAxis);
  6172. this._zAxis.normalize();
  6173. // X axis
  6174. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6175. if (this._xAxis.lengthSquared() === 0) {
  6176. this._xAxis.x = 1.0;
  6177. }
  6178. else {
  6179. this._xAxis.normalize();
  6180. }
  6181. // Y axis
  6182. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6183. this._yAxis.normalize();
  6184. // Eye angles
  6185. var ex = -Vector3.Dot(this._xAxis, eye);
  6186. var ey = -Vector3.Dot(this._yAxis, eye);
  6187. var ez = -Vector3.Dot(this._zAxis, eye);
  6188. 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);
  6189. };
  6190. /**
  6191. * 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"
  6192. * This function works in right handed mode
  6193. * @param eye defines the final position of the entity
  6194. * @param target defines where the entity should look at
  6195. * @param up defines the up vector for the entity
  6196. * @returns the new matrix
  6197. */
  6198. Matrix.LookAtRH = function (eye, target, up) {
  6199. var result = Matrix.Zero();
  6200. Matrix.LookAtRHToRef(eye, target, up, result);
  6201. return result;
  6202. };
  6203. /**
  6204. * 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".
  6205. * This function works in right handed mode
  6206. * @param eye defines the final position of the entity
  6207. * @param target defines where the entity should look at
  6208. * @param up defines the up vector for the entity
  6209. * @param result defines the target matrix
  6210. */
  6211. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6212. // Z axis
  6213. eye.subtractToRef(target, this._zAxis);
  6214. this._zAxis.normalize();
  6215. // X axis
  6216. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6217. if (this._xAxis.lengthSquared() === 0) {
  6218. this._xAxis.x = 1.0;
  6219. }
  6220. else {
  6221. this._xAxis.normalize();
  6222. }
  6223. // Y axis
  6224. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6225. this._yAxis.normalize();
  6226. // Eye angles
  6227. var ex = -Vector3.Dot(this._xAxis, eye);
  6228. var ey = -Vector3.Dot(this._yAxis, eye);
  6229. var ez = -Vector3.Dot(this._zAxis, eye);
  6230. 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);
  6231. };
  6232. /**
  6233. * Create a left-handed orthographic projection matrix
  6234. * @param width defines the viewport width
  6235. * @param height defines the viewport height
  6236. * @param znear defines the near clip plane
  6237. * @param zfar defines the far clip plane
  6238. * @returns a new matrix as a left-handed orthographic projection matrix
  6239. */
  6240. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6241. var matrix = Matrix.Zero();
  6242. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6243. return matrix;
  6244. };
  6245. /**
  6246. * Store a left-handed orthographic projection to a given matrix
  6247. * @param width defines the viewport width
  6248. * @param height defines the viewport height
  6249. * @param znear defines the near clip plane
  6250. * @param zfar defines the far clip plane
  6251. * @param result defines the target matrix
  6252. */
  6253. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6254. var n = znear;
  6255. var f = zfar;
  6256. var a = 2.0 / width;
  6257. var b = 2.0 / height;
  6258. var c = 2.0 / (f - n);
  6259. var d = -(f + n) / (f - n);
  6260. 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);
  6261. };
  6262. /**
  6263. * Create a left-handed orthographic projection matrix
  6264. * @param left defines the viewport left coordinate
  6265. * @param right defines the viewport right coordinate
  6266. * @param bottom defines the viewport bottom coordinate
  6267. * @param top defines the viewport top coordinate
  6268. * @param znear defines the near clip plane
  6269. * @param zfar defines the far clip plane
  6270. * @returns a new matrix as a left-handed orthographic projection matrix
  6271. */
  6272. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6273. var matrix = Matrix.Zero();
  6274. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6275. return matrix;
  6276. };
  6277. /**
  6278. * Stores a left-handed orthographic projection into a given matrix
  6279. * @param left defines the viewport left coordinate
  6280. * @param right defines the viewport right coordinate
  6281. * @param bottom defines the viewport bottom coordinate
  6282. * @param top defines the viewport top coordinate
  6283. * @param znear defines the near clip plane
  6284. * @param zfar defines the far clip plane
  6285. * @param result defines the target matrix
  6286. */
  6287. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6288. var n = znear;
  6289. var f = zfar;
  6290. var a = 2.0 / (right - left);
  6291. var b = 2.0 / (top - bottom);
  6292. var c = 2.0 / (f - n);
  6293. var d = -(f + n) / (f - n);
  6294. var i0 = (left + right) / (left - right);
  6295. var i1 = (top + bottom) / (bottom - top);
  6296. 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);
  6297. };
  6298. /**
  6299. * Creates a right-handed orthographic projection matrix
  6300. * @param left defines the viewport left coordinate
  6301. * @param right defines the viewport right coordinate
  6302. * @param bottom defines the viewport bottom coordinate
  6303. * @param top defines the viewport top coordinate
  6304. * @param znear defines the near clip plane
  6305. * @param zfar defines the far clip plane
  6306. * @returns a new matrix as a right-handed orthographic projection matrix
  6307. */
  6308. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6309. var matrix = Matrix.Zero();
  6310. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6311. return matrix;
  6312. };
  6313. /**
  6314. * Stores a right-handed orthographic projection into a given matrix
  6315. * @param left defines the viewport left coordinate
  6316. * @param right defines the viewport right coordinate
  6317. * @param bottom defines the viewport bottom coordinate
  6318. * @param top defines the viewport top coordinate
  6319. * @param znear defines the near clip plane
  6320. * @param zfar defines the far clip plane
  6321. * @param result defines the target matrix
  6322. */
  6323. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6324. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6325. result.m[10] *= -1.0;
  6326. };
  6327. /**
  6328. * Creates a left-handed perspective projection matrix
  6329. * @param width defines the viewport width
  6330. * @param height defines the viewport height
  6331. * @param znear defines the near clip plane
  6332. * @param zfar defines the far clip plane
  6333. * @returns a new matrix as a left-handed perspective projection matrix
  6334. */
  6335. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6336. var matrix = Matrix.Zero();
  6337. var n = znear;
  6338. var f = zfar;
  6339. var a = 2.0 * n / width;
  6340. var b = 2.0 * n / height;
  6341. var c = (f + n) / (f - n);
  6342. var d = -2.0 * f * n / (f - n);
  6343. 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);
  6344. return matrix;
  6345. };
  6346. /**
  6347. * Creates a left-handed perspective projection matrix
  6348. * @param fov defines the horizontal field of view
  6349. * @param aspect defines the aspect ratio
  6350. * @param znear defines the near clip plane
  6351. * @param zfar defines the far clip plane
  6352. * @returns a new matrix as a left-handed perspective projection matrix
  6353. */
  6354. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6355. var matrix = Matrix.Zero();
  6356. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6357. return matrix;
  6358. };
  6359. /**
  6360. * Stores a left-handed perspective projection into a given matrix
  6361. * @param fov defines the horizontal field of view
  6362. * @param aspect defines the aspect ratio
  6363. * @param znear defines the near clip plane
  6364. * @param zfar defines the far clip plane
  6365. * @param result defines the target matrix
  6366. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6367. */
  6368. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6369. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6370. var n = znear;
  6371. var f = zfar;
  6372. var t = 1.0 / (Math.tan(fov * 0.5));
  6373. var a = isVerticalFovFixed ? (t / aspect) : t;
  6374. var b = isVerticalFovFixed ? t : (t * aspect);
  6375. var c = (f + n) / (f - n);
  6376. var d = -2.0 * f * n / (f - n);
  6377. 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);
  6378. };
  6379. /**
  6380. * Creates a right-handed perspective projection matrix
  6381. * @param fov defines the horizontal field of view
  6382. * @param aspect defines the aspect ratio
  6383. * @param znear defines the near clip plane
  6384. * @param zfar defines the far clip plane
  6385. * @returns a new matrix as a right-handed perspective projection matrix
  6386. */
  6387. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6388. var matrix = Matrix.Zero();
  6389. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6390. return matrix;
  6391. };
  6392. /**
  6393. * Stores a right-handed perspective projection into a given matrix
  6394. * @param fov defines the horizontal field of view
  6395. * @param aspect defines the aspect ratio
  6396. * @param znear defines the near clip plane
  6397. * @param zfar defines the far clip plane
  6398. * @param result defines the target matrix
  6399. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6400. */
  6401. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6402. //alternatively this could be expressed as:
  6403. // m = PerspectiveFovLHToRef
  6404. // m[10] *= -1.0;
  6405. // m[11] *= -1.0;
  6406. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6407. var n = znear;
  6408. var f = zfar;
  6409. var t = 1.0 / (Math.tan(fov * 0.5));
  6410. var a = isVerticalFovFixed ? (t / aspect) : t;
  6411. var b = isVerticalFovFixed ? t : (t * aspect);
  6412. var c = -(f + n) / (f - n);
  6413. var d = -2 * f * n / (f - n);
  6414. 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);
  6415. };
  6416. /**
  6417. * Stores a perspective projection for WebVR info a given matrix
  6418. * @param fov defines the field of view
  6419. * @param znear defines the near clip plane
  6420. * @param zfar defines the far clip plane
  6421. * @param result defines the target matrix
  6422. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6423. */
  6424. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6425. if (rightHanded === void 0) { rightHanded = false; }
  6426. var rightHandedFactor = rightHanded ? -1 : 1;
  6427. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6428. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6429. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6430. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6431. var xScale = 2.0 / (leftTan + rightTan);
  6432. var yScale = 2.0 / (upTan + downTan);
  6433. result.m[0] = xScale;
  6434. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6435. result.m[5] = yScale;
  6436. result.m[6] = result.m[7] = 0.0;
  6437. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6438. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6439. result.m[10] = -zfar / (znear - zfar);
  6440. result.m[11] = 1.0 * rightHandedFactor;
  6441. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6442. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6443. result._markAsUpdated();
  6444. };
  6445. /**
  6446. * Computes a complete transformation matrix
  6447. * @param viewport defines the viewport to use
  6448. * @param world defines the world matrix
  6449. * @param view defines the view matrix
  6450. * @param projection defines the projection matrix
  6451. * @param zmin defines the near clip plane
  6452. * @param zmax defines the far clip plane
  6453. * @returns the transformation matrix
  6454. */
  6455. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6456. var cw = viewport.width;
  6457. var ch = viewport.height;
  6458. var cx = viewport.x;
  6459. var cy = viewport.y;
  6460. 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);
  6461. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6462. };
  6463. /**
  6464. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6465. * @param matrix defines the matrix to use
  6466. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6467. */
  6468. Matrix.GetAsMatrix2x2 = function (matrix) {
  6469. return new Float32Array([
  6470. matrix.m[0], matrix.m[1],
  6471. matrix.m[4], matrix.m[5]
  6472. ]);
  6473. };
  6474. /**
  6475. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6476. * @param matrix defines the matrix to use
  6477. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6478. */
  6479. Matrix.GetAsMatrix3x3 = function (matrix) {
  6480. return new Float32Array([
  6481. matrix.m[0], matrix.m[1], matrix.m[2],
  6482. matrix.m[4], matrix.m[5], matrix.m[6],
  6483. matrix.m[8], matrix.m[9], matrix.m[10]
  6484. ]);
  6485. };
  6486. /**
  6487. * Compute the transpose of a given matrix
  6488. * @param matrix defines the matrix to transpose
  6489. * @returns the new matrix
  6490. */
  6491. Matrix.Transpose = function (matrix) {
  6492. var result = new Matrix();
  6493. Matrix.TransposeToRef(matrix, result);
  6494. return result;
  6495. };
  6496. /**
  6497. * Compute the transpose of a matrix and store it in a target matrix
  6498. * @param matrix defines the matrix to transpose
  6499. * @param result defines the target matrix
  6500. */
  6501. Matrix.TransposeToRef = function (matrix, result) {
  6502. result.m[0] = matrix.m[0];
  6503. result.m[1] = matrix.m[4];
  6504. result.m[2] = matrix.m[8];
  6505. result.m[3] = matrix.m[12];
  6506. result.m[4] = matrix.m[1];
  6507. result.m[5] = matrix.m[5];
  6508. result.m[6] = matrix.m[9];
  6509. result.m[7] = matrix.m[13];
  6510. result.m[8] = matrix.m[2];
  6511. result.m[9] = matrix.m[6];
  6512. result.m[10] = matrix.m[10];
  6513. result.m[11] = matrix.m[14];
  6514. result.m[12] = matrix.m[3];
  6515. result.m[13] = matrix.m[7];
  6516. result.m[14] = matrix.m[11];
  6517. result.m[15] = matrix.m[15];
  6518. };
  6519. /**
  6520. * Computes a reflection matrix from a plane
  6521. * @param plane defines the reflection plane
  6522. * @returns a new matrix
  6523. */
  6524. Matrix.Reflection = function (plane) {
  6525. var matrix = new Matrix();
  6526. Matrix.ReflectionToRef(plane, matrix);
  6527. return matrix;
  6528. };
  6529. /**
  6530. * Computes a reflection matrix from a plane
  6531. * @param plane defines the reflection plane
  6532. * @param result defines the target matrix
  6533. */
  6534. Matrix.ReflectionToRef = function (plane, result) {
  6535. plane.normalize();
  6536. var x = plane.normal.x;
  6537. var y = plane.normal.y;
  6538. var z = plane.normal.z;
  6539. var temp = -2 * x;
  6540. var temp2 = -2 * y;
  6541. var temp3 = -2 * z;
  6542. result.m[0] = (temp * x) + 1;
  6543. result.m[1] = temp2 * x;
  6544. result.m[2] = temp3 * x;
  6545. result.m[3] = 0.0;
  6546. result.m[4] = temp * y;
  6547. result.m[5] = (temp2 * y) + 1;
  6548. result.m[6] = temp3 * y;
  6549. result.m[7] = 0.0;
  6550. result.m[8] = temp * z;
  6551. result.m[9] = temp2 * z;
  6552. result.m[10] = (temp3 * z) + 1;
  6553. result.m[11] = 0.0;
  6554. result.m[12] = temp * plane.d;
  6555. result.m[13] = temp2 * plane.d;
  6556. result.m[14] = temp3 * plane.d;
  6557. result.m[15] = 1.0;
  6558. result._markAsUpdated();
  6559. };
  6560. /**
  6561. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6562. * @param xaxis defines the value of the 1st axis
  6563. * @param yaxis defines the value of the 2nd axis
  6564. * @param zaxis defines the value of the 3rd axis
  6565. * @param result defines the target matrix
  6566. */
  6567. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6568. result.m[0] = xaxis.x;
  6569. result.m[1] = xaxis.y;
  6570. result.m[2] = xaxis.z;
  6571. result.m[3] = 0.0;
  6572. result.m[4] = yaxis.x;
  6573. result.m[5] = yaxis.y;
  6574. result.m[6] = yaxis.z;
  6575. result.m[7] = 0.0;
  6576. result.m[8] = zaxis.x;
  6577. result.m[9] = zaxis.y;
  6578. result.m[10] = zaxis.z;
  6579. result.m[11] = 0.0;
  6580. result.m[12] = 0.0;
  6581. result.m[13] = 0.0;
  6582. result.m[14] = 0.0;
  6583. result.m[15] = 1.0;
  6584. result._markAsUpdated();
  6585. };
  6586. /**
  6587. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6588. * @param quat defines the quaternion to use
  6589. * @param result defines the target matrix
  6590. */
  6591. Matrix.FromQuaternionToRef = function (quat, result) {
  6592. var xx = quat.x * quat.x;
  6593. var yy = quat.y * quat.y;
  6594. var zz = quat.z * quat.z;
  6595. var xy = quat.x * quat.y;
  6596. var zw = quat.z * quat.w;
  6597. var zx = quat.z * quat.x;
  6598. var yw = quat.y * quat.w;
  6599. var yz = quat.y * quat.z;
  6600. var xw = quat.x * quat.w;
  6601. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6602. result.m[1] = 2.0 * (xy + zw);
  6603. result.m[2] = 2.0 * (zx - yw);
  6604. result.m[3] = 0.0;
  6605. result.m[4] = 2.0 * (xy - zw);
  6606. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6607. result.m[6] = 2.0 * (yz + xw);
  6608. result.m[7] = 0.0;
  6609. result.m[8] = 2.0 * (zx + yw);
  6610. result.m[9] = 2.0 * (yz - xw);
  6611. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6612. result.m[11] = 0.0;
  6613. result.m[12] = 0.0;
  6614. result.m[13] = 0.0;
  6615. result.m[14] = 0.0;
  6616. result.m[15] = 1.0;
  6617. result._markAsUpdated();
  6618. };
  6619. Matrix._tempQuaternion = new Quaternion();
  6620. Matrix._xAxis = Vector3.Zero();
  6621. Matrix._yAxis = Vector3.Zero();
  6622. Matrix._zAxis = Vector3.Zero();
  6623. Matrix._updateFlagSeed = 0;
  6624. Matrix._identityReadOnly = Matrix.Identity();
  6625. return Matrix;
  6626. }());
  6627. BABYLON.Matrix = Matrix;
  6628. var Plane = /** @class */ (function () {
  6629. /**
  6630. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6631. */
  6632. function Plane(a, b, c, d) {
  6633. this.normal = new Vector3(a, b, c);
  6634. this.d = d;
  6635. }
  6636. /**
  6637. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6638. */
  6639. Plane.prototype.asArray = function () {
  6640. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6641. };
  6642. // Methods
  6643. /**
  6644. * Returns a new plane copied from the current Plane.
  6645. */
  6646. Plane.prototype.clone = function () {
  6647. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6648. };
  6649. /**
  6650. * Returns the string "Plane".
  6651. */
  6652. Plane.prototype.getClassName = function () {
  6653. return "Plane";
  6654. };
  6655. /**
  6656. * Returns the Plane hash code.
  6657. */
  6658. Plane.prototype.getHashCode = function () {
  6659. var hash = this.normal.getHashCode();
  6660. hash = (hash * 397) ^ (this.d || 0);
  6661. return hash;
  6662. };
  6663. /**
  6664. * Normalize the current Plane in place.
  6665. * Returns the updated Plane.
  6666. */
  6667. Plane.prototype.normalize = function () {
  6668. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6669. var magnitude = 0.0;
  6670. if (norm !== 0) {
  6671. magnitude = 1.0 / norm;
  6672. }
  6673. this.normal.x *= magnitude;
  6674. this.normal.y *= magnitude;
  6675. this.normal.z *= magnitude;
  6676. this.d *= magnitude;
  6677. return this;
  6678. };
  6679. /**
  6680. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6681. */
  6682. Plane.prototype.transform = function (transformation) {
  6683. var transposedMatrix = Matrix.Transpose(transformation);
  6684. var x = this.normal.x;
  6685. var y = this.normal.y;
  6686. var z = this.normal.z;
  6687. var d = this.d;
  6688. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6689. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6690. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6691. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6692. return new Plane(normalX, normalY, normalZ, finalD);
  6693. };
  6694. /**
  6695. * Returns the dot product (float) of the point coordinates and the plane normal.
  6696. */
  6697. Plane.prototype.dotCoordinate = function (point) {
  6698. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6699. };
  6700. /**
  6701. * Updates the current Plane from the plane defined by the three given points.
  6702. * Returns the updated Plane.
  6703. */
  6704. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6705. var x1 = point2.x - point1.x;
  6706. var y1 = point2.y - point1.y;
  6707. var z1 = point2.z - point1.z;
  6708. var x2 = point3.x - point1.x;
  6709. var y2 = point3.y - point1.y;
  6710. var z2 = point3.z - point1.z;
  6711. var yz = (y1 * z2) - (z1 * y2);
  6712. var xz = (z1 * x2) - (x1 * z2);
  6713. var xy = (x1 * y2) - (y1 * x2);
  6714. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6715. var invPyth;
  6716. if (pyth !== 0) {
  6717. invPyth = 1.0 / pyth;
  6718. }
  6719. else {
  6720. invPyth = 0.0;
  6721. }
  6722. this.normal.x = yz * invPyth;
  6723. this.normal.y = xz * invPyth;
  6724. this.normal.z = xy * invPyth;
  6725. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6726. return this;
  6727. };
  6728. /**
  6729. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6730. */
  6731. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6732. var dot = Vector3.Dot(this.normal, direction);
  6733. return (dot <= epsilon);
  6734. };
  6735. /**
  6736. * Returns the signed distance (float) from the given point to the Plane.
  6737. */
  6738. Plane.prototype.signedDistanceTo = function (point) {
  6739. return Vector3.Dot(point, this.normal) + this.d;
  6740. };
  6741. // Statics
  6742. /**
  6743. * Returns a new Plane from the given array.
  6744. */
  6745. Plane.FromArray = function (array) {
  6746. return new Plane(array[0], array[1], array[2], array[3]);
  6747. };
  6748. /**
  6749. * Returns a new Plane defined by the three given points.
  6750. */
  6751. Plane.FromPoints = function (point1, point2, point3) {
  6752. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6753. result.copyFromPoints(point1, point2, point3);
  6754. return result;
  6755. };
  6756. /**
  6757. * Returns a new Plane the normal vector to this plane at the given origin point.
  6758. * Note : the vector "normal" is updated because normalized.
  6759. */
  6760. Plane.FromPositionAndNormal = function (origin, normal) {
  6761. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6762. normal.normalize();
  6763. result.normal = normal;
  6764. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6765. return result;
  6766. };
  6767. /**
  6768. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6769. */
  6770. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6771. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6772. return Vector3.Dot(point, normal) + d;
  6773. };
  6774. return Plane;
  6775. }());
  6776. BABYLON.Plane = Plane;
  6777. var Viewport = /** @class */ (function () {
  6778. /**
  6779. * Creates a Viewport object located at (x, y) and sized (width, height).
  6780. */
  6781. function Viewport(x, y, width, height) {
  6782. this.x = x;
  6783. this.y = y;
  6784. this.width = width;
  6785. this.height = height;
  6786. }
  6787. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6788. if (renderWidthOrEngine.getRenderWidth) {
  6789. var engine = renderWidthOrEngine;
  6790. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6791. }
  6792. var renderWidth = renderWidthOrEngine;
  6793. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6794. };
  6795. /**
  6796. * Returns a new Viewport copied from the current one.
  6797. */
  6798. Viewport.prototype.clone = function () {
  6799. return new Viewport(this.x, this.y, this.width, this.height);
  6800. };
  6801. return Viewport;
  6802. }());
  6803. BABYLON.Viewport = Viewport;
  6804. var Frustum = /** @class */ (function () {
  6805. function Frustum() {
  6806. }
  6807. /**
  6808. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6809. */
  6810. Frustum.GetPlanes = function (transform) {
  6811. var frustumPlanes = [];
  6812. for (var index = 0; index < 6; index++) {
  6813. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6814. }
  6815. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6816. return frustumPlanes;
  6817. };
  6818. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6819. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6820. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6821. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6822. frustumPlane.d = transform.m[15] + transform.m[14];
  6823. frustumPlane.normalize();
  6824. };
  6825. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6826. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6827. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6828. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6829. frustumPlane.d = transform.m[15] - transform.m[14];
  6830. frustumPlane.normalize();
  6831. };
  6832. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6833. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6834. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6835. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6836. frustumPlane.d = transform.m[15] + transform.m[12];
  6837. frustumPlane.normalize();
  6838. };
  6839. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6840. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6841. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6842. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6843. frustumPlane.d = transform.m[15] - transform.m[12];
  6844. frustumPlane.normalize();
  6845. };
  6846. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6847. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6848. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6849. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6850. frustumPlane.d = transform.m[15] - transform.m[13];
  6851. frustumPlane.normalize();
  6852. };
  6853. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6854. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6855. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6856. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6857. frustumPlane.d = transform.m[15] + transform.m[13];
  6858. frustumPlane.normalize();
  6859. };
  6860. /**
  6861. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6862. */
  6863. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6864. // Near
  6865. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6866. // Far
  6867. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6868. // Left
  6869. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6870. // Right
  6871. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6872. // Top
  6873. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6874. // Bottom
  6875. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6876. };
  6877. return Frustum;
  6878. }());
  6879. BABYLON.Frustum = Frustum;
  6880. /** Defines supported spaces */
  6881. var Space;
  6882. (function (Space) {
  6883. /** Local (object) space */
  6884. Space[Space["LOCAL"] = 0] = "LOCAL";
  6885. /** World space */
  6886. Space[Space["WORLD"] = 1] = "WORLD";
  6887. /** Bone space */
  6888. Space[Space["BONE"] = 2] = "BONE";
  6889. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6890. /** Defines the 3 main axes */
  6891. var Axis = /** @class */ (function () {
  6892. function Axis() {
  6893. }
  6894. /** X axis */
  6895. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6896. /** Y axis */
  6897. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6898. /** Z axis */
  6899. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6900. return Axis;
  6901. }());
  6902. BABYLON.Axis = Axis;
  6903. ;
  6904. var BezierCurve = /** @class */ (function () {
  6905. function BezierCurve() {
  6906. }
  6907. /**
  6908. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6909. */
  6910. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6911. // Extract X (which is equal to time here)
  6912. var f0 = 1 - 3 * x2 + 3 * x1;
  6913. var f1 = 3 * x2 - 6 * x1;
  6914. var f2 = 3 * x1;
  6915. var refinedT = t;
  6916. for (var i = 0; i < 5; i++) {
  6917. var refinedT2 = refinedT * refinedT;
  6918. var refinedT3 = refinedT2 * refinedT;
  6919. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6920. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6921. refinedT -= (x - t) * slope;
  6922. refinedT = Math.min(1, Math.max(0, refinedT));
  6923. }
  6924. // Resolve cubic bezier for the given x
  6925. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6926. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6927. Math.pow(refinedT, 3);
  6928. };
  6929. return BezierCurve;
  6930. }());
  6931. BABYLON.BezierCurve = BezierCurve;
  6932. /**
  6933. * Defines potential orientation for back face culling
  6934. */
  6935. var Orientation;
  6936. (function (Orientation) {
  6937. /**
  6938. * Clockwise
  6939. */
  6940. Orientation[Orientation["CW"] = 0] = "CW";
  6941. /** Counter clockwise */
  6942. Orientation[Orientation["CCW"] = 1] = "CCW";
  6943. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6944. /**
  6945. * Defines angle representation
  6946. */
  6947. var Angle = /** @class */ (function () {
  6948. /**
  6949. * Creates an Angle object of "radians" radians (float).
  6950. */
  6951. function Angle(radians) {
  6952. this._radians = radians;
  6953. if (this._radians < 0.0)
  6954. this._radians += (2.0 * Math.PI);
  6955. }
  6956. /**
  6957. * Get value in degrees
  6958. * @returns the Angle value in degrees (float)
  6959. */
  6960. Angle.prototype.degrees = function () {
  6961. return this._radians * 180.0 / Math.PI;
  6962. };
  6963. /**
  6964. * Get value in radians
  6965. * @returns the Angle value in radians (float)
  6966. */
  6967. Angle.prototype.radians = function () {
  6968. return this._radians;
  6969. };
  6970. /**
  6971. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6972. * @param a defines first vector
  6973. * @param b defines second vector
  6974. * @returns a new Angle
  6975. */
  6976. Angle.BetweenTwoPoints = function (a, b) {
  6977. var delta = b.subtract(a);
  6978. var theta = Math.atan2(delta.y, delta.x);
  6979. return new Angle(theta);
  6980. };
  6981. /**
  6982. * Gets a new Angle object from the given float in radians
  6983. * @param radians defines the angle value in radians
  6984. * @returns a new Angle
  6985. */
  6986. Angle.FromRadians = function (radians) {
  6987. return new Angle(radians);
  6988. };
  6989. /**
  6990. * Gets a new Angle object from the given float in degrees
  6991. * @param degrees defines the angle value in degrees
  6992. * @returns a new Angle
  6993. */
  6994. Angle.FromDegrees = function (degrees) {
  6995. return new Angle(degrees * Math.PI / 180.0);
  6996. };
  6997. return Angle;
  6998. }());
  6999. BABYLON.Angle = Angle;
  7000. /**
  7001. * This represents an arc in a 2d space.
  7002. */
  7003. var Arc2 = /** @class */ (function () {
  7004. /**
  7005. * Creates an Arc object from the three given points : start, middle and end.
  7006. * @param startPoint Defines the start point of the arc
  7007. * @param midPoint Defines the midlle point of the arc
  7008. * @param endPoint Defines the end point of the arc
  7009. */
  7010. function Arc2(
  7011. /** Defines the start point of the arc */
  7012. startPoint,
  7013. /** Defines the mid point of the arc */
  7014. midPoint,
  7015. /** Defines the end point of the arc */
  7016. endPoint) {
  7017. this.startPoint = startPoint;
  7018. this.midPoint = midPoint;
  7019. this.endPoint = endPoint;
  7020. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7021. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7022. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7023. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7024. 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);
  7025. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7026. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7027. var a1 = this.startAngle.degrees();
  7028. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7029. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7030. // angles correction
  7031. if (a2 - a1 > +180.0)
  7032. a2 -= 360.0;
  7033. if (a2 - a1 < -180.0)
  7034. a2 += 360.0;
  7035. if (a3 - a2 > +180.0)
  7036. a3 -= 360.0;
  7037. if (a3 - a2 < -180.0)
  7038. a3 += 360.0;
  7039. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7040. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7041. }
  7042. return Arc2;
  7043. }());
  7044. BABYLON.Arc2 = Arc2;
  7045. var Path2 = /** @class */ (function () {
  7046. /**
  7047. * Creates a Path2 object from the starting 2D coordinates x and y.
  7048. */
  7049. function Path2(x, y) {
  7050. this._points = new Array();
  7051. this._length = 0.0;
  7052. this.closed = false;
  7053. this._points.push(new Vector2(x, y));
  7054. }
  7055. /**
  7056. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7057. * Returns the updated Path2.
  7058. */
  7059. Path2.prototype.addLineTo = function (x, y) {
  7060. if (this.closed) {
  7061. return this;
  7062. }
  7063. var newPoint = new Vector2(x, y);
  7064. var previousPoint = this._points[this._points.length - 1];
  7065. this._points.push(newPoint);
  7066. this._length += newPoint.subtract(previousPoint).length();
  7067. return this;
  7068. };
  7069. /**
  7070. * 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.
  7071. * Returns the updated Path2.
  7072. */
  7073. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7074. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7075. if (this.closed) {
  7076. return this;
  7077. }
  7078. var startPoint = this._points[this._points.length - 1];
  7079. var midPoint = new Vector2(midX, midY);
  7080. var endPoint = new Vector2(endX, endY);
  7081. var arc = new Arc2(startPoint, midPoint, endPoint);
  7082. var increment = arc.angle.radians() / numberOfSegments;
  7083. if (arc.orientation === Orientation.CW)
  7084. increment *= -1;
  7085. var currentAngle = arc.startAngle.radians() + increment;
  7086. for (var i = 0; i < numberOfSegments; i++) {
  7087. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7088. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7089. this.addLineTo(x, y);
  7090. currentAngle += increment;
  7091. }
  7092. return this;
  7093. };
  7094. /**
  7095. * Closes the Path2.
  7096. * Returns the Path2.
  7097. */
  7098. Path2.prototype.close = function () {
  7099. this.closed = true;
  7100. return this;
  7101. };
  7102. /**
  7103. * Returns the Path2 total length (float).
  7104. */
  7105. Path2.prototype.length = function () {
  7106. var result = this._length;
  7107. if (!this.closed) {
  7108. var lastPoint = this._points[this._points.length - 1];
  7109. var firstPoint = this._points[0];
  7110. result += (firstPoint.subtract(lastPoint).length());
  7111. }
  7112. return result;
  7113. };
  7114. /**
  7115. * Returns the Path2 internal array of points.
  7116. */
  7117. Path2.prototype.getPoints = function () {
  7118. return this._points;
  7119. };
  7120. /**
  7121. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7122. */
  7123. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7124. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7125. return Vector2.Zero();
  7126. }
  7127. var lengthPosition = normalizedLengthPosition * this.length();
  7128. var previousOffset = 0;
  7129. for (var i = 0; i < this._points.length; i++) {
  7130. var j = (i + 1) % this._points.length;
  7131. var a = this._points[i];
  7132. var b = this._points[j];
  7133. var bToA = b.subtract(a);
  7134. var nextOffset = (bToA.length() + previousOffset);
  7135. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7136. var dir = bToA.normalize();
  7137. var localOffset = lengthPosition - previousOffset;
  7138. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7139. }
  7140. previousOffset = nextOffset;
  7141. }
  7142. return Vector2.Zero();
  7143. };
  7144. /**
  7145. * Returns a new Path2 starting at the coordinates (x, y).
  7146. */
  7147. Path2.StartingAt = function (x, y) {
  7148. return new Path2(x, y);
  7149. };
  7150. return Path2;
  7151. }());
  7152. BABYLON.Path2 = Path2;
  7153. var Path3D = /** @class */ (function () {
  7154. /**
  7155. * new Path3D(path, normal, raw)
  7156. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7157. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7158. * path : an array of Vector3, the curve axis of the Path3D
  7159. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7160. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7161. */
  7162. function Path3D(path, firstNormal, raw) {
  7163. if (firstNormal === void 0) { firstNormal = null; }
  7164. this.path = path;
  7165. this._curve = new Array();
  7166. this._distances = new Array();
  7167. this._tangents = new Array();
  7168. this._normals = new Array();
  7169. this._binormals = new Array();
  7170. for (var p = 0; p < path.length; p++) {
  7171. this._curve[p] = path[p].clone(); // hard copy
  7172. }
  7173. this._raw = raw || false;
  7174. this._compute(firstNormal);
  7175. }
  7176. /**
  7177. * Returns the Path3D array of successive Vector3 designing its curve.
  7178. */
  7179. Path3D.prototype.getCurve = function () {
  7180. return this._curve;
  7181. };
  7182. /**
  7183. * Returns an array populated with tangent vectors on each Path3D curve point.
  7184. */
  7185. Path3D.prototype.getTangents = function () {
  7186. return this._tangents;
  7187. };
  7188. /**
  7189. * Returns an array populated with normal vectors on each Path3D curve point.
  7190. */
  7191. Path3D.prototype.getNormals = function () {
  7192. return this._normals;
  7193. };
  7194. /**
  7195. * Returns an array populated with binormal vectors on each Path3D curve point.
  7196. */
  7197. Path3D.prototype.getBinormals = function () {
  7198. return this._binormals;
  7199. };
  7200. /**
  7201. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7202. */
  7203. Path3D.prototype.getDistances = function () {
  7204. return this._distances;
  7205. };
  7206. /**
  7207. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7208. * Returns the same object updated.
  7209. */
  7210. Path3D.prototype.update = function (path, firstNormal) {
  7211. if (firstNormal === void 0) { firstNormal = null; }
  7212. for (var p = 0; p < path.length; p++) {
  7213. this._curve[p].x = path[p].x;
  7214. this._curve[p].y = path[p].y;
  7215. this._curve[p].z = path[p].z;
  7216. }
  7217. this._compute(firstNormal);
  7218. return this;
  7219. };
  7220. // private function compute() : computes tangents, normals and binormals
  7221. Path3D.prototype._compute = function (firstNormal) {
  7222. var l = this._curve.length;
  7223. // first and last tangents
  7224. this._tangents[0] = this._getFirstNonNullVector(0);
  7225. if (!this._raw) {
  7226. this._tangents[0].normalize();
  7227. }
  7228. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7229. if (!this._raw) {
  7230. this._tangents[l - 1].normalize();
  7231. }
  7232. // normals and binormals at first point : arbitrary vector with _normalVector()
  7233. var tg0 = this._tangents[0];
  7234. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7235. this._normals[0] = pp0;
  7236. if (!this._raw) {
  7237. this._normals[0].normalize();
  7238. }
  7239. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7240. if (!this._raw) {
  7241. this._binormals[0].normalize();
  7242. }
  7243. this._distances[0] = 0.0;
  7244. // normals and binormals : next points
  7245. var prev; // previous vector (segment)
  7246. var cur; // current vector (segment)
  7247. var curTang; // current tangent
  7248. // previous normal
  7249. var prevBinor; // previous binormal
  7250. for (var i = 1; i < l; i++) {
  7251. // tangents
  7252. prev = this._getLastNonNullVector(i);
  7253. if (i < l - 1) {
  7254. cur = this._getFirstNonNullVector(i);
  7255. this._tangents[i] = prev.add(cur);
  7256. this._tangents[i].normalize();
  7257. }
  7258. this._distances[i] = this._distances[i - 1] + prev.length();
  7259. // normals and binormals
  7260. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7261. curTang = this._tangents[i];
  7262. prevBinor = this._binormals[i - 1];
  7263. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7264. if (!this._raw) {
  7265. this._normals[i].normalize();
  7266. }
  7267. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7268. if (!this._raw) {
  7269. this._binormals[i].normalize();
  7270. }
  7271. }
  7272. };
  7273. // private function getFirstNonNullVector(index)
  7274. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7275. Path3D.prototype._getFirstNonNullVector = function (index) {
  7276. var i = 1;
  7277. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7278. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7279. i++;
  7280. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7281. }
  7282. return nNVector;
  7283. };
  7284. // private function getLastNonNullVector(index)
  7285. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7286. Path3D.prototype._getLastNonNullVector = function (index) {
  7287. var i = 1;
  7288. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7289. while (nLVector.length() === 0 && index > i + 1) {
  7290. i++;
  7291. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7292. }
  7293. return nLVector;
  7294. };
  7295. // private function normalVector(v0, vt, va) :
  7296. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7297. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7298. Path3D.prototype._normalVector = function (v0, vt, va) {
  7299. var normal0;
  7300. var tgl = vt.length();
  7301. if (tgl === 0.0) {
  7302. tgl = 1.0;
  7303. }
  7304. if (va === undefined || va === null) {
  7305. var point;
  7306. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7307. point = new Vector3(0.0, -1.0, 0.0);
  7308. }
  7309. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7310. point = new Vector3(1.0, 0.0, 0.0);
  7311. }
  7312. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7313. point = new Vector3(0.0, 0.0, 1.0);
  7314. }
  7315. else {
  7316. point = Vector3.Zero();
  7317. }
  7318. normal0 = Vector3.Cross(vt, point);
  7319. }
  7320. else {
  7321. normal0 = Vector3.Cross(vt, va);
  7322. Vector3.CrossToRef(normal0, vt, normal0);
  7323. }
  7324. normal0.normalize();
  7325. return normal0;
  7326. };
  7327. return Path3D;
  7328. }());
  7329. BABYLON.Path3D = Path3D;
  7330. var Curve3 = /** @class */ (function () {
  7331. /**
  7332. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7333. * A Curve3 is designed from a series of successive Vector3.
  7334. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7335. */
  7336. function Curve3(points) {
  7337. this._length = 0.0;
  7338. this._points = points;
  7339. this._length = this._computeLength(points);
  7340. }
  7341. /**
  7342. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7343. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7344. * @param v1 (Vector3) the control point
  7345. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7346. * @param nbPoints (integer) the wanted number of points in the curve
  7347. */
  7348. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7349. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7350. var bez = new Array();
  7351. var equation = function (t, val0, val1, val2) {
  7352. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7353. return res;
  7354. };
  7355. for (var i = 0; i <= nbPoints; i++) {
  7356. 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)));
  7357. }
  7358. return new Curve3(bez);
  7359. };
  7360. /**
  7361. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7362. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7363. * @param v1 (Vector3) the first control point
  7364. * @param v2 (Vector3) the second control point
  7365. * @param v3 (Vector3) the end point of the Cubic Bezier
  7366. * @param nbPoints (integer) the wanted number of points in the curve
  7367. */
  7368. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7369. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7370. var bez = new Array();
  7371. var equation = function (t, val0, val1, val2, val3) {
  7372. 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;
  7373. return res;
  7374. };
  7375. for (var i = 0; i <= nbPoints; i++) {
  7376. 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)));
  7377. }
  7378. return new Curve3(bez);
  7379. };
  7380. /**
  7381. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7382. * @param p1 (Vector3) the origin point of the Hermite Spline
  7383. * @param t1 (Vector3) the tangent vector at the origin point
  7384. * @param p2 (Vector3) the end point of the Hermite Spline
  7385. * @param t2 (Vector3) the tangent vector at the end point
  7386. * @param nbPoints (integer) the wanted number of points in the curve
  7387. */
  7388. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7389. var hermite = new Array();
  7390. var step = 1.0 / nbPoints;
  7391. for (var i = 0; i <= nbPoints; i++) {
  7392. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7393. }
  7394. return new Curve3(hermite);
  7395. };
  7396. /**
  7397. * Returns a Curve3 object along a CatmullRom Spline curve :
  7398. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7399. * @param nbPoints (integer) the wanted number of points between each curve control points
  7400. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7401. */
  7402. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7403. var catmullRom = new Array();
  7404. var step = 1.0 / nbPoints;
  7405. var amount = 0.0;
  7406. if (closed) {
  7407. var pointsCount = points.length;
  7408. for (var i = 0; i < pointsCount; i++) {
  7409. amount = 0;
  7410. for (var c = 0; c < nbPoints; c++) {
  7411. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7412. amount += step;
  7413. }
  7414. }
  7415. catmullRom.push(catmullRom[0]);
  7416. }
  7417. else {
  7418. var totalPoints = new Array();
  7419. totalPoints.push(points[0].clone());
  7420. Array.prototype.push.apply(totalPoints, points);
  7421. totalPoints.push(points[points.length - 1].clone());
  7422. for (var i = 0; i < totalPoints.length - 3; i++) {
  7423. amount = 0;
  7424. for (var c = 0; c < nbPoints; c++) {
  7425. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7426. amount += step;
  7427. }
  7428. }
  7429. i--;
  7430. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7431. }
  7432. return new Curve3(catmullRom);
  7433. };
  7434. /**
  7435. * Returns the Curve3 stored array of successive Vector3
  7436. */
  7437. Curve3.prototype.getPoints = function () {
  7438. return this._points;
  7439. };
  7440. /**
  7441. * Returns the computed length (float) of the curve.
  7442. */
  7443. Curve3.prototype.length = function () {
  7444. return this._length;
  7445. };
  7446. /**
  7447. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7448. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7449. * curveA and curveB keep unchanged.
  7450. */
  7451. Curve3.prototype.continue = function (curve) {
  7452. var lastPoint = this._points[this._points.length - 1];
  7453. var continuedPoints = this._points.slice();
  7454. var curvePoints = curve.getPoints();
  7455. for (var i = 1; i < curvePoints.length; i++) {
  7456. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7457. }
  7458. var continuedCurve = new Curve3(continuedPoints);
  7459. return continuedCurve;
  7460. };
  7461. Curve3.prototype._computeLength = function (path) {
  7462. var l = 0;
  7463. for (var i = 1; i < path.length; i++) {
  7464. l += (path[i].subtract(path[i - 1])).length();
  7465. }
  7466. return l;
  7467. };
  7468. return Curve3;
  7469. }());
  7470. BABYLON.Curve3 = Curve3;
  7471. // Vertex formats
  7472. var PositionNormalVertex = /** @class */ (function () {
  7473. function PositionNormalVertex(position, normal) {
  7474. if (position === void 0) { position = Vector3.Zero(); }
  7475. if (normal === void 0) { normal = Vector3.Up(); }
  7476. this.position = position;
  7477. this.normal = normal;
  7478. }
  7479. PositionNormalVertex.prototype.clone = function () {
  7480. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7481. };
  7482. return PositionNormalVertex;
  7483. }());
  7484. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7485. var PositionNormalTextureVertex = /** @class */ (function () {
  7486. function PositionNormalTextureVertex(position, normal, uv) {
  7487. if (position === void 0) { position = Vector3.Zero(); }
  7488. if (normal === void 0) { normal = Vector3.Up(); }
  7489. if (uv === void 0) { uv = Vector2.Zero(); }
  7490. this.position = position;
  7491. this.normal = normal;
  7492. this.uv = uv;
  7493. }
  7494. PositionNormalTextureVertex.prototype.clone = function () {
  7495. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7496. };
  7497. return PositionNormalTextureVertex;
  7498. }());
  7499. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7500. // Temporary pre-allocated objects for engine internal use
  7501. // usage in any internal function :
  7502. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7503. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7504. var Tmp = /** @class */ (function () {
  7505. function Tmp() {
  7506. }
  7507. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7508. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7509. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7510. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7511. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7512. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7513. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7514. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7515. Matrix.Zero(), Matrix.Zero(),
  7516. Matrix.Zero(), Matrix.Zero(),
  7517. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7518. return Tmp;
  7519. }());
  7520. BABYLON.Tmp = Tmp;
  7521. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7522. var MathTmp = /** @class */ (function () {
  7523. function MathTmp() {
  7524. }
  7525. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7526. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7527. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7528. return MathTmp;
  7529. }());
  7530. })(BABYLON || (BABYLON = {}));
  7531. //# sourceMappingURL=babylon.math.js.map
  7532. var BABYLON;
  7533. (function (BABYLON) {
  7534. var Scalar = /** @class */ (function () {
  7535. function Scalar() {
  7536. }
  7537. /**
  7538. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7539. */
  7540. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7541. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7542. var num = a - b;
  7543. return -epsilon <= num && num <= epsilon;
  7544. };
  7545. /**
  7546. * Returns a string : the upper case translation of the number i to hexadecimal.
  7547. */
  7548. Scalar.ToHex = function (i) {
  7549. var str = i.toString(16);
  7550. if (i <= 15) {
  7551. return ("0" + str).toUpperCase();
  7552. }
  7553. return str.toUpperCase();
  7554. };
  7555. /**
  7556. * Returns -1 if value is negative and +1 is value is positive.
  7557. * Returns the value itself if it's equal to zero.
  7558. */
  7559. Scalar.Sign = function (value) {
  7560. value = +value; // convert to a number
  7561. if (value === 0 || isNaN(value))
  7562. return value;
  7563. return value > 0 ? 1 : -1;
  7564. };
  7565. /**
  7566. * Returns the value itself if it's between min and max.
  7567. * Returns min if the value is lower than min.
  7568. * Returns max if the value is greater than max.
  7569. */
  7570. Scalar.Clamp = function (value, min, max) {
  7571. if (min === void 0) { min = 0; }
  7572. if (max === void 0) { max = 1; }
  7573. return Math.min(max, Math.max(min, value));
  7574. };
  7575. /**
  7576. * Returns the log2 of value.
  7577. */
  7578. Scalar.Log2 = function (value) {
  7579. return Math.log(value) * Math.LOG2E;
  7580. };
  7581. /**
  7582. * Loops the value, so that it is never larger than length and never smaller than 0.
  7583. *
  7584. * This is similar to the modulo operator but it works with floating point numbers.
  7585. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7586. * With t = 5 and length = 2.5, the result would be 0.0.
  7587. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7588. */
  7589. Scalar.Repeat = function (value, length) {
  7590. return value - Math.floor(value / length) * length;
  7591. };
  7592. /**
  7593. * Normalize the value between 0.0 and 1.0 using min and max values
  7594. */
  7595. Scalar.Normalize = function (value, min, max) {
  7596. return (value - min) / (max - min);
  7597. };
  7598. /**
  7599. * Denormalize the value from 0.0 and 1.0 using min and max values
  7600. */
  7601. Scalar.Denormalize = function (normalized, min, max) {
  7602. return (normalized * (max - min) + min);
  7603. };
  7604. /**
  7605. * Calculates the shortest difference between two given angles given in degrees.
  7606. */
  7607. Scalar.DeltaAngle = function (current, target) {
  7608. var num = Scalar.Repeat(target - current, 360.0);
  7609. if (num > 180.0) {
  7610. num -= 360.0;
  7611. }
  7612. return num;
  7613. };
  7614. /**
  7615. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7616. *
  7617. * The returned value will move back and forth between 0 and length
  7618. */
  7619. Scalar.PingPong = function (tx, length) {
  7620. var t = Scalar.Repeat(tx, length * 2.0);
  7621. return length - Math.abs(t - length);
  7622. };
  7623. /**
  7624. * Interpolates between min and max with smoothing at the limits.
  7625. *
  7626. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7627. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7628. */
  7629. Scalar.SmoothStep = function (from, to, tx) {
  7630. var t = Scalar.Clamp(tx);
  7631. t = -2.0 * t * t * t + 3.0 * t * t;
  7632. return to * t + from * (1.0 - t);
  7633. };
  7634. /**
  7635. * Moves a value current towards target.
  7636. *
  7637. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7638. * Negative values of maxDelta pushes the value away from target.
  7639. */
  7640. Scalar.MoveTowards = function (current, target, maxDelta) {
  7641. var result = 0;
  7642. if (Math.abs(target - current) <= maxDelta) {
  7643. result = target;
  7644. }
  7645. else {
  7646. result = current + Scalar.Sign(target - current) * maxDelta;
  7647. }
  7648. return result;
  7649. };
  7650. /**
  7651. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7652. *
  7653. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7654. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7655. */
  7656. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7657. var num = Scalar.DeltaAngle(current, target);
  7658. var result = 0;
  7659. if (-maxDelta < num && num < maxDelta) {
  7660. result = target;
  7661. }
  7662. else {
  7663. target = current + num;
  7664. result = Scalar.MoveTowards(current, target, maxDelta);
  7665. }
  7666. return result;
  7667. };
  7668. /**
  7669. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7670. */
  7671. Scalar.Lerp = function (start, end, amount) {
  7672. return start + ((end - start) * amount);
  7673. };
  7674. /**
  7675. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7676. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7677. */
  7678. Scalar.LerpAngle = function (start, end, amount) {
  7679. var num = Scalar.Repeat(end - start, 360.0);
  7680. if (num > 180.0) {
  7681. num -= 360.0;
  7682. }
  7683. return start + num * Scalar.Clamp(amount);
  7684. };
  7685. /**
  7686. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7687. */
  7688. Scalar.InverseLerp = function (a, b, value) {
  7689. var result = 0;
  7690. if (a != b) {
  7691. result = Scalar.Clamp((value - a) / (b - a));
  7692. }
  7693. else {
  7694. result = 0.0;
  7695. }
  7696. return result;
  7697. };
  7698. /**
  7699. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7700. */
  7701. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7702. var squared = amount * amount;
  7703. var cubed = amount * squared;
  7704. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7705. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7706. var part3 = (cubed - (2.0 * squared)) + amount;
  7707. var part4 = cubed - squared;
  7708. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7709. };
  7710. /**
  7711. * Returns a random float number between and min and max values
  7712. */
  7713. Scalar.RandomRange = function (min, max) {
  7714. if (min === max)
  7715. return min;
  7716. return ((Math.random() * (max - min)) + min);
  7717. };
  7718. /**
  7719. * This function returns percentage of a number in a given range.
  7720. *
  7721. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7722. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7723. */
  7724. Scalar.RangeToPercent = function (number, min, max) {
  7725. return ((number - min) / (max - min));
  7726. };
  7727. /**
  7728. * This function returns number that corresponds to the percentage in a given range.
  7729. *
  7730. * PercentToRange(0.34,0,100) will return 34.
  7731. */
  7732. Scalar.PercentToRange = function (percent, min, max) {
  7733. return ((max - min) * percent + min);
  7734. };
  7735. /**
  7736. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7737. * @param angle The angle to normalize in radian.
  7738. * @return The converted angle.
  7739. */
  7740. Scalar.NormalizeRadians = function (angle) {
  7741. // More precise but slower version kept for reference.
  7742. // angle = angle % Tools.TwoPi;
  7743. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7744. //if (angle > Math.PI) {
  7745. // angle -= Tools.TwoPi;
  7746. //}
  7747. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7748. return angle;
  7749. };
  7750. /**
  7751. * Two pi constants convenient for computation.
  7752. */
  7753. Scalar.TwoPi = Math.PI * 2;
  7754. return Scalar;
  7755. }());
  7756. BABYLON.Scalar = Scalar;
  7757. })(BABYLON || (BABYLON = {}));
  7758. //# sourceMappingURL=babylon.math.scalar.js.map
  7759. //# sourceMappingURL=babylon.mixins.js.map
  7760. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7761. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7762. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7763. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7764. //# sourceMappingURL=babylon.webgl2.js.map
  7765. var BABYLON;
  7766. (function (BABYLON) {
  7767. var __decoratorInitialStore = {};
  7768. var __mergedStore = {};
  7769. var _copySource = function (creationFunction, source, instanciate) {
  7770. var destination = creationFunction();
  7771. // Tags
  7772. if (BABYLON.Tags) {
  7773. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7774. }
  7775. var classStore = getMergedStore(destination);
  7776. // Properties
  7777. for (var property in classStore) {
  7778. var propertyDescriptor = classStore[property];
  7779. var sourceProperty = source[property];
  7780. var propertyType = propertyDescriptor.type;
  7781. if (sourceProperty !== undefined && sourceProperty !== null) {
  7782. switch (propertyType) {
  7783. case 0: // Value
  7784. case 6: // Mesh reference
  7785. case 11: // Camera reference
  7786. destination[property] = sourceProperty;
  7787. break;
  7788. case 1: // Texture
  7789. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7790. break;
  7791. case 2: // Color3
  7792. case 3: // FresnelParameters
  7793. case 4: // Vector2
  7794. case 5: // Vector3
  7795. case 7: // Color Curves
  7796. case 10: // Quaternion
  7797. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7798. break;
  7799. }
  7800. }
  7801. }
  7802. return destination;
  7803. };
  7804. function getDirectStore(target) {
  7805. var classKey = target.getClassName();
  7806. if (!__decoratorInitialStore[classKey]) {
  7807. __decoratorInitialStore[classKey] = {};
  7808. }
  7809. return __decoratorInitialStore[classKey];
  7810. }
  7811. /**
  7812. * Return the list of properties flagged as serializable
  7813. * @param target: host object
  7814. */
  7815. function getMergedStore(target) {
  7816. var classKey = target.getClassName();
  7817. if (__mergedStore[classKey]) {
  7818. return __mergedStore[classKey];
  7819. }
  7820. __mergedStore[classKey] = {};
  7821. var store = __mergedStore[classKey];
  7822. var currentTarget = target;
  7823. var currentKey = classKey;
  7824. while (currentKey) {
  7825. var initialStore = __decoratorInitialStore[currentKey];
  7826. for (var property in initialStore) {
  7827. store[property] = initialStore[property];
  7828. }
  7829. var parent_1 = void 0;
  7830. var done = false;
  7831. do {
  7832. parent_1 = Object.getPrototypeOf(currentTarget);
  7833. if (!parent_1.getClassName) {
  7834. done = true;
  7835. break;
  7836. }
  7837. if (parent_1.getClassName() !== currentKey) {
  7838. break;
  7839. }
  7840. currentTarget = parent_1;
  7841. } while (parent_1);
  7842. if (done) {
  7843. break;
  7844. }
  7845. currentKey = parent_1.getClassName();
  7846. currentTarget = parent_1;
  7847. }
  7848. return store;
  7849. }
  7850. function generateSerializableMember(type, sourceName) {
  7851. return function (target, propertyKey) {
  7852. var classStore = getDirectStore(target);
  7853. if (!classStore[propertyKey]) {
  7854. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7855. }
  7856. };
  7857. }
  7858. function generateExpandMember(setCallback, targetKey) {
  7859. if (targetKey === void 0) { targetKey = null; }
  7860. return function (target, propertyKey) {
  7861. var key = targetKey || ("_" + propertyKey);
  7862. Object.defineProperty(target, propertyKey, {
  7863. get: function () {
  7864. return this[key];
  7865. },
  7866. set: function (value) {
  7867. if (this[key] === value) {
  7868. return;
  7869. }
  7870. this[key] = value;
  7871. target[setCallback].apply(this);
  7872. },
  7873. enumerable: true,
  7874. configurable: true
  7875. });
  7876. };
  7877. }
  7878. function expandToProperty(callback, targetKey) {
  7879. if (targetKey === void 0) { targetKey = null; }
  7880. return generateExpandMember(callback, targetKey);
  7881. }
  7882. BABYLON.expandToProperty = expandToProperty;
  7883. function serialize(sourceName) {
  7884. return generateSerializableMember(0, sourceName); // value member
  7885. }
  7886. BABYLON.serialize = serialize;
  7887. function serializeAsTexture(sourceName) {
  7888. return generateSerializableMember(1, sourceName); // texture member
  7889. }
  7890. BABYLON.serializeAsTexture = serializeAsTexture;
  7891. function serializeAsColor3(sourceName) {
  7892. return generateSerializableMember(2, sourceName); // color3 member
  7893. }
  7894. BABYLON.serializeAsColor3 = serializeAsColor3;
  7895. function serializeAsFresnelParameters(sourceName) {
  7896. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7897. }
  7898. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7899. function serializeAsVector2(sourceName) {
  7900. return generateSerializableMember(4, sourceName); // vector2 member
  7901. }
  7902. BABYLON.serializeAsVector2 = serializeAsVector2;
  7903. function serializeAsVector3(sourceName) {
  7904. return generateSerializableMember(5, sourceName); // vector3 member
  7905. }
  7906. BABYLON.serializeAsVector3 = serializeAsVector3;
  7907. function serializeAsMeshReference(sourceName) {
  7908. return generateSerializableMember(6, sourceName); // mesh reference member
  7909. }
  7910. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7911. function serializeAsColorCurves(sourceName) {
  7912. return generateSerializableMember(7, sourceName); // color curves
  7913. }
  7914. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7915. function serializeAsColor4(sourceName) {
  7916. return generateSerializableMember(8, sourceName); // color 4
  7917. }
  7918. BABYLON.serializeAsColor4 = serializeAsColor4;
  7919. function serializeAsImageProcessingConfiguration(sourceName) {
  7920. return generateSerializableMember(9, sourceName); // image processing
  7921. }
  7922. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7923. function serializeAsQuaternion(sourceName) {
  7924. return generateSerializableMember(10, sourceName); // quaternion member
  7925. }
  7926. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7927. /**
  7928. * Decorator used to define property that can be serialized as reference to a camera
  7929. * @param sourceName defines the name of the property to decorate
  7930. */
  7931. function serializeAsCameraReference(sourceName) {
  7932. return generateSerializableMember(11, sourceName); // camera reference member
  7933. }
  7934. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7935. var SerializationHelper = /** @class */ (function () {
  7936. function SerializationHelper() {
  7937. }
  7938. SerializationHelper.Serialize = function (entity, serializationObject) {
  7939. if (!serializationObject) {
  7940. serializationObject = {};
  7941. }
  7942. // Tags
  7943. if (BABYLON.Tags) {
  7944. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7945. }
  7946. var serializedProperties = getMergedStore(entity);
  7947. // Properties
  7948. for (var property in serializedProperties) {
  7949. var propertyDescriptor = serializedProperties[property];
  7950. var targetPropertyName = propertyDescriptor.sourceName || property;
  7951. var propertyType = propertyDescriptor.type;
  7952. var sourceProperty = entity[property];
  7953. if (sourceProperty !== undefined && sourceProperty !== null) {
  7954. switch (propertyType) {
  7955. case 0: // Value
  7956. serializationObject[targetPropertyName] = sourceProperty;
  7957. break;
  7958. case 1: // Texture
  7959. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7960. break;
  7961. case 2: // Color3
  7962. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7963. break;
  7964. case 3: // FresnelParameters
  7965. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7966. break;
  7967. case 4: // Vector2
  7968. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7969. break;
  7970. case 5: // Vector3
  7971. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7972. break;
  7973. case 6: // Mesh reference
  7974. serializationObject[targetPropertyName] = sourceProperty.id;
  7975. break;
  7976. case 7: // Color Curves
  7977. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7978. break;
  7979. case 8: // Color 4
  7980. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7981. break;
  7982. case 9: // Image Processing
  7983. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7984. break;
  7985. case 10: // Quaternion
  7986. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7987. break;
  7988. case 11: // Camera reference
  7989. serializationObject[targetPropertyName] = sourceProperty.id;
  7990. break;
  7991. }
  7992. }
  7993. }
  7994. return serializationObject;
  7995. };
  7996. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7997. if (rootUrl === void 0) { rootUrl = null; }
  7998. var destination = creationFunction();
  7999. if (!rootUrl) {
  8000. rootUrl = "";
  8001. }
  8002. // Tags
  8003. if (BABYLON.Tags) {
  8004. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8005. }
  8006. var classStore = getMergedStore(destination);
  8007. // Properties
  8008. for (var property in classStore) {
  8009. var propertyDescriptor = classStore[property];
  8010. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8011. var propertyType = propertyDescriptor.type;
  8012. if (sourceProperty !== undefined && sourceProperty !== null) {
  8013. var dest = destination;
  8014. switch (propertyType) {
  8015. case 0: // Value
  8016. dest[property] = sourceProperty;
  8017. break;
  8018. case 1: // Texture
  8019. if (scene) {
  8020. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8021. }
  8022. break;
  8023. case 2: // Color3
  8024. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8025. break;
  8026. case 3: // FresnelParameters
  8027. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8028. break;
  8029. case 4: // Vector2
  8030. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8031. break;
  8032. case 5: // Vector3
  8033. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8034. break;
  8035. case 6: // Mesh reference
  8036. if (scene) {
  8037. dest[property] = scene.getLastMeshByID(sourceProperty);
  8038. }
  8039. break;
  8040. case 7: // Color Curves
  8041. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8042. break;
  8043. case 8: // Color 4
  8044. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8045. break;
  8046. case 9: // Image Processing
  8047. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8048. break;
  8049. case 10: // Quaternion
  8050. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8051. break;
  8052. case 11: // Camera reference
  8053. if (scene) {
  8054. dest[property] = scene.getCameraByID(sourceProperty);
  8055. }
  8056. break;
  8057. }
  8058. }
  8059. }
  8060. return destination;
  8061. };
  8062. SerializationHelper.Clone = function (creationFunction, source) {
  8063. return _copySource(creationFunction, source, false);
  8064. };
  8065. SerializationHelper.Instanciate = function (creationFunction, source) {
  8066. return _copySource(creationFunction, source, true);
  8067. };
  8068. return SerializationHelper;
  8069. }());
  8070. BABYLON.SerializationHelper = SerializationHelper;
  8071. })(BABYLON || (BABYLON = {}));
  8072. //# sourceMappingURL=babylon.decorators.js.map
  8073. var BABYLON;
  8074. (function (BABYLON) {
  8075. /**
  8076. * Wrapper class for promise with external resolve and reject.
  8077. */
  8078. var Deferred = /** @class */ (function () {
  8079. /**
  8080. * Constructor for this deferred object.
  8081. */
  8082. function Deferred() {
  8083. var _this = this;
  8084. this.promise = new Promise(function (resolve, reject) {
  8085. _this._resolve = resolve;
  8086. _this._reject = reject;
  8087. });
  8088. }
  8089. Object.defineProperty(Deferred.prototype, "resolve", {
  8090. /**
  8091. * The resolve method of the promise associated with this deferred object.
  8092. */
  8093. get: function () {
  8094. return this._resolve;
  8095. },
  8096. enumerable: true,
  8097. configurable: true
  8098. });
  8099. Object.defineProperty(Deferred.prototype, "reject", {
  8100. /**
  8101. * The reject method of the promise associated with this deferred object.
  8102. */
  8103. get: function () {
  8104. return this._reject;
  8105. },
  8106. enumerable: true,
  8107. configurable: true
  8108. });
  8109. return Deferred;
  8110. }());
  8111. BABYLON.Deferred = Deferred;
  8112. })(BABYLON || (BABYLON = {}));
  8113. //# sourceMappingURL=babylon.deferred.js.map
  8114. var BABYLON;
  8115. (function (BABYLON) {
  8116. /**
  8117. * A class serves as a medium between the observable and its observers
  8118. */
  8119. var EventState = /** @class */ (function () {
  8120. /**
  8121. * Create a new EventState
  8122. * @param mask defines the mask associated with this state
  8123. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8124. * @param target defines the original target of the state
  8125. * @param currentTarget defines the current target of the state
  8126. */
  8127. function EventState(mask, skipNextObservers, target, currentTarget) {
  8128. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8129. this.initalize(mask, skipNextObservers, target, currentTarget);
  8130. }
  8131. /**
  8132. * Initialize the current event state
  8133. * @param mask defines the mask associated with this state
  8134. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8135. * @param target defines the original target of the state
  8136. * @param currentTarget defines the current target of the state
  8137. * @returns the current event state
  8138. */
  8139. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8140. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8141. this.mask = mask;
  8142. this.skipNextObservers = skipNextObservers;
  8143. this.target = target;
  8144. this.currentTarget = currentTarget;
  8145. return this;
  8146. };
  8147. return EventState;
  8148. }());
  8149. BABYLON.EventState = EventState;
  8150. /**
  8151. * Represent an Observer registered to a given Observable object.
  8152. */
  8153. var Observer = /** @class */ (function () {
  8154. /**
  8155. * Creates a new observer
  8156. * @param callback defines the callback to call when the observer is notified
  8157. * @param mask defines the mask of the observer (used to filter notifications)
  8158. * @param scope defines the current scope used to restore the JS context
  8159. */
  8160. function Observer(
  8161. /**
  8162. * Defines the callback to call when the observer is notified
  8163. */
  8164. callback,
  8165. /**
  8166. * Defines the mask of the observer (used to filter notifications)
  8167. */
  8168. mask,
  8169. /**
  8170. * Defines the current scope used to restore the JS context
  8171. */
  8172. scope) {
  8173. if (scope === void 0) { scope = null; }
  8174. this.callback = callback;
  8175. this.mask = mask;
  8176. this.scope = scope;
  8177. /** @hidden */
  8178. this._willBeUnregistered = false;
  8179. /**
  8180. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8181. */
  8182. this.unregisterOnNextCall = false;
  8183. }
  8184. return Observer;
  8185. }());
  8186. BABYLON.Observer = Observer;
  8187. /**
  8188. * Represent a list of observers registered to multiple Observables object.
  8189. */
  8190. var MultiObserver = /** @class */ (function () {
  8191. function MultiObserver() {
  8192. }
  8193. /**
  8194. * Release associated resources
  8195. */
  8196. MultiObserver.prototype.dispose = function () {
  8197. if (this._observers && this._observables) {
  8198. for (var index = 0; index < this._observers.length; index++) {
  8199. this._observables[index].remove(this._observers[index]);
  8200. }
  8201. }
  8202. this._observers = null;
  8203. this._observables = null;
  8204. };
  8205. /**
  8206. * Raise a callback when one of the observable will notify
  8207. * @param observables defines a list of observables to watch
  8208. * @param callback defines the callback to call on notification
  8209. * @param mask defines the mask used to filter notifications
  8210. * @param scope defines the current scope used to restore the JS context
  8211. * @returns the new MultiObserver
  8212. */
  8213. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8214. if (mask === void 0) { mask = -1; }
  8215. if (scope === void 0) { scope = null; }
  8216. var result = new MultiObserver();
  8217. result._observers = new Array();
  8218. result._observables = observables;
  8219. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8220. var observable = observables_1[_i];
  8221. var observer = observable.add(callback, mask, false, scope);
  8222. if (observer) {
  8223. result._observers.push(observer);
  8224. }
  8225. }
  8226. return result;
  8227. };
  8228. return MultiObserver;
  8229. }());
  8230. BABYLON.MultiObserver = MultiObserver;
  8231. /**
  8232. * The Observable class is a simple implementation of the Observable pattern.
  8233. *
  8234. * 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.
  8235. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8236. * 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).
  8237. * 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.
  8238. */
  8239. var Observable = /** @class */ (function () {
  8240. /**
  8241. * Creates a new observable
  8242. * @param onObserverAdded defines a callback to call when a new observer is added
  8243. */
  8244. function Observable(onObserverAdded) {
  8245. this._observers = new Array();
  8246. this._eventState = new EventState(0);
  8247. if (onObserverAdded) {
  8248. this._onObserverAdded = onObserverAdded;
  8249. }
  8250. }
  8251. /**
  8252. * Create a new Observer with the specified callback
  8253. * @param callback the callback that will be executed for that Observer
  8254. * @param mask the mask used to filter observers
  8255. * @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.
  8256. * @param scope optional scope for the callback to be called from
  8257. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8258. * @returns the new observer created for the callback
  8259. */
  8260. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8261. if (mask === void 0) { mask = -1; }
  8262. if (insertFirst === void 0) { insertFirst = false; }
  8263. if (scope === void 0) { scope = null; }
  8264. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8265. if (!callback) {
  8266. return null;
  8267. }
  8268. var observer = new Observer(callback, mask, scope);
  8269. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8270. if (insertFirst) {
  8271. this._observers.unshift(observer);
  8272. }
  8273. else {
  8274. this._observers.push(observer);
  8275. }
  8276. if (this._onObserverAdded) {
  8277. this._onObserverAdded(observer);
  8278. }
  8279. return observer;
  8280. };
  8281. /**
  8282. * Create a new Observer with the specified callback and unregisters after the next notification
  8283. * @param callback the callback that will be executed for that Observer
  8284. * @returns the new observer created for the callback
  8285. */
  8286. Observable.prototype.addOnce = function (callback) {
  8287. return this.add(callback, undefined, undefined, undefined, true);
  8288. };
  8289. /**
  8290. * Remove an Observer from the Observable object
  8291. * @param observer the instance of the Observer to remove
  8292. * @returns false if it doesn't belong to this Observable
  8293. */
  8294. Observable.prototype.remove = function (observer) {
  8295. if (!observer) {
  8296. return false;
  8297. }
  8298. var index = this._observers.indexOf(observer);
  8299. if (index !== -1) {
  8300. this._deferUnregister(observer);
  8301. return true;
  8302. }
  8303. return false;
  8304. };
  8305. /**
  8306. * Remove a callback from the Observable object
  8307. * @param callback the callback to remove
  8308. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8309. * @returns false if it doesn't belong to this Observable
  8310. */
  8311. Observable.prototype.removeCallback = function (callback, scope) {
  8312. for (var index = 0; index < this._observers.length; index++) {
  8313. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8314. this._deferUnregister(this._observers[index]);
  8315. return true;
  8316. }
  8317. }
  8318. return false;
  8319. };
  8320. Observable.prototype._deferUnregister = function (observer) {
  8321. var _this = this;
  8322. observer.unregisterOnNextCall = false;
  8323. observer._willBeUnregistered = true;
  8324. BABYLON.Tools.SetImmediate(function () {
  8325. _this._remove(observer);
  8326. });
  8327. };
  8328. // This should only be called when not iterating over _observers to avoid callback skipping.
  8329. // Removes an observer from the _observer Array.
  8330. Observable.prototype._remove = function (observer) {
  8331. if (!observer) {
  8332. return false;
  8333. }
  8334. var index = this._observers.indexOf(observer);
  8335. if (index !== -1) {
  8336. this._observers.splice(index, 1);
  8337. return true;
  8338. }
  8339. return false;
  8340. };
  8341. /**
  8342. * Notify all Observers by calling their respective callback with the given data
  8343. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8344. * @param eventData defines the data to send to all observers
  8345. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8346. * @param target defines the original target of the state
  8347. * @param currentTarget defines the current target of the state
  8348. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8349. */
  8350. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8351. if (mask === void 0) { mask = -1; }
  8352. if (!this._observers.length) {
  8353. return true;
  8354. }
  8355. var state = this._eventState;
  8356. state.mask = mask;
  8357. state.target = target;
  8358. state.currentTarget = currentTarget;
  8359. state.skipNextObservers = false;
  8360. state.lastReturnValue = eventData;
  8361. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8362. var obs = _a[_i];
  8363. if (obs._willBeUnregistered) {
  8364. continue;
  8365. }
  8366. if (obs.mask & mask) {
  8367. if (obs.scope) {
  8368. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8369. }
  8370. else {
  8371. state.lastReturnValue = obs.callback(eventData, state);
  8372. }
  8373. if (obs.unregisterOnNextCall) {
  8374. this._deferUnregister(obs);
  8375. }
  8376. }
  8377. if (state.skipNextObservers) {
  8378. return false;
  8379. }
  8380. }
  8381. return true;
  8382. };
  8383. /**
  8384. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8385. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8386. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8387. * and it is crucial that all callbacks will be executed.
  8388. * The order of the callbacks is kept, callbacks are not executed parallel.
  8389. *
  8390. * @param eventData The data to be sent to each callback
  8391. * @param mask is used to filter observers defaults to -1
  8392. * @param target defines the callback target (see EventState)
  8393. * @param currentTarget defines he current object in the bubbling phase
  8394. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8395. */
  8396. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8397. var _this = this;
  8398. if (mask === void 0) { mask = -1; }
  8399. // create an empty promise
  8400. var p = Promise.resolve(eventData);
  8401. // no observers? return this promise.
  8402. if (!this._observers.length) {
  8403. return p;
  8404. }
  8405. var state = this._eventState;
  8406. state.mask = mask;
  8407. state.target = target;
  8408. state.currentTarget = currentTarget;
  8409. state.skipNextObservers = false;
  8410. // execute one callback after another (not using Promise.all, the order is important)
  8411. this._observers.forEach(function (obs) {
  8412. if (state.skipNextObservers) {
  8413. return;
  8414. }
  8415. if (obs._willBeUnregistered) {
  8416. return;
  8417. }
  8418. if (obs.mask & mask) {
  8419. if (obs.scope) {
  8420. p = p.then(function (lastReturnedValue) {
  8421. state.lastReturnValue = lastReturnedValue;
  8422. return obs.callback.apply(obs.scope, [eventData, state]);
  8423. });
  8424. }
  8425. else {
  8426. p = p.then(function (lastReturnedValue) {
  8427. state.lastReturnValue = lastReturnedValue;
  8428. return obs.callback(eventData, state);
  8429. });
  8430. }
  8431. if (obs.unregisterOnNextCall) {
  8432. _this._deferUnregister(obs);
  8433. }
  8434. }
  8435. });
  8436. // return the eventData
  8437. return p.then(function () { return eventData; });
  8438. };
  8439. /**
  8440. * Notify a specific observer
  8441. * @param observer defines the observer to notify
  8442. * @param eventData defines the data to be sent to each callback
  8443. * @param mask is used to filter observers defaults to -1
  8444. */
  8445. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8446. if (mask === void 0) { mask = -1; }
  8447. var state = this._eventState;
  8448. state.mask = mask;
  8449. state.skipNextObservers = false;
  8450. observer.callback(eventData, state);
  8451. };
  8452. /**
  8453. * Gets a boolean indicating if the observable has at least one observer
  8454. * @returns true is the Observable has at least one Observer registered
  8455. */
  8456. Observable.prototype.hasObservers = function () {
  8457. return this._observers.length > 0;
  8458. };
  8459. /**
  8460. * Clear the list of observers
  8461. */
  8462. Observable.prototype.clear = function () {
  8463. this._observers = new Array();
  8464. this._onObserverAdded = null;
  8465. };
  8466. /**
  8467. * Clone the current observable
  8468. * @returns a new observable
  8469. */
  8470. Observable.prototype.clone = function () {
  8471. var result = new Observable();
  8472. result._observers = this._observers.slice(0);
  8473. return result;
  8474. };
  8475. /**
  8476. * Does this observable handles observer registered with a given mask
  8477. * @param mask defines the mask to be tested
  8478. * @return whether or not one observer registered with the given mask is handeled
  8479. **/
  8480. Observable.prototype.hasSpecificMask = function (mask) {
  8481. if (mask === void 0) { mask = -1; }
  8482. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8483. var obs = _a[_i];
  8484. if (obs.mask & mask || obs.mask === mask) {
  8485. return true;
  8486. }
  8487. }
  8488. return false;
  8489. };
  8490. return Observable;
  8491. }());
  8492. BABYLON.Observable = Observable;
  8493. })(BABYLON || (BABYLON = {}));
  8494. //# sourceMappingURL=babylon.observable.js.map
  8495. var BABYLON;
  8496. (function (BABYLON) {
  8497. /**
  8498. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8499. */
  8500. var SmartArray = /** @class */ (function () {
  8501. /**
  8502. * Instantiates a Smart Array.
  8503. * @param capacity defines the default capacity of the array.
  8504. */
  8505. function SmartArray(capacity) {
  8506. /**
  8507. * The active length of the array.
  8508. */
  8509. this.length = 0;
  8510. this.data = new Array(capacity);
  8511. this._id = SmartArray._GlobalId++;
  8512. }
  8513. /**
  8514. * Pushes a value at the end of the active data.
  8515. * @param value defines the object to push in the array.
  8516. */
  8517. SmartArray.prototype.push = function (value) {
  8518. this.data[this.length++] = value;
  8519. if (this.length > this.data.length) {
  8520. this.data.length *= 2;
  8521. }
  8522. };
  8523. /**
  8524. * Iterates over the active data and apply the lambda to them.
  8525. * @param func defines the action to apply on each value.
  8526. */
  8527. SmartArray.prototype.forEach = function (func) {
  8528. for (var index = 0; index < this.length; index++) {
  8529. func(this.data[index]);
  8530. }
  8531. };
  8532. /**
  8533. * Sorts the full sets of data.
  8534. * @param compareFn defines the comparison function to apply.
  8535. */
  8536. SmartArray.prototype.sort = function (compareFn) {
  8537. this.data.sort(compareFn);
  8538. };
  8539. /**
  8540. * Resets the active data to an empty array.
  8541. */
  8542. SmartArray.prototype.reset = function () {
  8543. this.length = 0;
  8544. };
  8545. /**
  8546. * Releases all the data from the array as well as the array.
  8547. */
  8548. SmartArray.prototype.dispose = function () {
  8549. this.reset();
  8550. if (this.data) {
  8551. this.data.length = 0;
  8552. this.data = [];
  8553. }
  8554. };
  8555. /**
  8556. * Concats the active data with a given array.
  8557. * @param array defines the data to concatenate with.
  8558. */
  8559. SmartArray.prototype.concat = function (array) {
  8560. if (array.length === 0) {
  8561. return;
  8562. }
  8563. if (this.length + array.length > this.data.length) {
  8564. this.data.length = (this.length + array.length) * 2;
  8565. }
  8566. for (var index = 0; index < array.length; index++) {
  8567. this.data[this.length++] = (array.data || array)[index];
  8568. }
  8569. };
  8570. /**
  8571. * Returns the position of a value in the active data.
  8572. * @param value defines the value to find the index for
  8573. * @returns the index if found in the active data otherwise -1
  8574. */
  8575. SmartArray.prototype.indexOf = function (value) {
  8576. var position = this.data.indexOf(value);
  8577. if (position >= this.length) {
  8578. return -1;
  8579. }
  8580. return position;
  8581. };
  8582. /**
  8583. * Returns whether an element is part of the active data.
  8584. * @param value defines the value to look for
  8585. * @returns true if found in the active data otherwise false
  8586. */
  8587. SmartArray.prototype.contains = function (value) {
  8588. return this.indexOf(value) !== -1;
  8589. };
  8590. // Statics
  8591. SmartArray._GlobalId = 0;
  8592. return SmartArray;
  8593. }());
  8594. BABYLON.SmartArray = SmartArray;
  8595. /**
  8596. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8597. * The data in this array can only be present once
  8598. */
  8599. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8600. __extends(SmartArrayNoDuplicate, _super);
  8601. function SmartArrayNoDuplicate() {
  8602. var _this = _super !== null && _super.apply(this, arguments) || this;
  8603. _this._duplicateId = 0;
  8604. return _this;
  8605. }
  8606. /**
  8607. * Pushes a value at the end of the active data.
  8608. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8609. * @param value defines the object to push in the array.
  8610. */
  8611. SmartArrayNoDuplicate.prototype.push = function (value) {
  8612. _super.prototype.push.call(this, value);
  8613. if (!value.__smartArrayFlags) {
  8614. value.__smartArrayFlags = {};
  8615. }
  8616. value.__smartArrayFlags[this._id] = this._duplicateId;
  8617. };
  8618. /**
  8619. * Pushes a value at the end of the active data.
  8620. * If the data is already present, it won t be added again
  8621. * @param value defines the object to push in the array.
  8622. * @returns true if added false if it was already present
  8623. */
  8624. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8625. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8626. return false;
  8627. }
  8628. this.push(value);
  8629. return true;
  8630. };
  8631. /**
  8632. * Resets the active data to an empty array.
  8633. */
  8634. SmartArrayNoDuplicate.prototype.reset = function () {
  8635. _super.prototype.reset.call(this);
  8636. this._duplicateId++;
  8637. };
  8638. /**
  8639. * Concats the active data with a given array.
  8640. * This ensures no dupplicate will be present in the result.
  8641. * @param array defines the data to concatenate with.
  8642. */
  8643. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8644. if (array.length === 0) {
  8645. return;
  8646. }
  8647. if (this.length + array.length > this.data.length) {
  8648. this.data.length = (this.length + array.length) * 2;
  8649. }
  8650. for (var index = 0; index < array.length; index++) {
  8651. var item = (array.data || array)[index];
  8652. this.pushNoDuplicate(item);
  8653. }
  8654. };
  8655. return SmartArrayNoDuplicate;
  8656. }(SmartArray));
  8657. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8658. })(BABYLON || (BABYLON = {}));
  8659. //# sourceMappingURL=babylon.smartArray.js.map
  8660. var BABYLON;
  8661. (function (BABYLON) {
  8662. /** Class used to store color4 gradient */
  8663. var ColorGradient = /** @class */ (function () {
  8664. function ColorGradient() {
  8665. }
  8666. /**
  8667. * Will get a color picked randomly between color1 and color2.
  8668. * If color2 is undefined then color1 will be used
  8669. * @param result defines the target Color4 to store the result in
  8670. */
  8671. ColorGradient.prototype.getColorToRef = function (result) {
  8672. if (!this.color2) {
  8673. result.copyFrom(this.color1);
  8674. return;
  8675. }
  8676. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8677. };
  8678. return ColorGradient;
  8679. }());
  8680. BABYLON.ColorGradient = ColorGradient;
  8681. /** Class used to store color 3 gradient */
  8682. var Color3Gradient = /** @class */ (function () {
  8683. function Color3Gradient() {
  8684. }
  8685. return Color3Gradient;
  8686. }());
  8687. BABYLON.Color3Gradient = Color3Gradient;
  8688. /** Class used to store factor gradient */
  8689. var FactorGradient = /** @class */ (function () {
  8690. function FactorGradient() {
  8691. }
  8692. /**
  8693. * Will get a number picked randomly between factor1 and factor2.
  8694. * If factor2 is undefined then factor1 will be used
  8695. * @returns the picked number
  8696. */
  8697. FactorGradient.prototype.getFactor = function () {
  8698. if (this.factor2 === undefined) {
  8699. return this.factor1;
  8700. }
  8701. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8702. };
  8703. return FactorGradient;
  8704. }());
  8705. BABYLON.FactorGradient = FactorGradient;
  8706. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8707. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8708. var LoadFileError = /** @class */ (function (_super) {
  8709. __extends(LoadFileError, _super);
  8710. function LoadFileError(message, request) {
  8711. var _this = _super.call(this, message) || this;
  8712. _this.request = request;
  8713. _this.name = "LoadFileError";
  8714. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8715. return _this;
  8716. }
  8717. // Polyfill for Object.setPrototypeOf if necessary.
  8718. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8719. return LoadFileError;
  8720. }(Error));
  8721. BABYLON.LoadFileError = LoadFileError;
  8722. var RetryStrategy = /** @class */ (function () {
  8723. function RetryStrategy() {
  8724. }
  8725. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8726. if (maxRetries === void 0) { maxRetries = 3; }
  8727. if (baseInterval === void 0) { baseInterval = 500; }
  8728. return function (url, request, retryIndex) {
  8729. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8730. return -1;
  8731. }
  8732. return Math.pow(2, retryIndex) * baseInterval;
  8733. };
  8734. };
  8735. return RetryStrategy;
  8736. }());
  8737. BABYLON.RetryStrategy = RetryStrategy;
  8738. // Screenshots
  8739. var screenshotCanvas;
  8740. var cloneValue = function (source, destinationObject) {
  8741. if (!source)
  8742. return null;
  8743. if (source instanceof BABYLON.Mesh) {
  8744. return null;
  8745. }
  8746. if (source instanceof BABYLON.SubMesh) {
  8747. return source.clone(destinationObject);
  8748. }
  8749. else if (source.clone) {
  8750. return source.clone();
  8751. }
  8752. return null;
  8753. };
  8754. var Tools = /** @class */ (function () {
  8755. function Tools() {
  8756. }
  8757. /**
  8758. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8759. * @param u defines the coordinate on X axis
  8760. * @param v defines the coordinate on Y axis
  8761. * @param width defines the width of the source data
  8762. * @param height defines the height of the source data
  8763. * @param pixels defines the source byte array
  8764. * @param color defines the output color
  8765. */
  8766. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8767. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8768. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8769. var position = (wrappedU + wrappedV * width) * 4;
  8770. color.r = pixels[position] / 255;
  8771. color.g = pixels[position + 1] / 255;
  8772. color.b = pixels[position + 2] / 255;
  8773. color.a = pixels[position + 3] / 255;
  8774. };
  8775. /**
  8776. * Interpolates between a and b via alpha
  8777. * @param a The lower value (returned when alpha = 0)
  8778. * @param b The upper value (returned when alpha = 1)
  8779. * @param alpha The interpolation-factor
  8780. * @return The mixed value
  8781. */
  8782. Tools.Mix = function (a, b, alpha) {
  8783. return a * (1 - alpha) + b * alpha;
  8784. };
  8785. Tools.Instantiate = function (className) {
  8786. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8787. return Tools.RegisteredExternalClasses[className];
  8788. }
  8789. var arr = className.split(".");
  8790. var fn = (window || this);
  8791. for (var i = 0, len = arr.length; i < len; i++) {
  8792. fn = fn[arr[i]];
  8793. }
  8794. if (typeof fn !== "function") {
  8795. return null;
  8796. }
  8797. return fn;
  8798. };
  8799. /**
  8800. * Provides a slice function that will work even on IE
  8801. * @param data defines the array to slice
  8802. * @param start defines the start of the data (optional)
  8803. * @param end defines the end of the data (optional)
  8804. * @returns the new sliced array
  8805. */
  8806. Tools.Slice = function (data, start, end) {
  8807. if (data.slice) {
  8808. return data.slice(start, end);
  8809. }
  8810. return Array.prototype.slice.call(data, start, end);
  8811. };
  8812. Tools.SetImmediate = function (action) {
  8813. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8814. window.setImmediate(action);
  8815. }
  8816. else {
  8817. setTimeout(action, 1);
  8818. }
  8819. };
  8820. Tools.IsExponentOfTwo = function (value) {
  8821. var count = 1;
  8822. do {
  8823. count *= 2;
  8824. } while (count < value);
  8825. return count === value;
  8826. };
  8827. /**
  8828. * Returns the nearest 32-bit single precision float representation of a Number
  8829. * @param value A Number. If the parameter is of a different type, it will get converted
  8830. * to a number or to NaN if it cannot be converted
  8831. * @returns number
  8832. */
  8833. Tools.FloatRound = function (value) {
  8834. if (Math.fround) {
  8835. return Math.fround(value);
  8836. }
  8837. return (Tools._tmpFloatArray[0] = value);
  8838. };
  8839. /**
  8840. * Find the next highest power of two.
  8841. * @param x Number to start search from.
  8842. * @return Next highest power of two.
  8843. */
  8844. Tools.CeilingPOT = function (x) {
  8845. x--;
  8846. x |= x >> 1;
  8847. x |= x >> 2;
  8848. x |= x >> 4;
  8849. x |= x >> 8;
  8850. x |= x >> 16;
  8851. x++;
  8852. return x;
  8853. };
  8854. /**
  8855. * Find the next lowest power of two.
  8856. * @param x Number to start search from.
  8857. * @return Next lowest power of two.
  8858. */
  8859. Tools.FloorPOT = function (x) {
  8860. x = x | (x >> 1);
  8861. x = x | (x >> 2);
  8862. x = x | (x >> 4);
  8863. x = x | (x >> 8);
  8864. x = x | (x >> 16);
  8865. return x - (x >> 1);
  8866. };
  8867. /**
  8868. * Find the nearest power of two.
  8869. * @param x Number to start search from.
  8870. * @return Next nearest power of two.
  8871. */
  8872. Tools.NearestPOT = function (x) {
  8873. var c = Tools.CeilingPOT(x);
  8874. var f = Tools.FloorPOT(x);
  8875. return (c - x) > (x - f) ? f : c;
  8876. };
  8877. Tools.GetExponentOfTwo = function (value, max, mode) {
  8878. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8879. var pot;
  8880. switch (mode) {
  8881. case BABYLON.Engine.SCALEMODE_FLOOR:
  8882. pot = Tools.FloorPOT(value);
  8883. break;
  8884. case BABYLON.Engine.SCALEMODE_NEAREST:
  8885. pot = Tools.NearestPOT(value);
  8886. break;
  8887. case BABYLON.Engine.SCALEMODE_CEILING:
  8888. default:
  8889. pot = Tools.CeilingPOT(value);
  8890. break;
  8891. }
  8892. return Math.min(pot, max);
  8893. };
  8894. Tools.GetFilename = function (path) {
  8895. var index = path.lastIndexOf("/");
  8896. if (index < 0)
  8897. return path;
  8898. return path.substring(index + 1);
  8899. };
  8900. /**
  8901. * Extracts the "folder" part of a path (everything before the filename).
  8902. * @param uri The URI to extract the info from
  8903. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8904. * @returns The "folder" part of the path
  8905. */
  8906. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8907. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8908. var index = uri.lastIndexOf("/");
  8909. if (index < 0) {
  8910. if (returnUnchangedIfNoSlash) {
  8911. return uri;
  8912. }
  8913. return "";
  8914. }
  8915. return uri.substring(0, index + 1);
  8916. };
  8917. Tools.GetDOMTextContent = function (element) {
  8918. var result = "";
  8919. var child = element.firstChild;
  8920. while (child) {
  8921. if (child.nodeType === 3) {
  8922. result += child.textContent;
  8923. }
  8924. child = child.nextSibling;
  8925. }
  8926. return result;
  8927. };
  8928. Tools.ToDegrees = function (angle) {
  8929. return angle * 180 / Math.PI;
  8930. };
  8931. Tools.ToRadians = function (angle) {
  8932. return angle * Math.PI / 180;
  8933. };
  8934. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8935. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8936. var output = "";
  8937. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8938. var i = 0;
  8939. var bytes = new Uint8Array(buffer);
  8940. while (i < bytes.length) {
  8941. chr1 = bytes[i++];
  8942. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8943. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8944. enc1 = chr1 >> 2;
  8945. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8946. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8947. enc4 = chr3 & 63;
  8948. if (isNaN(chr2)) {
  8949. enc3 = enc4 = 64;
  8950. }
  8951. else if (isNaN(chr3)) {
  8952. enc4 = 64;
  8953. }
  8954. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8955. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8956. }
  8957. return "data:image/png;base64," + output;
  8958. };
  8959. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8960. if (bias === void 0) { bias = null; }
  8961. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8962. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8963. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8964. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8965. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8966. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8967. }
  8968. if (bias) {
  8969. minimum.x -= minimum.x * bias.x + bias.y;
  8970. minimum.y -= minimum.y * bias.x + bias.y;
  8971. minimum.z -= minimum.z * bias.x + bias.y;
  8972. maximum.x += maximum.x * bias.x + bias.y;
  8973. maximum.y += maximum.y * bias.x + bias.y;
  8974. maximum.z += maximum.z * bias.x + bias.y;
  8975. }
  8976. return {
  8977. minimum: minimum,
  8978. maximum: maximum
  8979. };
  8980. };
  8981. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8982. if (bias === void 0) { bias = null; }
  8983. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8984. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8985. if (!stride) {
  8986. stride = 3;
  8987. }
  8988. for (var index = start; index < start + count; index++) {
  8989. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8990. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8991. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8992. }
  8993. if (bias) {
  8994. minimum.x -= minimum.x * bias.x + bias.y;
  8995. minimum.y -= minimum.y * bias.x + bias.y;
  8996. minimum.z -= minimum.z * bias.x + bias.y;
  8997. maximum.x += maximum.x * bias.x + bias.y;
  8998. maximum.y += maximum.y * bias.x + bias.y;
  8999. maximum.z += maximum.z * bias.x + bias.y;
  9000. }
  9001. return {
  9002. minimum: minimum,
  9003. maximum: maximum
  9004. };
  9005. };
  9006. Tools.Vector2ArrayFeeder = function (array) {
  9007. return function (index) {
  9008. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  9009. var length = isFloatArray ? array.length / 2 : array.length;
  9010. if (index >= length) {
  9011. return null;
  9012. }
  9013. if (isFloatArray) {
  9014. var fa = array;
  9015. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  9016. }
  9017. var a = array;
  9018. return a[index];
  9019. };
  9020. };
  9021. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  9022. if (bias === void 0) { bias = null; }
  9023. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  9024. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  9025. var i = 0;
  9026. var cur = feeder(i++);
  9027. while (cur) {
  9028. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  9029. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  9030. cur = feeder(i++);
  9031. }
  9032. if (bias) {
  9033. minimum.x -= minimum.x * bias.x + bias.y;
  9034. minimum.y -= minimum.y * bias.x + bias.y;
  9035. maximum.x += maximum.x * bias.x + bias.y;
  9036. maximum.y += maximum.y * bias.x + bias.y;
  9037. }
  9038. return {
  9039. minimum: minimum,
  9040. maximum: maximum
  9041. };
  9042. };
  9043. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9044. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9045. return null;
  9046. return Array.isArray(obj) ? obj : [obj];
  9047. };
  9048. // Misc.
  9049. Tools.GetPointerPrefix = function () {
  9050. var eventPrefix = "pointer";
  9051. // Check if pointer events are supported
  9052. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9053. eventPrefix = "mouse";
  9054. }
  9055. return eventPrefix;
  9056. };
  9057. /**
  9058. * @param func - the function to be called
  9059. * @param requester - the object that will request the next frame. Falls back to window.
  9060. */
  9061. Tools.QueueNewFrame = function (func, requester) {
  9062. if (!Tools.IsWindowObjectExist()) {
  9063. return setTimeout(func, 16);
  9064. }
  9065. if (!requester) {
  9066. requester = window;
  9067. }
  9068. if (requester.requestAnimationFrame) {
  9069. return requester.requestAnimationFrame(func);
  9070. }
  9071. else if (requester.msRequestAnimationFrame) {
  9072. return requester.msRequestAnimationFrame(func);
  9073. }
  9074. else if (requester.webkitRequestAnimationFrame) {
  9075. return requester.webkitRequestAnimationFrame(func);
  9076. }
  9077. else if (requester.mozRequestAnimationFrame) {
  9078. return requester.mozRequestAnimationFrame(func);
  9079. }
  9080. else if (requester.oRequestAnimationFrame) {
  9081. return requester.oRequestAnimationFrame(func);
  9082. }
  9083. else {
  9084. return window.setTimeout(func, 16);
  9085. }
  9086. };
  9087. Tools.RequestFullscreen = function (element) {
  9088. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9089. if (!requestFunction)
  9090. return;
  9091. requestFunction.call(element);
  9092. };
  9093. Tools.ExitFullscreen = function () {
  9094. if (document.exitFullscreen) {
  9095. document.exitFullscreen();
  9096. }
  9097. else if (document.mozCancelFullScreen) {
  9098. document.mozCancelFullScreen();
  9099. }
  9100. else if (document.webkitCancelFullScreen) {
  9101. document.webkitCancelFullScreen();
  9102. }
  9103. else if (document.msCancelFullScreen) {
  9104. document.msCancelFullScreen();
  9105. }
  9106. };
  9107. Tools.SetCorsBehavior = function (url, element) {
  9108. if (url && url.indexOf("data:") === 0) {
  9109. return;
  9110. }
  9111. if (Tools.CorsBehavior) {
  9112. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9113. element.crossOrigin = Tools.CorsBehavior;
  9114. }
  9115. else {
  9116. var result = Tools.CorsBehavior(url);
  9117. if (result) {
  9118. element.crossOrigin = result;
  9119. }
  9120. }
  9121. }
  9122. };
  9123. // External files
  9124. Tools.CleanUrl = function (url) {
  9125. url = url.replace(/#/mg, "%23");
  9126. return url;
  9127. };
  9128. /**
  9129. * Loads an image as an HTMLImageElement.
  9130. * @param input url string, ArrayBuffer, or Blob to load
  9131. * @param onLoad callback called when the image successfully loads
  9132. * @param onError callback called when the image fails to load
  9133. * @param database database for caching
  9134. * @returns the HTMLImageElement of the loaded image
  9135. */
  9136. Tools.LoadImage = function (input, onLoad, onError, database) {
  9137. var url;
  9138. var usingObjectURL = false;
  9139. if (input instanceof ArrayBuffer) {
  9140. url = URL.createObjectURL(new Blob([input]));
  9141. usingObjectURL = true;
  9142. }
  9143. else if (input instanceof Blob) {
  9144. url = URL.createObjectURL(input);
  9145. usingObjectURL = true;
  9146. }
  9147. else {
  9148. url = Tools.CleanUrl(input);
  9149. url = Tools.PreprocessUrl(input);
  9150. }
  9151. var img = new Image();
  9152. Tools.SetCorsBehavior(url, img);
  9153. var loadHandler = function () {
  9154. if (usingObjectURL && img.src) {
  9155. URL.revokeObjectURL(img.src);
  9156. }
  9157. img.removeEventListener("load", loadHandler);
  9158. img.removeEventListener("error", errorHandler);
  9159. onLoad(img);
  9160. };
  9161. var errorHandler = function (err) {
  9162. if (usingObjectURL && img.src) {
  9163. URL.revokeObjectURL(img.src);
  9164. }
  9165. img.removeEventListener("load", loadHandler);
  9166. img.removeEventListener("error", errorHandler);
  9167. Tools.Error("Error while trying to load image: " + input);
  9168. if (onError) {
  9169. onError("Error while trying to load image: " + input, err);
  9170. }
  9171. };
  9172. img.addEventListener("load", loadHandler);
  9173. img.addEventListener("error", errorHandler);
  9174. var noIndexedDB = function () {
  9175. img.src = url;
  9176. };
  9177. var loadFromIndexedDB = function () {
  9178. if (database) {
  9179. database.loadImageFromDB(url, img);
  9180. }
  9181. };
  9182. //ANY database to do!
  9183. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9184. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9185. }
  9186. else {
  9187. if (url.indexOf("file:") !== -1) {
  9188. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9189. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9190. try {
  9191. var blobURL;
  9192. try {
  9193. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9194. }
  9195. catch (ex) {
  9196. // Chrome doesn't support oneTimeOnly parameter
  9197. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9198. }
  9199. img.src = blobURL;
  9200. usingObjectURL = true;
  9201. }
  9202. catch (e) {
  9203. img.src = "";
  9204. }
  9205. return img;
  9206. }
  9207. }
  9208. noIndexedDB();
  9209. }
  9210. return img;
  9211. };
  9212. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9213. url = Tools.CleanUrl(url);
  9214. url = Tools.PreprocessUrl(url);
  9215. // If file and file input are set
  9216. if (url.indexOf("file:") !== -1) {
  9217. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9218. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9219. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9220. }
  9221. }
  9222. var loadUrl = Tools.BaseUrl + url;
  9223. var aborted = false;
  9224. var fileRequest = {
  9225. onCompleteObservable: new BABYLON.Observable(),
  9226. abort: function () { return aborted = true; },
  9227. };
  9228. var requestFile = function () {
  9229. var request = new XMLHttpRequest();
  9230. var retryHandle = null;
  9231. fileRequest.abort = function () {
  9232. aborted = true;
  9233. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9234. request.abort();
  9235. }
  9236. if (retryHandle !== null) {
  9237. clearTimeout(retryHandle);
  9238. retryHandle = null;
  9239. }
  9240. };
  9241. var retryLoop = function (retryIndex) {
  9242. request.open('GET', loadUrl, true);
  9243. if (useArrayBuffer) {
  9244. request.responseType = "arraybuffer";
  9245. }
  9246. if (onProgress) {
  9247. request.addEventListener("progress", onProgress);
  9248. }
  9249. var onLoadEnd = function () {
  9250. request.removeEventListener("loadend", onLoadEnd);
  9251. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9252. fileRequest.onCompleteObservable.clear();
  9253. };
  9254. request.addEventListener("loadend", onLoadEnd);
  9255. var onReadyStateChange = function () {
  9256. if (aborted) {
  9257. return;
  9258. }
  9259. // In case of undefined state in some browsers.
  9260. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9261. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9262. request.removeEventListener("readystatechange", onReadyStateChange);
  9263. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9264. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9265. return;
  9266. }
  9267. var retryStrategy = Tools.DefaultRetryStrategy;
  9268. if (retryStrategy) {
  9269. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9270. if (waitTime !== -1) {
  9271. // Prevent the request from completing for retry.
  9272. request.removeEventListener("loadend", onLoadEnd);
  9273. request = new XMLHttpRequest();
  9274. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9275. return;
  9276. }
  9277. }
  9278. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9279. if (onError) {
  9280. onError(request, e);
  9281. }
  9282. else {
  9283. throw e;
  9284. }
  9285. }
  9286. };
  9287. request.addEventListener("readystatechange", onReadyStateChange);
  9288. request.send();
  9289. };
  9290. retryLoop(0);
  9291. };
  9292. // Caching all files
  9293. if (database && database.enableSceneOffline) {
  9294. var noIndexedDB_1 = function (request) {
  9295. if (request && request.status > 400) {
  9296. if (onError) {
  9297. onError(request);
  9298. }
  9299. }
  9300. else {
  9301. if (!aborted) {
  9302. requestFile();
  9303. }
  9304. }
  9305. };
  9306. var loadFromIndexedDB = function () {
  9307. // TODO: database needs to support aborting and should return a IFileRequest
  9308. if (aborted) {
  9309. return;
  9310. }
  9311. if (database) {
  9312. database.loadFileFromDB(url, function (data) {
  9313. if (!aborted) {
  9314. onSuccess(data);
  9315. }
  9316. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9317. }, onProgress ? function (event) {
  9318. if (!aborted) {
  9319. onProgress(event);
  9320. }
  9321. } : undefined, noIndexedDB_1, useArrayBuffer);
  9322. }
  9323. };
  9324. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9325. }
  9326. else {
  9327. requestFile();
  9328. }
  9329. return fileRequest;
  9330. };
  9331. /**
  9332. * Load a script (identified by an url). When the url returns, the
  9333. * content of this file is added into a new script element, attached to the DOM (body element)
  9334. */
  9335. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9336. if (!Tools.IsWindowObjectExist()) {
  9337. return;
  9338. }
  9339. var head = document.getElementsByTagName('head')[0];
  9340. var script = document.createElement('script');
  9341. script.type = 'text/javascript';
  9342. script.src = scriptUrl;
  9343. script.onload = function () {
  9344. if (onSuccess) {
  9345. onSuccess();
  9346. }
  9347. };
  9348. script.onerror = function (e) {
  9349. if (onError) {
  9350. onError("Unable to load script '" + scriptUrl + "'", e);
  9351. }
  9352. };
  9353. head.appendChild(script);
  9354. };
  9355. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9356. var reader = new FileReader();
  9357. var request = {
  9358. onCompleteObservable: new BABYLON.Observable(),
  9359. abort: function () { return reader.abort(); },
  9360. };
  9361. reader.onloadend = function (e) {
  9362. request.onCompleteObservable.notifyObservers(request);
  9363. };
  9364. reader.onload = function (e) {
  9365. //target doesn't have result from ts 1.3
  9366. callback(e.target['result']);
  9367. };
  9368. reader.onprogress = progressCallback;
  9369. reader.readAsDataURL(fileToLoad);
  9370. return request;
  9371. };
  9372. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9373. var reader = new FileReader();
  9374. var request = {
  9375. onCompleteObservable: new BABYLON.Observable(),
  9376. abort: function () { return reader.abort(); },
  9377. };
  9378. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9379. reader.onerror = function (e) {
  9380. Tools.Log("Error while reading file: " + fileToLoad.name);
  9381. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9382. };
  9383. reader.onload = function (e) {
  9384. //target doesn't have result from ts 1.3
  9385. callback(e.target['result']);
  9386. };
  9387. if (progressCallBack) {
  9388. reader.onprogress = progressCallBack;
  9389. }
  9390. if (!useArrayBuffer) {
  9391. // Asynchronous read
  9392. reader.readAsText(fileToLoad);
  9393. }
  9394. else {
  9395. reader.readAsArrayBuffer(fileToLoad);
  9396. }
  9397. return request;
  9398. };
  9399. //returns a downloadable url to a file content.
  9400. Tools.FileAsURL = function (content) {
  9401. var fileBlob = new Blob([content]);
  9402. var url = window.URL || window.webkitURL;
  9403. var link = url.createObjectURL(fileBlob);
  9404. return link;
  9405. };
  9406. // Misc.
  9407. Tools.Format = function (value, decimals) {
  9408. if (decimals === void 0) { decimals = 2; }
  9409. return value.toFixed(decimals);
  9410. };
  9411. Tools.CheckExtends = function (v, min, max) {
  9412. if (v.x < min.x)
  9413. min.x = v.x;
  9414. if (v.y < min.y)
  9415. min.y = v.y;
  9416. if (v.z < min.z)
  9417. min.z = v.z;
  9418. if (v.x > max.x)
  9419. max.x = v.x;
  9420. if (v.y > max.y)
  9421. max.y = v.y;
  9422. if (v.z > max.z)
  9423. max.z = v.z;
  9424. };
  9425. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9426. for (var prop in source) {
  9427. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9428. continue;
  9429. }
  9430. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9431. continue;
  9432. }
  9433. var sourceValue = source[prop];
  9434. var typeOfSourceValue = typeof sourceValue;
  9435. if (typeOfSourceValue === "function") {
  9436. continue;
  9437. }
  9438. try {
  9439. if (typeOfSourceValue === "object") {
  9440. if (sourceValue instanceof Array) {
  9441. destination[prop] = [];
  9442. if (sourceValue.length > 0) {
  9443. if (typeof sourceValue[0] == "object") {
  9444. for (var index = 0; index < sourceValue.length; index++) {
  9445. var clonedValue = cloneValue(sourceValue[index], destination);
  9446. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9447. destination[prop].push(clonedValue);
  9448. }
  9449. }
  9450. }
  9451. else {
  9452. destination[prop] = sourceValue.slice(0);
  9453. }
  9454. }
  9455. }
  9456. else {
  9457. destination[prop] = cloneValue(sourceValue, destination);
  9458. }
  9459. }
  9460. else {
  9461. destination[prop] = sourceValue;
  9462. }
  9463. }
  9464. catch (e) {
  9465. // Just ignore error (it could be because of a read-only property)
  9466. }
  9467. }
  9468. };
  9469. Tools.IsEmpty = function (obj) {
  9470. for (var i in obj) {
  9471. if (obj.hasOwnProperty(i)) {
  9472. return false;
  9473. }
  9474. }
  9475. return true;
  9476. };
  9477. Tools.RegisterTopRootEvents = function (events) {
  9478. for (var index = 0; index < events.length; index++) {
  9479. var event = events[index];
  9480. window.addEventListener(event.name, event.handler, false);
  9481. try {
  9482. if (window.parent) {
  9483. window.parent.addEventListener(event.name, event.handler, false);
  9484. }
  9485. }
  9486. catch (e) {
  9487. // Silently fails...
  9488. }
  9489. }
  9490. };
  9491. Tools.UnregisterTopRootEvents = function (events) {
  9492. for (var index = 0; index < events.length; index++) {
  9493. var event = events[index];
  9494. window.removeEventListener(event.name, event.handler);
  9495. try {
  9496. if (window.parent) {
  9497. window.parent.removeEventListener(event.name, event.handler);
  9498. }
  9499. }
  9500. catch (e) {
  9501. // Silently fails...
  9502. }
  9503. }
  9504. };
  9505. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9506. if (mimeType === void 0) { mimeType = "image/png"; }
  9507. // Read the contents of the framebuffer
  9508. var numberOfChannelsByLine = width * 4;
  9509. var halfHeight = height / 2;
  9510. //Reading datas from WebGL
  9511. var data = engine.readPixels(0, 0, width, height);
  9512. //To flip image on Y axis.
  9513. for (var i = 0; i < halfHeight; i++) {
  9514. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9515. var currentCell = j + i * numberOfChannelsByLine;
  9516. var targetLine = height - i - 1;
  9517. var targetCell = j + targetLine * numberOfChannelsByLine;
  9518. var temp = data[currentCell];
  9519. data[currentCell] = data[targetCell];
  9520. data[targetCell] = temp;
  9521. }
  9522. }
  9523. // Create a 2D canvas to store the result
  9524. if (!screenshotCanvas) {
  9525. screenshotCanvas = document.createElement('canvas');
  9526. }
  9527. screenshotCanvas.width = width;
  9528. screenshotCanvas.height = height;
  9529. var context = screenshotCanvas.getContext('2d');
  9530. if (context) {
  9531. // Copy the pixels to a 2D canvas
  9532. var imageData = context.createImageData(width, height);
  9533. var castData = (imageData.data);
  9534. castData.set(data);
  9535. context.putImageData(imageData, 0, 0);
  9536. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9537. }
  9538. };
  9539. /**
  9540. * Converts the canvas data to blob.
  9541. * This acts as a polyfill for browsers not supporting the to blob function.
  9542. * @param canvas Defines the canvas to extract the data from
  9543. * @param successCallback Defines the callback triggered once the data are available
  9544. * @param mimeType Defines the mime type of the result
  9545. */
  9546. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9547. if (mimeType === void 0) { mimeType = "image/png"; }
  9548. // We need HTMLCanvasElement.toBlob for HD screenshots
  9549. if (!canvas.toBlob) {
  9550. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9551. canvas.toBlob = function (callback, type, quality) {
  9552. var _this = this;
  9553. setTimeout(function () {
  9554. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9555. for (var i = 0; i < len; i++) {
  9556. arr[i] = binStr.charCodeAt(i);
  9557. }
  9558. callback(new Blob([arr]));
  9559. });
  9560. };
  9561. }
  9562. canvas.toBlob(function (blob) {
  9563. successCallback(blob);
  9564. }, mimeType);
  9565. };
  9566. /**
  9567. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9568. * @param successCallback Defines the callback triggered once the data are available
  9569. * @param mimeType Defines the mime type of the result
  9570. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9571. */
  9572. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9573. if (mimeType === void 0) { mimeType = "image/png"; }
  9574. if (successCallback) {
  9575. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9576. successCallback(base64Image);
  9577. }
  9578. else {
  9579. this.ToBlob(screenshotCanvas, function (blob) {
  9580. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9581. if (("download" in document.createElement("a"))) {
  9582. if (!fileName) {
  9583. var date = new Date();
  9584. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9585. fileName = "screenshot_" + stringDate + ".png";
  9586. }
  9587. Tools.Download(blob, fileName);
  9588. }
  9589. else {
  9590. var url = URL.createObjectURL(blob);
  9591. var newWindow = window.open("");
  9592. if (!newWindow)
  9593. return;
  9594. var img = newWindow.document.createElement("img");
  9595. img.onload = function () {
  9596. // no longer need to read the blob so it's revoked
  9597. URL.revokeObjectURL(url);
  9598. };
  9599. img.src = url;
  9600. newWindow.document.body.appendChild(img);
  9601. }
  9602. }, mimeType);
  9603. }
  9604. };
  9605. /**
  9606. * Downloads a blob in the browser
  9607. * @param blob defines the blob to download
  9608. * @param fileName defines the name of the downloaded file
  9609. */
  9610. Tools.Download = function (blob, fileName) {
  9611. if (navigator && navigator.msSaveBlob) {
  9612. navigator.msSaveBlob(blob, fileName);
  9613. return;
  9614. }
  9615. var url = window.URL.createObjectURL(blob);
  9616. var a = document.createElement("a");
  9617. document.body.appendChild(a);
  9618. a.style.display = "none";
  9619. a.href = url;
  9620. a.download = fileName;
  9621. a.addEventListener("click", function () {
  9622. if (a.parentElement) {
  9623. a.parentElement.removeChild(a);
  9624. }
  9625. });
  9626. a.click();
  9627. window.URL.revokeObjectURL(url);
  9628. };
  9629. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9630. if (mimeType === void 0) { mimeType = "image/png"; }
  9631. var width;
  9632. var height;
  9633. // If a precision value is specified
  9634. if (size.precision) {
  9635. width = Math.round(engine.getRenderWidth() * size.precision);
  9636. height = Math.round(width / engine.getAspectRatio(camera));
  9637. }
  9638. else if (size.width && size.height) {
  9639. width = size.width;
  9640. height = size.height;
  9641. }
  9642. //If passing only width, computing height to keep display canvas ratio.
  9643. else if (size.width && !size.height) {
  9644. width = size.width;
  9645. height = Math.round(width / engine.getAspectRatio(camera));
  9646. }
  9647. //If passing only height, computing width to keep display canvas ratio.
  9648. else if (size.height && !size.width) {
  9649. height = size.height;
  9650. width = Math.round(height * engine.getAspectRatio(camera));
  9651. }
  9652. //Assuming here that "size" parameter is a number
  9653. else if (!isNaN(size)) {
  9654. height = size;
  9655. width = size;
  9656. }
  9657. else {
  9658. Tools.Error("Invalid 'size' parameter !");
  9659. return;
  9660. }
  9661. if (!screenshotCanvas) {
  9662. screenshotCanvas = document.createElement('canvas');
  9663. }
  9664. screenshotCanvas.width = width;
  9665. screenshotCanvas.height = height;
  9666. var renderContext = screenshotCanvas.getContext("2d");
  9667. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9668. var newWidth = width;
  9669. var newHeight = newWidth / ratio;
  9670. if (newHeight > height) {
  9671. newHeight = height;
  9672. newWidth = newHeight * ratio;
  9673. }
  9674. var offsetX = Math.max(0, width - newWidth) / 2;
  9675. var offsetY = Math.max(0, height - newHeight) / 2;
  9676. var renderingCanvas = engine.getRenderingCanvas();
  9677. if (renderContext && renderingCanvas) {
  9678. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9679. }
  9680. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9681. };
  9682. /**
  9683. * Generates an image screenshot from the specified camera.
  9684. *
  9685. * @param engine The engine to use for rendering
  9686. * @param camera The camera to use for rendering
  9687. * @param size This parameter can be set to a single number or to an object with the
  9688. * following (optional) properties: precision, width, height. If a single number is passed,
  9689. * it will be used for both width and height. If an object is passed, the screenshot size
  9690. * will be derived from the parameters. The precision property is a multiplier allowing
  9691. * rendering at a higher or lower resolution.
  9692. * @param successCallback The callback receives a single parameter which contains the
  9693. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9694. * src parameter of an <img> to display it.
  9695. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9696. * Check your browser for supported MIME types.
  9697. * @param samples Texture samples (default: 1)
  9698. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9699. * @param fileName A name for for the downloaded file.
  9700. * @constructor
  9701. */
  9702. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9703. if (mimeType === void 0) { mimeType = "image/png"; }
  9704. if (samples === void 0) { samples = 1; }
  9705. if (antialiasing === void 0) { antialiasing = false; }
  9706. var width;
  9707. var height;
  9708. //If a precision value is specified
  9709. if (size.precision) {
  9710. width = Math.round(engine.getRenderWidth() * size.precision);
  9711. height = Math.round(width / engine.getAspectRatio(camera));
  9712. size = { width: width, height: height };
  9713. }
  9714. else if (size.width && size.height) {
  9715. width = size.width;
  9716. height = size.height;
  9717. }
  9718. //If passing only width, computing height to keep display canvas ratio.
  9719. else if (size.width && !size.height) {
  9720. width = size.width;
  9721. height = Math.round(width / engine.getAspectRatio(camera));
  9722. size = { width: width, height: height };
  9723. }
  9724. //If passing only height, computing width to keep display canvas ratio.
  9725. else if (size.height && !size.width) {
  9726. height = size.height;
  9727. width = Math.round(height * engine.getAspectRatio(camera));
  9728. size = { width: width, height: height };
  9729. }
  9730. //Assuming here that "size" parameter is a number
  9731. else if (!isNaN(size)) {
  9732. height = size;
  9733. width = size;
  9734. }
  9735. else {
  9736. Tools.Error("Invalid 'size' parameter !");
  9737. return;
  9738. }
  9739. var scene = camera.getScene();
  9740. var previousCamera = null;
  9741. if (scene.activeCamera !== camera) {
  9742. previousCamera = scene.activeCamera;
  9743. scene.activeCamera = camera;
  9744. }
  9745. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9746. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9747. texture.renderList = null;
  9748. texture.samples = samples;
  9749. if (antialiasing) {
  9750. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9751. }
  9752. texture.onAfterRenderObservable.add(function () {
  9753. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9754. });
  9755. scene.incrementRenderId();
  9756. scene.resetCachedMaterial();
  9757. texture.render(true);
  9758. texture.dispose();
  9759. if (previousCamera) {
  9760. scene.activeCamera = previousCamera;
  9761. }
  9762. camera.getProjectionMatrix(true); // Force cache refresh;
  9763. };
  9764. // XHR response validator for local file scenario
  9765. Tools.ValidateXHRData = function (xhr, dataType) {
  9766. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9767. if (dataType === void 0) { dataType = 7; }
  9768. try {
  9769. if (dataType & 1) {
  9770. if (xhr.responseText && xhr.responseText.length > 0) {
  9771. return true;
  9772. }
  9773. else if (dataType === 1) {
  9774. return false;
  9775. }
  9776. }
  9777. if (dataType & 2) {
  9778. // Check header width and height since there is no "TGA" magic number
  9779. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9780. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9781. return true;
  9782. }
  9783. else if (dataType === 2) {
  9784. return false;
  9785. }
  9786. }
  9787. if (dataType & 4) {
  9788. // Check for the "DDS" magic number
  9789. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9790. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9791. return true;
  9792. }
  9793. else {
  9794. return false;
  9795. }
  9796. }
  9797. }
  9798. catch (e) {
  9799. // Global protection
  9800. }
  9801. return false;
  9802. };
  9803. /**
  9804. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9805. * Be aware Math.random() could cause collisions, but:
  9806. * "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"
  9807. */
  9808. Tools.RandomId = function () {
  9809. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9810. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9811. return v.toString(16);
  9812. });
  9813. };
  9814. /**
  9815. * Test if the given uri is a base64 string.
  9816. * @param uri The uri to test
  9817. * @return True if the uri is a base64 string or false otherwise.
  9818. */
  9819. Tools.IsBase64 = function (uri) {
  9820. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9821. };
  9822. /**
  9823. * Decode the given base64 uri.
  9824. * @param uri The uri to decode
  9825. * @return The decoded base64 data.
  9826. */
  9827. Tools.DecodeBase64 = function (uri) {
  9828. var decodedString = atob(uri.split(",")[1]);
  9829. var bufferLength = decodedString.length;
  9830. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9831. for (var i = 0; i < bufferLength; i++) {
  9832. bufferView[i] = decodedString.charCodeAt(i);
  9833. }
  9834. return bufferView.buffer;
  9835. };
  9836. Object.defineProperty(Tools, "NoneLogLevel", {
  9837. get: function () {
  9838. return Tools._NoneLogLevel;
  9839. },
  9840. enumerable: true,
  9841. configurable: true
  9842. });
  9843. Object.defineProperty(Tools, "MessageLogLevel", {
  9844. get: function () {
  9845. return Tools._MessageLogLevel;
  9846. },
  9847. enumerable: true,
  9848. configurable: true
  9849. });
  9850. Object.defineProperty(Tools, "WarningLogLevel", {
  9851. get: function () {
  9852. return Tools._WarningLogLevel;
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. Object.defineProperty(Tools, "ErrorLogLevel", {
  9858. get: function () {
  9859. return Tools._ErrorLogLevel;
  9860. },
  9861. enumerable: true,
  9862. configurable: true
  9863. });
  9864. Object.defineProperty(Tools, "AllLogLevel", {
  9865. get: function () {
  9866. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9867. },
  9868. enumerable: true,
  9869. configurable: true
  9870. });
  9871. Tools._AddLogEntry = function (entry) {
  9872. Tools._LogCache = entry + Tools._LogCache;
  9873. if (Tools.OnNewCacheEntry) {
  9874. Tools.OnNewCacheEntry(entry);
  9875. }
  9876. };
  9877. Tools._FormatMessage = function (message) {
  9878. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9879. var date = new Date();
  9880. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9881. };
  9882. Tools._LogDisabled = function (message) {
  9883. // nothing to do
  9884. };
  9885. Tools._LogEnabled = function (message) {
  9886. var formattedMessage = Tools._FormatMessage(message);
  9887. console.log("BJS - " + formattedMessage);
  9888. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9889. Tools._AddLogEntry(entry);
  9890. };
  9891. Tools._WarnDisabled = function (message) {
  9892. // nothing to do
  9893. };
  9894. Tools._WarnEnabled = function (message) {
  9895. var formattedMessage = Tools._FormatMessage(message);
  9896. console.warn("BJS - " + formattedMessage);
  9897. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9898. Tools._AddLogEntry(entry);
  9899. };
  9900. Tools._ErrorDisabled = function (message) {
  9901. // nothing to do
  9902. };
  9903. Tools._ErrorEnabled = function (message) {
  9904. Tools.errorsCount++;
  9905. var formattedMessage = Tools._FormatMessage(message);
  9906. console.error("BJS - " + formattedMessage);
  9907. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9908. Tools._AddLogEntry(entry);
  9909. };
  9910. Object.defineProperty(Tools, "LogCache", {
  9911. get: function () {
  9912. return Tools._LogCache;
  9913. },
  9914. enumerable: true,
  9915. configurable: true
  9916. });
  9917. Tools.ClearLogCache = function () {
  9918. Tools._LogCache = "";
  9919. Tools.errorsCount = 0;
  9920. };
  9921. Object.defineProperty(Tools, "LogLevels", {
  9922. set: function (level) {
  9923. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9924. Tools.Log = Tools._LogEnabled;
  9925. }
  9926. else {
  9927. Tools.Log = Tools._LogDisabled;
  9928. }
  9929. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9930. Tools.Warn = Tools._WarnEnabled;
  9931. }
  9932. else {
  9933. Tools.Warn = Tools._WarnDisabled;
  9934. }
  9935. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9936. Tools.Error = Tools._ErrorEnabled;
  9937. }
  9938. else {
  9939. Tools.Error = Tools._ErrorDisabled;
  9940. }
  9941. },
  9942. enumerable: true,
  9943. configurable: true
  9944. });
  9945. /**
  9946. * Check if the loaded document was accessed via `file:`-Protocol.
  9947. * @returns boolean
  9948. */
  9949. Tools.IsFileURL = function () {
  9950. return location.protocol === "file:";
  9951. };
  9952. Tools.IsWindowObjectExist = function () {
  9953. return (typeof window) !== "undefined";
  9954. };
  9955. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9956. get: function () {
  9957. return Tools._PerformanceNoneLogLevel;
  9958. },
  9959. enumerable: true,
  9960. configurable: true
  9961. });
  9962. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9963. get: function () {
  9964. return Tools._PerformanceUserMarkLogLevel;
  9965. },
  9966. enumerable: true,
  9967. configurable: true
  9968. });
  9969. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9970. get: function () {
  9971. return Tools._PerformanceConsoleLogLevel;
  9972. },
  9973. enumerable: true,
  9974. configurable: true
  9975. });
  9976. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9977. set: function (level) {
  9978. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9979. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9980. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9981. return;
  9982. }
  9983. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9984. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9985. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9986. return;
  9987. }
  9988. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9989. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9990. },
  9991. enumerable: true,
  9992. configurable: true
  9993. });
  9994. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9995. };
  9996. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9997. };
  9998. Tools._StartUserMark = function (counterName, condition) {
  9999. if (condition === void 0) { condition = true; }
  10000. if (!Tools._performance) {
  10001. if (!Tools.IsWindowObjectExist()) {
  10002. return;
  10003. }
  10004. Tools._performance = window.performance;
  10005. }
  10006. if (!condition || !Tools._performance.mark) {
  10007. return;
  10008. }
  10009. Tools._performance.mark(counterName + "-Begin");
  10010. };
  10011. Tools._EndUserMark = function (counterName, condition) {
  10012. if (condition === void 0) { condition = true; }
  10013. if (!condition || !Tools._performance.mark) {
  10014. return;
  10015. }
  10016. Tools._performance.mark(counterName + "-End");
  10017. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10018. };
  10019. Tools._StartPerformanceConsole = function (counterName, condition) {
  10020. if (condition === void 0) { condition = true; }
  10021. if (!condition) {
  10022. return;
  10023. }
  10024. Tools._StartUserMark(counterName, condition);
  10025. if (console.time) {
  10026. console.time(counterName);
  10027. }
  10028. };
  10029. Tools._EndPerformanceConsole = function (counterName, condition) {
  10030. if (condition === void 0) { condition = true; }
  10031. if (!condition) {
  10032. return;
  10033. }
  10034. Tools._EndUserMark(counterName, condition);
  10035. if (console.time) {
  10036. console.timeEnd(counterName);
  10037. }
  10038. };
  10039. Object.defineProperty(Tools, "Now", {
  10040. get: function () {
  10041. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10042. return window.performance.now();
  10043. }
  10044. return Date.now();
  10045. },
  10046. enumerable: true,
  10047. configurable: true
  10048. });
  10049. /**
  10050. * This method will return the name of the class used to create the instance of the given object.
  10051. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10052. * @param object the object to get the class name from
  10053. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10054. */
  10055. Tools.GetClassName = function (object, isType) {
  10056. if (isType === void 0) { isType = false; }
  10057. var name = null;
  10058. if (!isType && object.getClassName) {
  10059. name = object.getClassName();
  10060. }
  10061. else {
  10062. if (object instanceof Object) {
  10063. var classObj = isType ? object : Object.getPrototypeOf(object);
  10064. name = classObj.constructor["__bjsclassName__"];
  10065. }
  10066. if (!name) {
  10067. name = typeof object;
  10068. }
  10069. }
  10070. return name;
  10071. };
  10072. Tools.First = function (array, predicate) {
  10073. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10074. var el = array_1[_i];
  10075. if (predicate(el)) {
  10076. return el;
  10077. }
  10078. }
  10079. return null;
  10080. };
  10081. /**
  10082. * This method will return the name of the full name of the class, including its owning module (if any).
  10083. * 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).
  10084. * @param object the object to get the class name from
  10085. * @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.
  10086. */
  10087. Tools.getFullClassName = function (object, isType) {
  10088. if (isType === void 0) { isType = false; }
  10089. var className = null;
  10090. var moduleName = null;
  10091. if (!isType && object.getClassName) {
  10092. className = object.getClassName();
  10093. }
  10094. else {
  10095. if (object instanceof Object) {
  10096. var classObj = isType ? object : Object.getPrototypeOf(object);
  10097. className = classObj.constructor["__bjsclassName__"];
  10098. moduleName = classObj.constructor["__bjsmoduleName__"];
  10099. }
  10100. if (!className) {
  10101. className = typeof object;
  10102. }
  10103. }
  10104. if (!className) {
  10105. return null;
  10106. }
  10107. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10108. };
  10109. /**
  10110. * 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.
  10111. * @param array
  10112. */
  10113. Tools.arrayOrStringFeeder = function (array) {
  10114. return function (index) {
  10115. if (index >= array.length) {
  10116. return null;
  10117. }
  10118. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10119. if (val && val.getHashCode) {
  10120. val = val.getHashCode();
  10121. }
  10122. if (typeof val === "string") {
  10123. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10124. }
  10125. return val;
  10126. };
  10127. };
  10128. /**
  10129. * Compute the hashCode of a stream of number
  10130. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10131. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10132. * @return the hash code computed
  10133. */
  10134. Tools.hashCodeFromStream = function (feeder) {
  10135. // Based from here: http://stackoverflow.com/a/7616484/802124
  10136. var hash = 0;
  10137. var index = 0;
  10138. var chr = feeder(index++);
  10139. while (chr != null) {
  10140. hash = ((hash << 5) - hash) + chr;
  10141. hash |= 0; // Convert to 32bit integer
  10142. chr = feeder(index++);
  10143. }
  10144. return hash;
  10145. };
  10146. /**
  10147. * Returns a promise that resolves after the given amount of time.
  10148. * @param delay Number of milliseconds to delay
  10149. * @returns Promise that resolves after the given amount of time
  10150. */
  10151. Tools.DelayAsync = function (delay) {
  10152. return new Promise(function (resolve) {
  10153. setTimeout(function () {
  10154. resolve();
  10155. }, delay);
  10156. });
  10157. };
  10158. /**
  10159. * Gets the current gradient from an array of IValueGradient
  10160. * @param ratio defines the current ratio to get
  10161. * @param gradients defines the array of IValueGradient
  10162. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10163. */
  10164. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10165. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10166. var currentGradient = gradients[gradientIndex];
  10167. var nextGradient = gradients[gradientIndex + 1];
  10168. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10169. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10170. updateFunc(currentGradient, nextGradient, scale);
  10171. return;
  10172. }
  10173. }
  10174. // Use last index if over
  10175. var lastIndex = gradients.length - 1;
  10176. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10177. };
  10178. Tools.BaseUrl = "";
  10179. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10180. /**
  10181. * Default behaviour for cors in the application.
  10182. * It can be a string if the expected behavior is identical in the entire app.
  10183. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10184. */
  10185. Tools.CorsBehavior = "anonymous";
  10186. Tools.UseFallbackTexture = true;
  10187. /**
  10188. * Use this object to register external classes like custom textures or material
  10189. * to allow the laoders to instantiate them
  10190. */
  10191. Tools.RegisteredExternalClasses = {};
  10192. // Used in case of a texture loading problem
  10193. 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";
  10194. Tools._tmpFloatArray = new Float32Array(1);
  10195. Tools.PreprocessUrl = function (url) {
  10196. return url;
  10197. };
  10198. // Logs
  10199. Tools._NoneLogLevel = 0;
  10200. Tools._MessageLogLevel = 1;
  10201. Tools._WarningLogLevel = 2;
  10202. Tools._ErrorLogLevel = 4;
  10203. Tools._LogCache = "";
  10204. Tools.errorsCount = 0;
  10205. Tools.Log = Tools._LogEnabled;
  10206. Tools.Warn = Tools._WarnEnabled;
  10207. Tools.Error = Tools._ErrorEnabled;
  10208. // Performances
  10209. Tools._PerformanceNoneLogLevel = 0;
  10210. Tools._PerformanceUserMarkLogLevel = 1;
  10211. Tools._PerformanceConsoleLogLevel = 2;
  10212. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10213. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10214. return Tools;
  10215. }());
  10216. BABYLON.Tools = Tools;
  10217. /**
  10218. * This class is used to track a performance counter which is number based.
  10219. * The user has access to many properties which give statistics of different nature
  10220. *
  10221. * The implementer can track two kinds of Performance Counter: time and count
  10222. * 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.
  10223. * 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.
  10224. */
  10225. var PerfCounter = /** @class */ (function () {
  10226. function PerfCounter() {
  10227. this._startMonitoringTime = 0;
  10228. this._min = 0;
  10229. this._max = 0;
  10230. this._average = 0;
  10231. this._lastSecAverage = 0;
  10232. this._current = 0;
  10233. this._totalValueCount = 0;
  10234. this._totalAccumulated = 0;
  10235. this._lastSecAccumulated = 0;
  10236. this._lastSecTime = 0;
  10237. this._lastSecValueCount = 0;
  10238. }
  10239. Object.defineProperty(PerfCounter.prototype, "min", {
  10240. /**
  10241. * Returns the smallest value ever
  10242. */
  10243. get: function () {
  10244. return this._min;
  10245. },
  10246. enumerable: true,
  10247. configurable: true
  10248. });
  10249. Object.defineProperty(PerfCounter.prototype, "max", {
  10250. /**
  10251. * Returns the biggest value ever
  10252. */
  10253. get: function () {
  10254. return this._max;
  10255. },
  10256. enumerable: true,
  10257. configurable: true
  10258. });
  10259. Object.defineProperty(PerfCounter.prototype, "average", {
  10260. /**
  10261. * Returns the average value since the performance counter is running
  10262. */
  10263. get: function () {
  10264. return this._average;
  10265. },
  10266. enumerable: true,
  10267. configurable: true
  10268. });
  10269. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10270. /**
  10271. * Returns the average value of the last second the counter was monitored
  10272. */
  10273. get: function () {
  10274. return this._lastSecAverage;
  10275. },
  10276. enumerable: true,
  10277. configurable: true
  10278. });
  10279. Object.defineProperty(PerfCounter.prototype, "current", {
  10280. /**
  10281. * Returns the current value
  10282. */
  10283. get: function () {
  10284. return this._current;
  10285. },
  10286. enumerable: true,
  10287. configurable: true
  10288. });
  10289. Object.defineProperty(PerfCounter.prototype, "total", {
  10290. get: function () {
  10291. return this._totalAccumulated;
  10292. },
  10293. enumerable: true,
  10294. configurable: true
  10295. });
  10296. Object.defineProperty(PerfCounter.prototype, "count", {
  10297. get: function () {
  10298. return this._totalValueCount;
  10299. },
  10300. enumerable: true,
  10301. configurable: true
  10302. });
  10303. /**
  10304. * Call this method to start monitoring a new frame.
  10305. * 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.
  10306. */
  10307. PerfCounter.prototype.fetchNewFrame = function () {
  10308. this._totalValueCount++;
  10309. this._current = 0;
  10310. this._lastSecValueCount++;
  10311. };
  10312. /**
  10313. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10314. * @param newCount the count value to add to the monitored count
  10315. * @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.
  10316. */
  10317. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10318. if (!PerfCounter.Enabled) {
  10319. return;
  10320. }
  10321. this._current += newCount;
  10322. if (fetchResult) {
  10323. this._fetchResult();
  10324. }
  10325. };
  10326. /**
  10327. * Start monitoring this performance counter
  10328. */
  10329. PerfCounter.prototype.beginMonitoring = function () {
  10330. if (!PerfCounter.Enabled) {
  10331. return;
  10332. }
  10333. this._startMonitoringTime = Tools.Now;
  10334. };
  10335. /**
  10336. * Compute the time lapsed since the previous beginMonitoring() call.
  10337. * @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
  10338. */
  10339. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10340. if (newFrame === void 0) { newFrame = true; }
  10341. if (!PerfCounter.Enabled) {
  10342. return;
  10343. }
  10344. if (newFrame) {
  10345. this.fetchNewFrame();
  10346. }
  10347. var currentTime = Tools.Now;
  10348. this._current = currentTime - this._startMonitoringTime;
  10349. if (newFrame) {
  10350. this._fetchResult();
  10351. }
  10352. };
  10353. PerfCounter.prototype._fetchResult = function () {
  10354. this._totalAccumulated += this._current;
  10355. this._lastSecAccumulated += this._current;
  10356. // Min/Max update
  10357. this._min = Math.min(this._min, this._current);
  10358. this._max = Math.max(this._max, this._current);
  10359. this._average = this._totalAccumulated / this._totalValueCount;
  10360. // Reset last sec?
  10361. var now = Tools.Now;
  10362. if ((now - this._lastSecTime) > 1000) {
  10363. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10364. this._lastSecTime = now;
  10365. this._lastSecAccumulated = 0;
  10366. this._lastSecValueCount = 0;
  10367. }
  10368. };
  10369. PerfCounter.Enabled = true;
  10370. return PerfCounter;
  10371. }());
  10372. BABYLON.PerfCounter = PerfCounter;
  10373. /**
  10374. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10375. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10376. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10377. * @param name The name of the class, case should be preserved
  10378. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10379. */
  10380. function className(name, module) {
  10381. return function (target) {
  10382. target["__bjsclassName__"] = name;
  10383. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10384. };
  10385. }
  10386. BABYLON.className = className;
  10387. /**
  10388. * An implementation of a loop for asynchronous functions.
  10389. */
  10390. var AsyncLoop = /** @class */ (function () {
  10391. /**
  10392. * Constroctor.
  10393. * @param iterations the number of iterations.
  10394. * @param _fn the function to run each iteration
  10395. * @param _successCallback the callback that will be called upon succesful execution
  10396. * @param offset starting offset.
  10397. */
  10398. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10399. if (offset === void 0) { offset = 0; }
  10400. this.iterations = iterations;
  10401. this._fn = _fn;
  10402. this._successCallback = _successCallback;
  10403. this.index = offset - 1;
  10404. this._done = false;
  10405. }
  10406. /**
  10407. * Execute the next iteration. Must be called after the last iteration was finished.
  10408. */
  10409. AsyncLoop.prototype.executeNext = function () {
  10410. if (!this._done) {
  10411. if (this.index + 1 < this.iterations) {
  10412. ++this.index;
  10413. this._fn(this);
  10414. }
  10415. else {
  10416. this.breakLoop();
  10417. }
  10418. }
  10419. };
  10420. /**
  10421. * Break the loop and run the success callback.
  10422. */
  10423. AsyncLoop.prototype.breakLoop = function () {
  10424. this._done = true;
  10425. this._successCallback();
  10426. };
  10427. /**
  10428. * Helper function
  10429. */
  10430. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10431. if (offset === void 0) { offset = 0; }
  10432. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10433. loop.executeNext();
  10434. return loop;
  10435. };
  10436. /**
  10437. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10438. * @param iterations total number of iterations
  10439. * @param syncedIterations number of synchronous iterations in each async iteration.
  10440. * @param fn the function to call each iteration.
  10441. * @param callback a success call back that will be called when iterating stops.
  10442. * @param breakFunction a break condition (optional)
  10443. * @param timeout timeout settings for the setTimeout function. default - 0.
  10444. * @constructor
  10445. */
  10446. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10447. if (timeout === void 0) { timeout = 0; }
  10448. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10449. if (breakFunction && breakFunction())
  10450. loop.breakLoop();
  10451. else {
  10452. setTimeout(function () {
  10453. for (var i = 0; i < syncedIterations; ++i) {
  10454. var iteration = (loop.index * syncedIterations) + i;
  10455. if (iteration >= iterations)
  10456. break;
  10457. fn(iteration);
  10458. if (breakFunction && breakFunction()) {
  10459. loop.breakLoop();
  10460. break;
  10461. }
  10462. }
  10463. loop.executeNext();
  10464. }, timeout);
  10465. }
  10466. }, callback);
  10467. };
  10468. return AsyncLoop;
  10469. }());
  10470. BABYLON.AsyncLoop = AsyncLoop;
  10471. })(BABYLON || (BABYLON = {}));
  10472. //# sourceMappingURL=babylon.tools.js.map
  10473. var BABYLON;
  10474. (function (BABYLON) {
  10475. var PromiseStates;
  10476. (function (PromiseStates) {
  10477. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10478. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10479. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10480. })(PromiseStates || (PromiseStates = {}));
  10481. var FulFillmentAgregator = /** @class */ (function () {
  10482. function FulFillmentAgregator() {
  10483. this.count = 0;
  10484. this.target = 0;
  10485. this.results = [];
  10486. }
  10487. return FulFillmentAgregator;
  10488. }());
  10489. var InternalPromise = /** @class */ (function () {
  10490. function InternalPromise(resolver) {
  10491. var _this = this;
  10492. this._state = PromiseStates.Pending;
  10493. this._children = new Array();
  10494. this._rejectWasConsumed = false;
  10495. if (!resolver) {
  10496. return;
  10497. }
  10498. try {
  10499. resolver(function (value) {
  10500. _this._resolve(value);
  10501. }, function (reason) {
  10502. _this._reject(reason);
  10503. });
  10504. }
  10505. catch (e) {
  10506. this._reject(e);
  10507. }
  10508. }
  10509. Object.defineProperty(InternalPromise.prototype, "_result", {
  10510. get: function () {
  10511. return this._resultValue;
  10512. },
  10513. set: function (value) {
  10514. this._resultValue = value;
  10515. if (this._parent && this._parent._result === undefined) {
  10516. this._parent._result = value;
  10517. }
  10518. },
  10519. enumerable: true,
  10520. configurable: true
  10521. });
  10522. InternalPromise.prototype.catch = function (onRejected) {
  10523. return this.then(undefined, onRejected);
  10524. };
  10525. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10526. var _this = this;
  10527. var newPromise = new InternalPromise();
  10528. newPromise._onFulfilled = onFulfilled;
  10529. newPromise._onRejected = onRejected;
  10530. // Composition
  10531. this._children.push(newPromise);
  10532. newPromise._parent = this;
  10533. if (this._state !== PromiseStates.Pending) {
  10534. BABYLON.Tools.SetImmediate(function () {
  10535. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10536. var returnedValue = newPromise._resolve(_this._result);
  10537. if (returnedValue !== undefined && returnedValue !== null) {
  10538. if (returnedValue._state !== undefined) {
  10539. var returnedPromise = returnedValue;
  10540. newPromise._children.push(returnedPromise);
  10541. returnedPromise._parent = newPromise;
  10542. newPromise = returnedPromise;
  10543. }
  10544. else {
  10545. newPromise._result = returnedValue;
  10546. }
  10547. }
  10548. }
  10549. else {
  10550. newPromise._reject(_this._reason);
  10551. }
  10552. });
  10553. }
  10554. return newPromise;
  10555. };
  10556. InternalPromise.prototype._moveChildren = function (children) {
  10557. var _this = this;
  10558. var _a;
  10559. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10560. this._children.forEach(function (child) {
  10561. child._parent = _this;
  10562. });
  10563. if (this._state === PromiseStates.Fulfilled) {
  10564. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10565. var child = _b[_i];
  10566. child._resolve(this._result);
  10567. }
  10568. }
  10569. else if (this._state === PromiseStates.Rejected) {
  10570. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10571. var child = _d[_c];
  10572. child._reject(this._reason);
  10573. }
  10574. }
  10575. };
  10576. InternalPromise.prototype._resolve = function (value) {
  10577. try {
  10578. this._state = PromiseStates.Fulfilled;
  10579. var returnedValue = null;
  10580. if (this._onFulfilled) {
  10581. returnedValue = this._onFulfilled(value);
  10582. }
  10583. if (returnedValue !== undefined && returnedValue !== null) {
  10584. if (returnedValue._state !== undefined) {
  10585. // Transmit children
  10586. var returnedPromise = returnedValue;
  10587. returnedPromise._parent = this;
  10588. returnedPromise._moveChildren(this._children);
  10589. value = returnedPromise._result;
  10590. }
  10591. else {
  10592. value = returnedValue;
  10593. }
  10594. }
  10595. this._result = value;
  10596. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10597. var child = _a[_i];
  10598. child._resolve(value);
  10599. }
  10600. this._children.length = 0;
  10601. delete this._onFulfilled;
  10602. delete this._onRejected;
  10603. }
  10604. catch (e) {
  10605. this._reject(e, true);
  10606. }
  10607. };
  10608. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10609. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10610. this._state = PromiseStates.Rejected;
  10611. this._reason = reason;
  10612. if (this._onRejected && !onLocalThrow) {
  10613. try {
  10614. this._onRejected(reason);
  10615. this._rejectWasConsumed = true;
  10616. }
  10617. catch (e) {
  10618. reason = e;
  10619. }
  10620. }
  10621. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10622. var child = _a[_i];
  10623. if (this._rejectWasConsumed) {
  10624. child._resolve(null);
  10625. }
  10626. else {
  10627. child._reject(reason);
  10628. }
  10629. }
  10630. this._children.length = 0;
  10631. delete this._onFulfilled;
  10632. delete this._onRejected;
  10633. };
  10634. InternalPromise.resolve = function (value) {
  10635. var newPromise = new InternalPromise();
  10636. newPromise._resolve(value);
  10637. return newPromise;
  10638. };
  10639. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10640. promise.then(function (value) {
  10641. agregator.results[index] = value;
  10642. agregator.count++;
  10643. if (agregator.count === agregator.target) {
  10644. agregator.rootPromise._resolve(agregator.results);
  10645. }
  10646. return null;
  10647. }, function (reason) {
  10648. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10649. agregator.rootPromise._reject(reason);
  10650. }
  10651. });
  10652. };
  10653. InternalPromise.all = function (promises) {
  10654. var newPromise = new InternalPromise();
  10655. var agregator = new FulFillmentAgregator();
  10656. agregator.target = promises.length;
  10657. agregator.rootPromise = newPromise;
  10658. if (promises.length) {
  10659. for (var index = 0; index < promises.length; index++) {
  10660. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10661. }
  10662. }
  10663. else {
  10664. newPromise._resolve([]);
  10665. }
  10666. return newPromise;
  10667. };
  10668. InternalPromise.race = function (promises) {
  10669. var newPromise = new InternalPromise();
  10670. if (promises.length) {
  10671. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10672. var promise = promises_1[_i];
  10673. promise.then(function (value) {
  10674. if (newPromise) {
  10675. newPromise._resolve(value);
  10676. newPromise = null;
  10677. }
  10678. return null;
  10679. }, function (reason) {
  10680. if (newPromise) {
  10681. newPromise._reject(reason);
  10682. newPromise = null;
  10683. }
  10684. });
  10685. }
  10686. }
  10687. return newPromise;
  10688. };
  10689. return InternalPromise;
  10690. }());
  10691. /**
  10692. * Helper class that provides a small promise polyfill
  10693. */
  10694. var PromisePolyfill = /** @class */ (function () {
  10695. function PromisePolyfill() {
  10696. }
  10697. /**
  10698. * Static function used to check if the polyfill is required
  10699. * If this is the case then the function will inject the polyfill to window.Promise
  10700. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10701. */
  10702. PromisePolyfill.Apply = function (force) {
  10703. if (force === void 0) { force = false; }
  10704. if (force || typeof Promise === 'undefined') {
  10705. var root = window;
  10706. root.Promise = InternalPromise;
  10707. }
  10708. };
  10709. return PromisePolyfill;
  10710. }());
  10711. BABYLON.PromisePolyfill = PromisePolyfill;
  10712. })(BABYLON || (BABYLON = {}));
  10713. //# sourceMappingURL=babylon.promise.js.map
  10714. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10715. var BABYLON;
  10716. (function (BABYLON) {
  10717. /**
  10718. * Helper class to push actions to a pool of workers.
  10719. */
  10720. var WorkerPool = /** @class */ (function () {
  10721. /**
  10722. * Constructor
  10723. * @param workers Array of workers to use for actions
  10724. */
  10725. function WorkerPool(workers) {
  10726. this._pendingActions = new Array();
  10727. this._workerInfos = workers.map(function (worker) { return ({
  10728. worker: worker,
  10729. active: false
  10730. }); });
  10731. }
  10732. /**
  10733. * Terminates all workers and clears any pending actions.
  10734. */
  10735. WorkerPool.prototype.dispose = function () {
  10736. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10737. var workerInfo = _a[_i];
  10738. workerInfo.worker.terminate();
  10739. }
  10740. delete this._workerInfos;
  10741. delete this._pendingActions;
  10742. };
  10743. /**
  10744. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10745. * pended until a worker has completed its action.
  10746. * @param action The action to perform. Call onComplete when the action is complete.
  10747. */
  10748. WorkerPool.prototype.push = function (action) {
  10749. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10750. var workerInfo = _a[_i];
  10751. if (!workerInfo.active) {
  10752. this._execute(workerInfo, action);
  10753. return;
  10754. }
  10755. }
  10756. this._pendingActions.push(action);
  10757. };
  10758. WorkerPool.prototype._execute = function (workerInfo, action) {
  10759. var _this = this;
  10760. workerInfo.active = true;
  10761. action(workerInfo.worker, function () {
  10762. workerInfo.active = false;
  10763. var nextAction = _this._pendingActions.shift();
  10764. if (nextAction) {
  10765. _this._execute(workerInfo, nextAction);
  10766. }
  10767. });
  10768. };
  10769. return WorkerPool;
  10770. }());
  10771. BABYLON.WorkerPool = WorkerPool;
  10772. })(BABYLON || (BABYLON = {}));
  10773. //# sourceMappingURL=babylon.workerPool.js.map
  10774. var BABYLON;
  10775. (function (BABYLON) {
  10776. /**
  10777. * @hidden
  10778. **/
  10779. var _AlphaState = /** @class */ (function () {
  10780. /**
  10781. * Initializes the state.
  10782. */
  10783. function _AlphaState() {
  10784. this._isAlphaBlendDirty = false;
  10785. this._isBlendFunctionParametersDirty = false;
  10786. this._isBlendEquationParametersDirty = false;
  10787. this._isBlendConstantsDirty = false;
  10788. this._alphaBlend = false;
  10789. this._blendFunctionParameters = new Array(4);
  10790. this._blendEquationParameters = new Array(2);
  10791. this._blendConstants = new Array(4);
  10792. this.reset();
  10793. }
  10794. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10795. get: function () {
  10796. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10797. },
  10798. enumerable: true,
  10799. configurable: true
  10800. });
  10801. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10802. get: function () {
  10803. return this._alphaBlend;
  10804. },
  10805. set: function (value) {
  10806. if (this._alphaBlend === value) {
  10807. return;
  10808. }
  10809. this._alphaBlend = value;
  10810. this._isAlphaBlendDirty = true;
  10811. },
  10812. enumerable: true,
  10813. configurable: true
  10814. });
  10815. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10816. if (this._blendConstants[0] === r &&
  10817. this._blendConstants[1] === g &&
  10818. this._blendConstants[2] === b &&
  10819. this._blendConstants[3] === a) {
  10820. return;
  10821. }
  10822. this._blendConstants[0] = r;
  10823. this._blendConstants[1] = g;
  10824. this._blendConstants[2] = b;
  10825. this._blendConstants[3] = a;
  10826. this._isBlendConstantsDirty = true;
  10827. };
  10828. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10829. if (this._blendFunctionParameters[0] === value0 &&
  10830. this._blendFunctionParameters[1] === value1 &&
  10831. this._blendFunctionParameters[2] === value2 &&
  10832. this._blendFunctionParameters[3] === value3) {
  10833. return;
  10834. }
  10835. this._blendFunctionParameters[0] = value0;
  10836. this._blendFunctionParameters[1] = value1;
  10837. this._blendFunctionParameters[2] = value2;
  10838. this._blendFunctionParameters[3] = value3;
  10839. this._isBlendFunctionParametersDirty = true;
  10840. };
  10841. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10842. if (this._blendEquationParameters[0] === rgb &&
  10843. this._blendEquationParameters[1] === alpha) {
  10844. return;
  10845. }
  10846. this._blendEquationParameters[0] = rgb;
  10847. this._blendEquationParameters[1] = alpha;
  10848. this._isBlendEquationParametersDirty = true;
  10849. };
  10850. _AlphaState.prototype.reset = function () {
  10851. this._alphaBlend = false;
  10852. this._blendFunctionParameters[0] = null;
  10853. this._blendFunctionParameters[1] = null;
  10854. this._blendFunctionParameters[2] = null;
  10855. this._blendFunctionParameters[3] = null;
  10856. this._blendEquationParameters[0] = null;
  10857. this._blendEquationParameters[1] = null;
  10858. this._blendConstants[0] = null;
  10859. this._blendConstants[1] = null;
  10860. this._blendConstants[2] = null;
  10861. this._blendConstants[3] = null;
  10862. this._isAlphaBlendDirty = true;
  10863. this._isBlendFunctionParametersDirty = false;
  10864. this._isBlendEquationParametersDirty = false;
  10865. this._isBlendConstantsDirty = false;
  10866. };
  10867. _AlphaState.prototype.apply = function (gl) {
  10868. if (!this.isDirty) {
  10869. return;
  10870. }
  10871. // Alpha blend
  10872. if (this._isAlphaBlendDirty) {
  10873. if (this._alphaBlend) {
  10874. gl.enable(gl.BLEND);
  10875. }
  10876. else {
  10877. gl.disable(gl.BLEND);
  10878. }
  10879. this._isAlphaBlendDirty = false;
  10880. }
  10881. // Alpha function
  10882. if (this._isBlendFunctionParametersDirty) {
  10883. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10884. this._isBlendFunctionParametersDirty = false;
  10885. }
  10886. // Alpha equation
  10887. if (this._isBlendEquationParametersDirty) {
  10888. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10889. this._isBlendEquationParametersDirty = false;
  10890. }
  10891. // Constants
  10892. if (this._isBlendConstantsDirty) {
  10893. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10894. this._isBlendConstantsDirty = false;
  10895. }
  10896. };
  10897. return _AlphaState;
  10898. }());
  10899. BABYLON._AlphaState = _AlphaState;
  10900. })(BABYLON || (BABYLON = {}));
  10901. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10902. var BABYLON;
  10903. (function (BABYLON) {
  10904. /**
  10905. * @hidden
  10906. **/
  10907. var _DepthCullingState = /** @class */ (function () {
  10908. /**
  10909. * Initializes the state.
  10910. */
  10911. function _DepthCullingState() {
  10912. this._isDepthTestDirty = false;
  10913. this._isDepthMaskDirty = false;
  10914. this._isDepthFuncDirty = false;
  10915. this._isCullFaceDirty = false;
  10916. this._isCullDirty = false;
  10917. this._isZOffsetDirty = false;
  10918. this._isFrontFaceDirty = false;
  10919. this.reset();
  10920. }
  10921. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10922. get: function () {
  10923. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10929. get: function () {
  10930. return this._zOffset;
  10931. },
  10932. set: function (value) {
  10933. if (this._zOffset === value) {
  10934. return;
  10935. }
  10936. this._zOffset = value;
  10937. this._isZOffsetDirty = true;
  10938. },
  10939. enumerable: true,
  10940. configurable: true
  10941. });
  10942. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10943. get: function () {
  10944. return this._cullFace;
  10945. },
  10946. set: function (value) {
  10947. if (this._cullFace === value) {
  10948. return;
  10949. }
  10950. this._cullFace = value;
  10951. this._isCullFaceDirty = true;
  10952. },
  10953. enumerable: true,
  10954. configurable: true
  10955. });
  10956. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10957. get: function () {
  10958. return this._cull;
  10959. },
  10960. set: function (value) {
  10961. if (this._cull === value) {
  10962. return;
  10963. }
  10964. this._cull = value;
  10965. this._isCullDirty = true;
  10966. },
  10967. enumerable: true,
  10968. configurable: true
  10969. });
  10970. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10971. get: function () {
  10972. return this._depthFunc;
  10973. },
  10974. set: function (value) {
  10975. if (this._depthFunc === value) {
  10976. return;
  10977. }
  10978. this._depthFunc = value;
  10979. this._isDepthFuncDirty = true;
  10980. },
  10981. enumerable: true,
  10982. configurable: true
  10983. });
  10984. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10985. get: function () {
  10986. return this._depthMask;
  10987. },
  10988. set: function (value) {
  10989. if (this._depthMask === value) {
  10990. return;
  10991. }
  10992. this._depthMask = value;
  10993. this._isDepthMaskDirty = true;
  10994. },
  10995. enumerable: true,
  10996. configurable: true
  10997. });
  10998. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10999. get: function () {
  11000. return this._depthTest;
  11001. },
  11002. set: function (value) {
  11003. if (this._depthTest === value) {
  11004. return;
  11005. }
  11006. this._depthTest = value;
  11007. this._isDepthTestDirty = true;
  11008. },
  11009. enumerable: true,
  11010. configurable: true
  11011. });
  11012. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11013. get: function () {
  11014. return this._frontFace;
  11015. },
  11016. set: function (value) {
  11017. if (this._frontFace === value) {
  11018. return;
  11019. }
  11020. this._frontFace = value;
  11021. this._isFrontFaceDirty = true;
  11022. },
  11023. enumerable: true,
  11024. configurable: true
  11025. });
  11026. _DepthCullingState.prototype.reset = function () {
  11027. this._depthMask = true;
  11028. this._depthTest = true;
  11029. this._depthFunc = null;
  11030. this._cullFace = null;
  11031. this._cull = null;
  11032. this._zOffset = 0;
  11033. this._frontFace = null;
  11034. this._isDepthTestDirty = true;
  11035. this._isDepthMaskDirty = true;
  11036. this._isDepthFuncDirty = false;
  11037. this._isCullFaceDirty = false;
  11038. this._isCullDirty = false;
  11039. this._isZOffsetDirty = false;
  11040. this._isFrontFaceDirty = false;
  11041. };
  11042. _DepthCullingState.prototype.apply = function (gl) {
  11043. if (!this.isDirty) {
  11044. return;
  11045. }
  11046. // Cull
  11047. if (this._isCullDirty) {
  11048. if (this.cull) {
  11049. gl.enable(gl.CULL_FACE);
  11050. }
  11051. else {
  11052. gl.disable(gl.CULL_FACE);
  11053. }
  11054. this._isCullDirty = false;
  11055. }
  11056. // Cull face
  11057. if (this._isCullFaceDirty) {
  11058. gl.cullFace(this.cullFace);
  11059. this._isCullFaceDirty = false;
  11060. }
  11061. // Depth mask
  11062. if (this._isDepthMaskDirty) {
  11063. gl.depthMask(this.depthMask);
  11064. this._isDepthMaskDirty = false;
  11065. }
  11066. // Depth test
  11067. if (this._isDepthTestDirty) {
  11068. if (this.depthTest) {
  11069. gl.enable(gl.DEPTH_TEST);
  11070. }
  11071. else {
  11072. gl.disable(gl.DEPTH_TEST);
  11073. }
  11074. this._isDepthTestDirty = false;
  11075. }
  11076. // Depth func
  11077. if (this._isDepthFuncDirty) {
  11078. gl.depthFunc(this.depthFunc);
  11079. this._isDepthFuncDirty = false;
  11080. }
  11081. // zOffset
  11082. if (this._isZOffsetDirty) {
  11083. if (this.zOffset) {
  11084. gl.enable(gl.POLYGON_OFFSET_FILL);
  11085. gl.polygonOffset(this.zOffset, 0);
  11086. }
  11087. else {
  11088. gl.disable(gl.POLYGON_OFFSET_FILL);
  11089. }
  11090. this._isZOffsetDirty = false;
  11091. }
  11092. // Front face
  11093. if (this._isFrontFaceDirty) {
  11094. gl.frontFace(this.frontFace);
  11095. this._isFrontFaceDirty = false;
  11096. }
  11097. };
  11098. return _DepthCullingState;
  11099. }());
  11100. BABYLON._DepthCullingState = _DepthCullingState;
  11101. })(BABYLON || (BABYLON = {}));
  11102. //# sourceMappingURL=babylon.depthCullingState.js.map
  11103. var BABYLON;
  11104. (function (BABYLON) {
  11105. /**
  11106. * @hidden
  11107. **/
  11108. var _StencilState = /** @class */ (function () {
  11109. function _StencilState() {
  11110. this._isStencilTestDirty = false;
  11111. this._isStencilMaskDirty = false;
  11112. this._isStencilFuncDirty = false;
  11113. this._isStencilOpDirty = false;
  11114. this.reset();
  11115. }
  11116. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11117. get: function () {
  11118. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11119. },
  11120. enumerable: true,
  11121. configurable: true
  11122. });
  11123. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11124. get: function () {
  11125. return this._stencilFunc;
  11126. },
  11127. set: function (value) {
  11128. if (this._stencilFunc === value) {
  11129. return;
  11130. }
  11131. this._stencilFunc = value;
  11132. this._isStencilFuncDirty = true;
  11133. },
  11134. enumerable: true,
  11135. configurable: true
  11136. });
  11137. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11138. get: function () {
  11139. return this._stencilFuncRef;
  11140. },
  11141. set: function (value) {
  11142. if (this._stencilFuncRef === value) {
  11143. return;
  11144. }
  11145. this._stencilFuncRef = value;
  11146. this._isStencilFuncDirty = true;
  11147. },
  11148. enumerable: true,
  11149. configurable: true
  11150. });
  11151. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11152. get: function () {
  11153. return this._stencilFuncMask;
  11154. },
  11155. set: function (value) {
  11156. if (this._stencilFuncMask === value) {
  11157. return;
  11158. }
  11159. this._stencilFuncMask = value;
  11160. this._isStencilFuncDirty = true;
  11161. },
  11162. enumerable: true,
  11163. configurable: true
  11164. });
  11165. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11166. get: function () {
  11167. return this._stencilOpStencilFail;
  11168. },
  11169. set: function (value) {
  11170. if (this._stencilOpStencilFail === value) {
  11171. return;
  11172. }
  11173. this._stencilOpStencilFail = value;
  11174. this._isStencilOpDirty = true;
  11175. },
  11176. enumerable: true,
  11177. configurable: true
  11178. });
  11179. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11180. get: function () {
  11181. return this._stencilOpDepthFail;
  11182. },
  11183. set: function (value) {
  11184. if (this._stencilOpDepthFail === value) {
  11185. return;
  11186. }
  11187. this._stencilOpDepthFail = value;
  11188. this._isStencilOpDirty = true;
  11189. },
  11190. enumerable: true,
  11191. configurable: true
  11192. });
  11193. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11194. get: function () {
  11195. return this._stencilOpStencilDepthPass;
  11196. },
  11197. set: function (value) {
  11198. if (this._stencilOpStencilDepthPass === value) {
  11199. return;
  11200. }
  11201. this._stencilOpStencilDepthPass = value;
  11202. this._isStencilOpDirty = true;
  11203. },
  11204. enumerable: true,
  11205. configurable: true
  11206. });
  11207. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11208. get: function () {
  11209. return this._stencilMask;
  11210. },
  11211. set: function (value) {
  11212. if (this._stencilMask === value) {
  11213. return;
  11214. }
  11215. this._stencilMask = value;
  11216. this._isStencilMaskDirty = true;
  11217. },
  11218. enumerable: true,
  11219. configurable: true
  11220. });
  11221. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11222. get: function () {
  11223. return this._stencilTest;
  11224. },
  11225. set: function (value) {
  11226. if (this._stencilTest === value) {
  11227. return;
  11228. }
  11229. this._stencilTest = value;
  11230. this._isStencilTestDirty = true;
  11231. },
  11232. enumerable: true,
  11233. configurable: true
  11234. });
  11235. _StencilState.prototype.reset = function () {
  11236. this._stencilTest = false;
  11237. this._stencilMask = 0xFF;
  11238. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11239. this._stencilFuncRef = 1;
  11240. this._stencilFuncMask = 0xFF;
  11241. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11242. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11243. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11244. this._isStencilTestDirty = true;
  11245. this._isStencilMaskDirty = true;
  11246. this._isStencilFuncDirty = true;
  11247. this._isStencilOpDirty = true;
  11248. };
  11249. _StencilState.prototype.apply = function (gl) {
  11250. if (!this.isDirty) {
  11251. return;
  11252. }
  11253. // Stencil test
  11254. if (this._isStencilTestDirty) {
  11255. if (this.stencilTest) {
  11256. gl.enable(gl.STENCIL_TEST);
  11257. }
  11258. else {
  11259. gl.disable(gl.STENCIL_TEST);
  11260. }
  11261. this._isStencilTestDirty = false;
  11262. }
  11263. // Stencil mask
  11264. if (this._isStencilMaskDirty) {
  11265. gl.stencilMask(this.stencilMask);
  11266. this._isStencilMaskDirty = false;
  11267. }
  11268. // Stencil func
  11269. if (this._isStencilFuncDirty) {
  11270. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11271. this._isStencilFuncDirty = false;
  11272. }
  11273. // Stencil op
  11274. if (this._isStencilOpDirty) {
  11275. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11276. this._isStencilOpDirty = false;
  11277. }
  11278. };
  11279. return _StencilState;
  11280. }());
  11281. BABYLON._StencilState = _StencilState;
  11282. })(BABYLON || (BABYLON = {}));
  11283. //# sourceMappingURL=babylon.stencilState.js.map
  11284. var __assign = (this && this.__assign) || function () {
  11285. __assign = Object.assign || function(t) {
  11286. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11287. s = arguments[i];
  11288. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11289. t[p] = s[p];
  11290. }
  11291. return t;
  11292. };
  11293. return __assign.apply(this, arguments);
  11294. };
  11295. var BABYLON;
  11296. (function (BABYLON) {
  11297. /**
  11298. * Keeps track of all the buffer info used in engine.
  11299. */
  11300. var BufferPointer = /** @class */ (function () {
  11301. function BufferPointer() {
  11302. }
  11303. return BufferPointer;
  11304. }());
  11305. /**
  11306. * Interface for attribute information associated with buffer instanciation
  11307. */
  11308. var InstancingAttributeInfo = /** @class */ (function () {
  11309. function InstancingAttributeInfo() {
  11310. }
  11311. return InstancingAttributeInfo;
  11312. }());
  11313. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11314. /**
  11315. * Define options used to create a render target texture
  11316. */
  11317. var RenderTargetCreationOptions = /** @class */ (function () {
  11318. function RenderTargetCreationOptions() {
  11319. }
  11320. return RenderTargetCreationOptions;
  11321. }());
  11322. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11323. /**
  11324. * Define options used to create a depth texture
  11325. */
  11326. var DepthTextureCreationOptions = /** @class */ (function () {
  11327. function DepthTextureCreationOptions() {
  11328. }
  11329. return DepthTextureCreationOptions;
  11330. }());
  11331. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11332. /**
  11333. * Class used to describe the capabilities of the engine relatively to the current browser
  11334. */
  11335. var EngineCapabilities = /** @class */ (function () {
  11336. function EngineCapabilities() {
  11337. }
  11338. return EngineCapabilities;
  11339. }());
  11340. BABYLON.EngineCapabilities = EngineCapabilities;
  11341. /**
  11342. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11343. */
  11344. var Engine = /** @class */ (function () {
  11345. /**
  11346. * Creates a new engine
  11347. * @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
  11348. * @param antialias defines enable antialiasing (default: false)
  11349. * @param options defines further options to be sent to the getContext() function
  11350. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11351. */
  11352. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11353. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11354. var _this = this;
  11355. // Public members
  11356. /**
  11357. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11358. */
  11359. this.forcePOTTextures = false;
  11360. /**
  11361. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11362. */
  11363. this.isFullscreen = false;
  11364. /**
  11365. * Gets a boolean indicating if the pointer is currently locked
  11366. */
  11367. this.isPointerLock = false;
  11368. /**
  11369. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11370. */
  11371. this.cullBackFaces = true;
  11372. /**
  11373. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11374. */
  11375. this.renderEvenInBackground = true;
  11376. /**
  11377. * Gets or sets a boolean indicating that cache can be kept between frames
  11378. */
  11379. this.preventCacheWipeBetweenFrames = false;
  11380. /**
  11381. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11382. **/
  11383. this.enableOfflineSupport = false;
  11384. /**
  11385. * 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)
  11386. **/
  11387. this.disableManifestCheck = false;
  11388. /**
  11389. * Gets the list of created scenes
  11390. */
  11391. this.scenes = new Array();
  11392. /**
  11393. * Gets the list of created postprocesses
  11394. */
  11395. this.postProcesses = new Array();
  11396. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11397. this.validateShaderPrograms = false;
  11398. // Observables
  11399. /**
  11400. * Observable event triggered each time the rendering canvas is resized
  11401. */
  11402. this.onResizeObservable = new BABYLON.Observable();
  11403. /**
  11404. * Observable event triggered each time the canvas loses focus
  11405. */
  11406. this.onCanvasBlurObservable = new BABYLON.Observable();
  11407. /**
  11408. * Observable event triggered each time the canvas gains focus
  11409. */
  11410. this.onCanvasFocusObservable = new BABYLON.Observable();
  11411. /**
  11412. * Observable event triggered each time the canvas receives pointerout event
  11413. */
  11414. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11415. /**
  11416. * Observable event triggered before each texture is initialized
  11417. */
  11418. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11419. //WebVR
  11420. this._vrDisplay = undefined;
  11421. this._vrSupported = false;
  11422. this._vrExclusivePointerMode = false;
  11423. // Uniform buffers list
  11424. /**
  11425. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11426. */
  11427. this.disableUniformBuffers = false;
  11428. /** @hidden */
  11429. this._uniformBuffers = new Array();
  11430. // Observables
  11431. /**
  11432. * Observable raised when the engine begins a new frame
  11433. */
  11434. this.onBeginFrameObservable = new BABYLON.Observable();
  11435. /**
  11436. * Observable raised when the engine ends the current frame
  11437. */
  11438. this.onEndFrameObservable = new BABYLON.Observable();
  11439. /**
  11440. * Observable raised when the engine is about to compile a shader
  11441. */
  11442. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11443. /**
  11444. * Observable raised when the engine has jsut compiled a shader
  11445. */
  11446. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11447. this._windowIsBackground = false;
  11448. this._webGLVersion = 1.0;
  11449. /** @hidden */
  11450. this._badOS = false;
  11451. /** @hidden */
  11452. this._badDesktopOS = false;
  11453. /**
  11454. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11455. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11456. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11457. */
  11458. this.disableTextureBindingOptimization = false;
  11459. /**
  11460. * Observable signaled when VR display mode changes
  11461. */
  11462. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11463. /**
  11464. * Observable signaled when VR request present is complete
  11465. */
  11466. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11467. /**
  11468. * Observable signaled when VR request present starts
  11469. */
  11470. this.onVRRequestPresentStart = new BABYLON.Observable();
  11471. this._colorWrite = true;
  11472. /** @hidden */
  11473. this._drawCalls = new BABYLON.PerfCounter();
  11474. /** @hidden */
  11475. this._textureCollisions = new BABYLON.PerfCounter();
  11476. this._renderingQueueLaunched = false;
  11477. this._activeRenderLoops = new Array();
  11478. // Deterministic lockstepMaxSteps
  11479. this._deterministicLockstep = false;
  11480. this._lockstepMaxSteps = 4;
  11481. // Lost context
  11482. /**
  11483. * Observable signaled when a context lost event is raised
  11484. */
  11485. this.onContextLostObservable = new BABYLON.Observable();
  11486. /**
  11487. * Observable signaled when a context restored event is raised
  11488. */
  11489. this.onContextRestoredObservable = new BABYLON.Observable();
  11490. this._contextWasLost = false;
  11491. this._doNotHandleContextLost = false;
  11492. // FPS
  11493. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11494. this._fps = 60;
  11495. this._deltaTime = 0;
  11496. /**
  11497. * Turn this value on if you want to pause FPS computation when in background
  11498. */
  11499. this.disablePerformanceMonitorInBackground = false;
  11500. // States
  11501. /** @hidden */
  11502. this._depthCullingState = new BABYLON._DepthCullingState();
  11503. /** @hidden */
  11504. this._stencilState = new BABYLON._StencilState();
  11505. /** @hidden */
  11506. this._alphaState = new BABYLON._AlphaState();
  11507. /** @hidden */
  11508. this._alphaMode = Engine.ALPHA_DISABLE;
  11509. // Cache
  11510. this._internalTexturesCache = new Array();
  11511. /** @hidden */
  11512. this._activeChannel = 0;
  11513. this._currentTextureChannel = -1;
  11514. /** @hidden */
  11515. this._boundTexturesCache = {};
  11516. this._compiledEffects = {};
  11517. this._vertexAttribArraysEnabled = [];
  11518. this._uintIndicesCurrentlySet = false;
  11519. this._currentBoundBuffer = new Array();
  11520. /** @hidden */
  11521. this._currentFramebuffer = null;
  11522. this._currentBufferPointers = new Array();
  11523. this._currentInstanceLocations = new Array();
  11524. this._currentInstanceBuffers = new Array();
  11525. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11526. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11527. this._vaoRecordInProgress = false;
  11528. this._mustWipeVertexAttributes = false;
  11529. this._nextFreeTextureSlots = new Array();
  11530. this._maxSimultaneousTextures = 0;
  11531. this._activeRequests = new Array();
  11532. // Hardware supported Compressed Textures
  11533. this._texturesSupported = new Array();
  11534. /**
  11535. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11536. */
  11537. this.premultipliedAlpha = true;
  11538. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11539. this._onVRFullScreenTriggered = function () {
  11540. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11541. //get the old size before we change
  11542. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11543. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11544. //get the width and height, change the render size
  11545. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11546. _this.setHardwareScalingLevel(1);
  11547. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11548. }
  11549. else {
  11550. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11551. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11552. }
  11553. };
  11554. this._unpackFlipYCached = null;
  11555. /**
  11556. * In case you are sharing the context with other applications, it might
  11557. * be interested to not cache the unpack flip y state to ensure a consistent
  11558. * value would be set.
  11559. */
  11560. this.enableUnpackFlipYCached = true;
  11561. this._boundUniforms = {};
  11562. // Register promises
  11563. BABYLON.PromisePolyfill.Apply();
  11564. var canvas = null;
  11565. Engine.Instances.push(this);
  11566. if (!canvasOrContext) {
  11567. return;
  11568. }
  11569. options = options || {};
  11570. if (canvasOrContext.getContext) {
  11571. canvas = canvasOrContext;
  11572. this._renderingCanvas = canvas;
  11573. if (antialias != null) {
  11574. options.antialias = antialias;
  11575. }
  11576. if (options.deterministicLockstep === undefined) {
  11577. options.deterministicLockstep = false;
  11578. }
  11579. if (options.lockstepMaxSteps === undefined) {
  11580. options.lockstepMaxSteps = 4;
  11581. }
  11582. if (options.preserveDrawingBuffer === undefined) {
  11583. options.preserveDrawingBuffer = false;
  11584. }
  11585. if (options.audioEngine === undefined) {
  11586. options.audioEngine = true;
  11587. }
  11588. if (options.stencil === undefined) {
  11589. options.stencil = true;
  11590. }
  11591. if (options.premultipliedAlpha === false) {
  11592. this.premultipliedAlpha = false;
  11593. }
  11594. this._deterministicLockstep = options.deterministicLockstep;
  11595. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11596. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11597. // Exceptions
  11598. if (navigator && navigator.userAgent) {
  11599. var ua = navigator.userAgent;
  11600. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11601. var exception = _a[_i];
  11602. var key = exception.key;
  11603. var targets = exception.targets;
  11604. if (ua.indexOf(key) > -1) {
  11605. if (exception.capture && exception.captureConstraint) {
  11606. var capture = exception.capture;
  11607. var constraint = exception.captureConstraint;
  11608. var regex = new RegExp(capture);
  11609. var matches = regex.exec(ua);
  11610. if (matches && matches.length > 0) {
  11611. var capturedValue = parseInt(matches[matches.length - 1]);
  11612. if (capturedValue >= constraint) {
  11613. continue;
  11614. }
  11615. }
  11616. }
  11617. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11618. var target = targets_1[_b];
  11619. switch (target) {
  11620. case "uniformBuffer":
  11621. this.disableUniformBuffers = true;
  11622. break;
  11623. case "textureBindingOptimization":
  11624. this.disableTextureBindingOptimization = true;
  11625. break;
  11626. }
  11627. }
  11628. }
  11629. }
  11630. }
  11631. // GL
  11632. if (!options.disableWebGL2Support) {
  11633. try {
  11634. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11635. if (this._gl) {
  11636. this._webGLVersion = 2.0;
  11637. }
  11638. }
  11639. catch (e) {
  11640. // Do nothing
  11641. }
  11642. }
  11643. if (!this._gl) {
  11644. if (!canvas) {
  11645. throw new Error("The provided canvas is null or undefined.");
  11646. }
  11647. try {
  11648. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11649. }
  11650. catch (e) {
  11651. throw new Error("WebGL not supported");
  11652. }
  11653. }
  11654. if (!this._gl) {
  11655. throw new Error("WebGL not supported");
  11656. }
  11657. this._onCanvasFocus = function () {
  11658. _this.onCanvasFocusObservable.notifyObservers(_this);
  11659. };
  11660. this._onCanvasBlur = function () {
  11661. _this.onCanvasBlurObservable.notifyObservers(_this);
  11662. };
  11663. canvas.addEventListener("focus", this._onCanvasFocus);
  11664. canvas.addEventListener("blur", this._onCanvasBlur);
  11665. this._onBlur = function () {
  11666. if (_this.disablePerformanceMonitorInBackground) {
  11667. _this._performanceMonitor.disable();
  11668. }
  11669. _this._windowIsBackground = true;
  11670. };
  11671. this._onFocus = function () {
  11672. if (_this.disablePerformanceMonitorInBackground) {
  11673. _this._performanceMonitor.enable();
  11674. }
  11675. _this._windowIsBackground = false;
  11676. };
  11677. this._onCanvasPointerOut = function (ev) {
  11678. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11679. };
  11680. window.addEventListener("blur", this._onBlur);
  11681. window.addEventListener("focus", this._onFocus);
  11682. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11683. // Context lost
  11684. if (!this._doNotHandleContextLost) {
  11685. this._onContextLost = function (evt) {
  11686. evt.preventDefault();
  11687. _this._contextWasLost = true;
  11688. BABYLON.Tools.Warn("WebGL context lost.");
  11689. _this.onContextLostObservable.notifyObservers(_this);
  11690. };
  11691. this._onContextRestored = function (evt) {
  11692. // Adding a timeout to avoid race condition at browser level
  11693. setTimeout(function () {
  11694. // Rebuild gl context
  11695. _this._initGLContext();
  11696. // Rebuild effects
  11697. _this._rebuildEffects();
  11698. // Rebuild textures
  11699. _this._rebuildInternalTextures();
  11700. // Rebuild buffers
  11701. _this._rebuildBuffers();
  11702. // Cache
  11703. _this.wipeCaches(true);
  11704. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11705. _this.onContextRestoredObservable.notifyObservers(_this);
  11706. _this._contextWasLost = false;
  11707. }, 0);
  11708. };
  11709. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11710. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11711. }
  11712. }
  11713. else {
  11714. this._gl = canvasOrContext;
  11715. this._renderingCanvas = this._gl.canvas;
  11716. if (this._gl.renderbufferStorageMultisample) {
  11717. this._webGLVersion = 2.0;
  11718. }
  11719. options.stencil = this._gl.getContextAttributes().stencil;
  11720. }
  11721. // Viewport
  11722. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11723. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11724. this.resize();
  11725. this._isStencilEnable = options.stencil ? true : false;
  11726. this._initGLContext();
  11727. if (canvas) {
  11728. // Fullscreen
  11729. this._onFullscreenChange = function () {
  11730. if (document.fullscreen !== undefined) {
  11731. _this.isFullscreen = document.fullscreen;
  11732. }
  11733. else if (document.mozFullScreen !== undefined) {
  11734. _this.isFullscreen = document.mozFullScreen;
  11735. }
  11736. else if (document.webkitIsFullScreen !== undefined) {
  11737. _this.isFullscreen = document.webkitIsFullScreen;
  11738. }
  11739. else if (document.msIsFullScreen !== undefined) {
  11740. _this.isFullscreen = document.msIsFullScreen;
  11741. }
  11742. // Pointer lock
  11743. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11744. canvas.requestPointerLock = canvas.requestPointerLock ||
  11745. canvas.msRequestPointerLock ||
  11746. canvas.mozRequestPointerLock ||
  11747. canvas.webkitRequestPointerLock;
  11748. if (canvas.requestPointerLock) {
  11749. canvas.requestPointerLock();
  11750. }
  11751. }
  11752. };
  11753. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11754. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11755. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11756. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11757. // Pointer lock
  11758. this._onPointerLockChange = function () {
  11759. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11760. document.webkitPointerLockElement === canvas ||
  11761. document.msPointerLockElement === canvas ||
  11762. document.pointerLockElement === canvas);
  11763. };
  11764. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11765. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11766. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11767. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11768. this._onVRDisplayPointerRestricted = function () {
  11769. if (canvas) {
  11770. canvas.requestPointerLock();
  11771. }
  11772. };
  11773. this._onVRDisplayPointerUnrestricted = function () {
  11774. document.exitPointerLock();
  11775. };
  11776. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11777. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11778. }
  11779. // Create Audio Engine if needed.
  11780. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  11781. Engine.audioEngine = Engine.AudioEngineFactory();
  11782. }
  11783. // Prepare buffer pointers
  11784. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11785. this._currentBufferPointers[i] = new BufferPointer();
  11786. }
  11787. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11788. // Load WebVR Devices
  11789. if (options.autoEnableWebVR) {
  11790. this.initWebVR();
  11791. }
  11792. // Detect if we are running on a faulty buggy OS.
  11793. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11794. // Detect if we are running on a faulty buggy desktop OS.
  11795. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11796. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11797. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11798. }
  11799. Object.defineProperty(Engine, "LastCreatedEngine", {
  11800. /**
  11801. * Gets the latest created engine
  11802. */
  11803. get: function () {
  11804. if (Engine.Instances.length === 0) {
  11805. return null;
  11806. }
  11807. return Engine.Instances[Engine.Instances.length - 1];
  11808. },
  11809. enumerable: true,
  11810. configurable: true
  11811. });
  11812. Object.defineProperty(Engine, "LastCreatedScene", {
  11813. /**
  11814. * Gets the latest created scene
  11815. */
  11816. get: function () {
  11817. var lastCreatedEngine = Engine.LastCreatedEngine;
  11818. if (!lastCreatedEngine) {
  11819. return null;
  11820. }
  11821. if (lastCreatedEngine.scenes.length === 0) {
  11822. return null;
  11823. }
  11824. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11825. },
  11826. enumerable: true,
  11827. configurable: true
  11828. });
  11829. /**
  11830. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11831. * @param flag defines which part of the materials must be marked as dirty
  11832. * @param predicate defines a predicate used to filter which materials should be affected
  11833. */
  11834. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11835. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11836. var engine = Engine.Instances[engineIndex];
  11837. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11838. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11839. }
  11840. }
  11841. };
  11842. Object.defineProperty(Engine, "Version", {
  11843. /**
  11844. * Returns the current version of the framework
  11845. */
  11846. get: function () {
  11847. return "3.3.0-beta.5";
  11848. },
  11849. enumerable: true,
  11850. configurable: true
  11851. });
  11852. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11853. /**
  11854. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11855. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11856. */
  11857. get: function () {
  11858. return this._vrExclusivePointerMode;
  11859. },
  11860. enumerable: true,
  11861. configurable: true
  11862. });
  11863. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11864. /**
  11865. * Gets a boolean indicating that the engine supports uniform buffers
  11866. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11867. */
  11868. get: function () {
  11869. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11875. /**
  11876. * Gets a boolean indicating that only power of 2 textures are supported
  11877. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11878. */
  11879. get: function () {
  11880. return this._webGLVersion < 2 || this.forcePOTTextures;
  11881. },
  11882. enumerable: true,
  11883. configurable: true
  11884. });
  11885. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11886. /**
  11887. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11888. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11889. */
  11890. get: function () {
  11891. return this._doNotHandleContextLost;
  11892. },
  11893. set: function (value) {
  11894. this._doNotHandleContextLost = value;
  11895. },
  11896. enumerable: true,
  11897. configurable: true
  11898. });
  11899. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11900. /**
  11901. * Gets the performance monitor attached to this engine
  11902. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11903. */
  11904. get: function () {
  11905. return this._performanceMonitor;
  11906. },
  11907. enumerable: true,
  11908. configurable: true
  11909. });
  11910. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11911. /**
  11912. * Gets the list of texture formats supported
  11913. */
  11914. get: function () {
  11915. return this._texturesSupported;
  11916. },
  11917. enumerable: true,
  11918. configurable: true
  11919. });
  11920. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11921. /**
  11922. * Gets the list of texture formats in use
  11923. */
  11924. get: function () {
  11925. return this._textureFormatInUse;
  11926. },
  11927. enumerable: true,
  11928. configurable: true
  11929. });
  11930. Object.defineProperty(Engine.prototype, "currentViewport", {
  11931. /**
  11932. * Gets the current viewport
  11933. */
  11934. get: function () {
  11935. return this._cachedViewport;
  11936. },
  11937. enumerable: true,
  11938. configurable: true
  11939. });
  11940. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11941. /**
  11942. * Gets the default empty texture
  11943. */
  11944. get: function () {
  11945. if (!this._emptyTexture) {
  11946. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11947. }
  11948. return this._emptyTexture;
  11949. },
  11950. enumerable: true,
  11951. configurable: true
  11952. });
  11953. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11954. /**
  11955. * Gets the default empty 3D texture
  11956. */
  11957. get: function () {
  11958. if (!this._emptyTexture3D) {
  11959. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11960. }
  11961. return this._emptyTexture3D;
  11962. },
  11963. enumerable: true,
  11964. configurable: true
  11965. });
  11966. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11967. /**
  11968. * Gets the default empty cube texture
  11969. */
  11970. get: function () {
  11971. if (!this._emptyCubeTexture) {
  11972. var faceData = new Uint8Array(4);
  11973. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11974. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11975. }
  11976. return this._emptyCubeTexture;
  11977. },
  11978. enumerable: true,
  11979. configurable: true
  11980. });
  11981. Engine.prototype._rebuildInternalTextures = function () {
  11982. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11983. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11984. var internalTexture = currentState_1[_i];
  11985. internalTexture._rebuild();
  11986. }
  11987. };
  11988. Engine.prototype._rebuildEffects = function () {
  11989. for (var key in this._compiledEffects) {
  11990. var effect = this._compiledEffects[key];
  11991. effect._prepareEffect();
  11992. }
  11993. BABYLON.Effect.ResetCache();
  11994. };
  11995. Engine.prototype._rebuildBuffers = function () {
  11996. // Index / Vertex
  11997. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11998. var scene = _a[_i];
  11999. scene.resetCachedMaterial();
  12000. scene._rebuildGeometries();
  12001. scene._rebuildTextures();
  12002. }
  12003. // Uniforms
  12004. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12005. var uniformBuffer = _c[_b];
  12006. uniformBuffer._rebuild();
  12007. }
  12008. };
  12009. Engine.prototype._initGLContext = function () {
  12010. // Caps
  12011. this._caps = new EngineCapabilities();
  12012. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12013. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12014. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12015. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12016. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12017. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12018. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12019. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12020. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12021. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12022. // Infos
  12023. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12024. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12025. if (rendererInfo != null) {
  12026. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12027. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12028. }
  12029. if (!this._glVendor) {
  12030. this._glVendor = "Unknown vendor";
  12031. }
  12032. if (!this._glRenderer) {
  12033. this._glRenderer = "Unknown renderer";
  12034. }
  12035. // Constants
  12036. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12037. if (this._gl.RGBA16F !== 0x881A) {
  12038. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12039. }
  12040. if (this._gl.RGBA32F !== 0x8814) {
  12041. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12042. }
  12043. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12044. this._gl.DEPTH24_STENCIL8 = 35056;
  12045. }
  12046. // Extensions
  12047. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12048. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12049. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12050. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12051. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12052. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12053. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12054. 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');
  12055. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12056. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12057. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12058. this._caps.highPrecisionShaderSupported = true;
  12059. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12060. if (this._caps.timerQuery) {
  12061. if (this._webGLVersion === 1) {
  12062. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12063. }
  12064. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12065. }
  12066. // Checks if some of the format renders first to allow the use of webgl inspector.
  12067. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12068. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12069. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12070. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12071. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12072. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12073. if (this._webGLVersion > 1) {
  12074. this._gl.HALF_FLOAT_OES = 0x140B;
  12075. }
  12076. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12077. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12078. // Draw buffers
  12079. if (this._webGLVersion > 1) {
  12080. this._caps.drawBuffersExtension = true;
  12081. }
  12082. else {
  12083. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12084. if (drawBuffersExtension !== null) {
  12085. this._caps.drawBuffersExtension = true;
  12086. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12087. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12088. for (var i = 0; i < 16; i++) {
  12089. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12090. }
  12091. }
  12092. else {
  12093. this._caps.drawBuffersExtension = false;
  12094. }
  12095. }
  12096. // Depth Texture
  12097. if (this._webGLVersion > 1) {
  12098. this._caps.depthTextureExtension = true;
  12099. }
  12100. else {
  12101. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12102. if (depthTextureExtension != null) {
  12103. this._caps.depthTextureExtension = true;
  12104. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12105. }
  12106. }
  12107. // Vertex array object
  12108. if (this._webGLVersion > 1) {
  12109. this._caps.vertexArrayObject = true;
  12110. }
  12111. else {
  12112. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12113. if (vertexArrayObjectExtension != null) {
  12114. this._caps.vertexArrayObject = true;
  12115. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12116. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12117. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12118. }
  12119. else {
  12120. this._caps.vertexArrayObject = false;
  12121. }
  12122. }
  12123. // Instances count
  12124. if (this._webGLVersion > 1) {
  12125. this._caps.instancedArrays = true;
  12126. }
  12127. else {
  12128. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12129. if (instanceExtension != null) {
  12130. this._caps.instancedArrays = true;
  12131. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12132. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12133. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12134. }
  12135. else {
  12136. this._caps.instancedArrays = false;
  12137. }
  12138. }
  12139. // Intelligently add supported compressed formats in order to check for.
  12140. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12141. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12142. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12143. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12144. if (this._caps.astc)
  12145. this.texturesSupported.push('-astc.ktx');
  12146. if (this._caps.s3tc)
  12147. this.texturesSupported.push('-dxt.ktx');
  12148. if (this._caps.pvrtc)
  12149. this.texturesSupported.push('-pvrtc.ktx');
  12150. if (this._caps.etc2)
  12151. this.texturesSupported.push('-etc2.ktx');
  12152. if (this._caps.etc1)
  12153. this.texturesSupported.push('-etc1.ktx');
  12154. if (this._gl.getShaderPrecisionFormat) {
  12155. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12156. if (highp) {
  12157. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12158. }
  12159. }
  12160. // Depth buffer
  12161. this.setDepthBuffer(true);
  12162. this.setDepthFunctionToLessOrEqual();
  12163. this.setDepthWrite(true);
  12164. // Texture maps
  12165. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12166. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12167. this._nextFreeTextureSlots.push(slot);
  12168. }
  12169. };
  12170. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12171. /**
  12172. * Gets version of the current webGL context
  12173. */
  12174. get: function () {
  12175. return this._webGLVersion;
  12176. },
  12177. enumerable: true,
  12178. configurable: true
  12179. });
  12180. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12181. /**
  12182. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12183. */
  12184. get: function () {
  12185. return this._isStencilEnable;
  12186. },
  12187. enumerable: true,
  12188. configurable: true
  12189. });
  12190. Engine.prototype._prepareWorkingCanvas = function () {
  12191. if (this._workingCanvas) {
  12192. return;
  12193. }
  12194. this._workingCanvas = document.createElement("canvas");
  12195. var context = this._workingCanvas.getContext("2d");
  12196. if (context) {
  12197. this._workingContext = context;
  12198. }
  12199. };
  12200. /**
  12201. * Reset the texture cache to empty state
  12202. */
  12203. Engine.prototype.resetTextureCache = function () {
  12204. for (var key in this._boundTexturesCache) {
  12205. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12206. continue;
  12207. }
  12208. var boundTexture = this._boundTexturesCache[key];
  12209. if (boundTexture) {
  12210. this._removeDesignatedSlot(boundTexture);
  12211. }
  12212. this._boundTexturesCache[key] = null;
  12213. }
  12214. if (!this.disableTextureBindingOptimization) {
  12215. this._nextFreeTextureSlots = [];
  12216. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12217. this._nextFreeTextureSlots.push(slot);
  12218. }
  12219. }
  12220. this._currentTextureChannel = -1;
  12221. };
  12222. /**
  12223. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12224. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12225. * @returns true if engine is in deterministic lock step mode
  12226. */
  12227. Engine.prototype.isDeterministicLockStep = function () {
  12228. return this._deterministicLockstep;
  12229. };
  12230. /**
  12231. * Gets the max steps when engine is running in deterministic lock step
  12232. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12233. * @returns the max steps
  12234. */
  12235. Engine.prototype.getLockstepMaxSteps = function () {
  12236. return this._lockstepMaxSteps;
  12237. };
  12238. /**
  12239. * Gets an object containing information about the current webGL context
  12240. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12241. */
  12242. Engine.prototype.getGlInfo = function () {
  12243. return {
  12244. vendor: this._glVendor,
  12245. renderer: this._glRenderer,
  12246. version: this._glVersion
  12247. };
  12248. };
  12249. /**
  12250. * Gets current aspect ratio
  12251. * @param camera defines the camera to use to get the aspect ratio
  12252. * @param useScreen defines if screen size must be used (or the current render target if any)
  12253. * @returns a number defining the aspect ratio
  12254. */
  12255. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12256. if (useScreen === void 0) { useScreen = false; }
  12257. var viewport = camera.viewport;
  12258. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12259. };
  12260. /**
  12261. * Gets current screen aspect ratio
  12262. * @returns a number defining the aspect ratio
  12263. */
  12264. Engine.prototype.getScreenAspectRatio = function () {
  12265. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12266. };
  12267. /**
  12268. * Gets the current render width
  12269. * @param useScreen defines if screen size must be used (or the current render target if any)
  12270. * @returns a number defining the current render width
  12271. */
  12272. Engine.prototype.getRenderWidth = function (useScreen) {
  12273. if (useScreen === void 0) { useScreen = false; }
  12274. if (!useScreen && this._currentRenderTarget) {
  12275. return this._currentRenderTarget.width;
  12276. }
  12277. return this._gl.drawingBufferWidth;
  12278. };
  12279. /**
  12280. * Gets the current render height
  12281. * @param useScreen defines if screen size must be used (or the current render target if any)
  12282. * @returns a number defining the current render height
  12283. */
  12284. Engine.prototype.getRenderHeight = function (useScreen) {
  12285. if (useScreen === void 0) { useScreen = false; }
  12286. if (!useScreen && this._currentRenderTarget) {
  12287. return this._currentRenderTarget.height;
  12288. }
  12289. return this._gl.drawingBufferHeight;
  12290. };
  12291. /**
  12292. * Gets the HTML canvas attached with the current webGL context
  12293. * @returns a HTML canvas
  12294. */
  12295. Engine.prototype.getRenderingCanvas = function () {
  12296. return this._renderingCanvas;
  12297. };
  12298. /**
  12299. * Gets the client rect of the HTML canvas attached with the current webGL context
  12300. * @returns a client rectanglee
  12301. */
  12302. Engine.prototype.getRenderingCanvasClientRect = function () {
  12303. if (!this._renderingCanvas) {
  12304. return null;
  12305. }
  12306. return this._renderingCanvas.getBoundingClientRect();
  12307. };
  12308. /**
  12309. * Defines the hardware scaling level.
  12310. * By default the hardware scaling level is computed from the window device ratio.
  12311. * 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.
  12312. * @param level defines the level to use
  12313. */
  12314. Engine.prototype.setHardwareScalingLevel = function (level) {
  12315. this._hardwareScalingLevel = level;
  12316. this.resize();
  12317. };
  12318. /**
  12319. * Gets the current hardware scaling level.
  12320. * By default the hardware scaling level is computed from the window device ratio.
  12321. * 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.
  12322. * @returns a number indicating the current hardware scaling level
  12323. */
  12324. Engine.prototype.getHardwareScalingLevel = function () {
  12325. return this._hardwareScalingLevel;
  12326. };
  12327. /**
  12328. * Gets the list of loaded textures
  12329. * @returns an array containing all loaded textures
  12330. */
  12331. Engine.prototype.getLoadedTexturesCache = function () {
  12332. return this._internalTexturesCache;
  12333. };
  12334. /**
  12335. * Gets the object containing all engine capabilities
  12336. * @returns the EngineCapabilities object
  12337. */
  12338. Engine.prototype.getCaps = function () {
  12339. return this._caps;
  12340. };
  12341. Object.defineProperty(Engine.prototype, "drawCalls", {
  12342. /** @hidden */
  12343. get: function () {
  12344. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12345. return 0;
  12346. },
  12347. enumerable: true,
  12348. configurable: true
  12349. });
  12350. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12351. /** @hidden */
  12352. get: function () {
  12353. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12354. return null;
  12355. },
  12356. enumerable: true,
  12357. configurable: true
  12358. });
  12359. /**
  12360. * Gets the current depth function
  12361. * @returns a number defining the depth function
  12362. */
  12363. Engine.prototype.getDepthFunction = function () {
  12364. return this._depthCullingState.depthFunc;
  12365. };
  12366. /**
  12367. * Sets the current depth function
  12368. * @param depthFunc defines the function to use
  12369. */
  12370. Engine.prototype.setDepthFunction = function (depthFunc) {
  12371. this._depthCullingState.depthFunc = depthFunc;
  12372. };
  12373. /**
  12374. * Sets the current depth function to GREATER
  12375. */
  12376. Engine.prototype.setDepthFunctionToGreater = function () {
  12377. this._depthCullingState.depthFunc = this._gl.GREATER;
  12378. };
  12379. /**
  12380. * Sets the current depth function to GEQUAL
  12381. */
  12382. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12383. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12384. };
  12385. /**
  12386. * Sets the current depth function to LESS
  12387. */
  12388. Engine.prototype.setDepthFunctionToLess = function () {
  12389. this._depthCullingState.depthFunc = this._gl.LESS;
  12390. };
  12391. /**
  12392. * Sets the current depth function to LEQUAL
  12393. */
  12394. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12395. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12396. };
  12397. /**
  12398. * Gets a boolean indicating if stencil buffer is enabled
  12399. * @returns the current stencil buffer state
  12400. */
  12401. Engine.prototype.getStencilBuffer = function () {
  12402. return this._stencilState.stencilTest;
  12403. };
  12404. /**
  12405. * Enable or disable the stencil buffer
  12406. * @param enable defines if the stencil buffer must be enabled or disabled
  12407. */
  12408. Engine.prototype.setStencilBuffer = function (enable) {
  12409. this._stencilState.stencilTest = enable;
  12410. };
  12411. /**
  12412. * Gets the current stencil mask
  12413. * @returns a number defining the new stencil mask to use
  12414. */
  12415. Engine.prototype.getStencilMask = function () {
  12416. return this._stencilState.stencilMask;
  12417. };
  12418. /**
  12419. * Sets the current stencil mask
  12420. * @param mask defines the new stencil mask to use
  12421. */
  12422. Engine.prototype.setStencilMask = function (mask) {
  12423. this._stencilState.stencilMask = mask;
  12424. };
  12425. /**
  12426. * Gets the current stencil function
  12427. * @returns a number defining the stencil function to use
  12428. */
  12429. Engine.prototype.getStencilFunction = function () {
  12430. return this._stencilState.stencilFunc;
  12431. };
  12432. /**
  12433. * Gets the current stencil reference value
  12434. * @returns a number defining the stencil reference value to use
  12435. */
  12436. Engine.prototype.getStencilFunctionReference = function () {
  12437. return this._stencilState.stencilFuncRef;
  12438. };
  12439. /**
  12440. * Gets the current stencil mask
  12441. * @returns a number defining the stencil mask to use
  12442. */
  12443. Engine.prototype.getStencilFunctionMask = function () {
  12444. return this._stencilState.stencilFuncMask;
  12445. };
  12446. /**
  12447. * Sets the current stencil function
  12448. * @param stencilFunc defines the new stencil function to use
  12449. */
  12450. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12451. this._stencilState.stencilFunc = stencilFunc;
  12452. };
  12453. /**
  12454. * Sets the current stencil reference
  12455. * @param reference defines the new stencil reference to use
  12456. */
  12457. Engine.prototype.setStencilFunctionReference = function (reference) {
  12458. this._stencilState.stencilFuncRef = reference;
  12459. };
  12460. /**
  12461. * Sets the current stencil mask
  12462. * @param mask defines the new stencil mask to use
  12463. */
  12464. Engine.prototype.setStencilFunctionMask = function (mask) {
  12465. this._stencilState.stencilFuncMask = mask;
  12466. };
  12467. /**
  12468. * Gets the current stencil operation when stencil fails
  12469. * @returns a number defining stencil operation to use when stencil fails
  12470. */
  12471. Engine.prototype.getStencilOperationFail = function () {
  12472. return this._stencilState.stencilOpStencilFail;
  12473. };
  12474. /**
  12475. * Gets the current stencil operation when depth fails
  12476. * @returns a number defining stencil operation to use when depth fails
  12477. */
  12478. Engine.prototype.getStencilOperationDepthFail = function () {
  12479. return this._stencilState.stencilOpDepthFail;
  12480. };
  12481. /**
  12482. * Gets the current stencil operation when stencil passes
  12483. * @returns a number defining stencil operation to use when stencil passes
  12484. */
  12485. Engine.prototype.getStencilOperationPass = function () {
  12486. return this._stencilState.stencilOpStencilDepthPass;
  12487. };
  12488. /**
  12489. * Sets the stencil operation to use when stencil fails
  12490. * @param operation defines the stencil operation to use when stencil fails
  12491. */
  12492. Engine.prototype.setStencilOperationFail = function (operation) {
  12493. this._stencilState.stencilOpStencilFail = operation;
  12494. };
  12495. /**
  12496. * Sets the stencil operation to use when depth fails
  12497. * @param operation defines the stencil operation to use when depth fails
  12498. */
  12499. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12500. this._stencilState.stencilOpDepthFail = operation;
  12501. };
  12502. /**
  12503. * Sets the stencil operation to use when stencil passes
  12504. * @param operation defines the stencil operation to use when stencil passes
  12505. */
  12506. Engine.prototype.setStencilOperationPass = function (operation) {
  12507. this._stencilState.stencilOpStencilDepthPass = operation;
  12508. };
  12509. /**
  12510. * Sets a boolean indicating if the dithering state is enabled or disabled
  12511. * @param value defines the dithering state
  12512. */
  12513. Engine.prototype.setDitheringState = function (value) {
  12514. if (value) {
  12515. this._gl.enable(this._gl.DITHER);
  12516. }
  12517. else {
  12518. this._gl.disable(this._gl.DITHER);
  12519. }
  12520. };
  12521. /**
  12522. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12523. * @param value defines the rasterizer state
  12524. */
  12525. Engine.prototype.setRasterizerState = function (value) {
  12526. if (value) {
  12527. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12528. }
  12529. else {
  12530. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12531. }
  12532. };
  12533. /**
  12534. * stop executing a render loop function and remove it from the execution array
  12535. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12536. */
  12537. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12538. if (!renderFunction) {
  12539. this._activeRenderLoops = [];
  12540. return;
  12541. }
  12542. var index = this._activeRenderLoops.indexOf(renderFunction);
  12543. if (index >= 0) {
  12544. this._activeRenderLoops.splice(index, 1);
  12545. }
  12546. };
  12547. /** @hidden */
  12548. Engine.prototype._renderLoop = function () {
  12549. if (!this._contextWasLost) {
  12550. var shouldRender = true;
  12551. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12552. shouldRender = false;
  12553. }
  12554. if (shouldRender) {
  12555. // Start new frame
  12556. this.beginFrame();
  12557. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12558. var renderFunction = this._activeRenderLoops[index];
  12559. renderFunction();
  12560. }
  12561. // Present
  12562. this.endFrame();
  12563. }
  12564. }
  12565. if (this._activeRenderLoops.length > 0) {
  12566. // Register new frame
  12567. var requester = null;
  12568. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12569. requester = this._vrDisplay;
  12570. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12571. }
  12572. else {
  12573. this._renderingQueueLaunched = false;
  12574. }
  12575. };
  12576. /**
  12577. * Register and execute a render loop. The engine can have more than one render function
  12578. * @param renderFunction defines the function to continuously execute
  12579. */
  12580. Engine.prototype.runRenderLoop = function (renderFunction) {
  12581. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12582. return;
  12583. }
  12584. this._activeRenderLoops.push(renderFunction);
  12585. if (!this._renderingQueueLaunched) {
  12586. this._renderingQueueLaunched = true;
  12587. this._bindedRenderFunction = this._renderLoop.bind(this);
  12588. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12589. }
  12590. };
  12591. /**
  12592. * Toggle full screen mode
  12593. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12594. * @param options defines an option object to be sent to the requestFullscreen function
  12595. */
  12596. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12597. if (this.isFullscreen) {
  12598. BABYLON.Tools.ExitFullscreen();
  12599. }
  12600. else {
  12601. this._pointerLockRequested = requestPointerLock;
  12602. if (this._renderingCanvas) {
  12603. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12604. }
  12605. }
  12606. };
  12607. /**
  12608. * Clear the current render buffer or the current render target (if any is set up)
  12609. * @param color defines the color to use
  12610. * @param backBuffer defines if the back buffer must be cleared
  12611. * @param depth defines if the depth buffer must be cleared
  12612. * @param stencil defines if the stencil buffer must be cleared
  12613. */
  12614. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12615. if (stencil === void 0) { stencil = false; }
  12616. this.applyStates();
  12617. var mode = 0;
  12618. if (backBuffer && color) {
  12619. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12620. mode |= this._gl.COLOR_BUFFER_BIT;
  12621. }
  12622. if (depth) {
  12623. this._gl.clearDepth(1.0);
  12624. mode |= this._gl.DEPTH_BUFFER_BIT;
  12625. }
  12626. if (stencil) {
  12627. this._gl.clearStencil(0);
  12628. mode |= this._gl.STENCIL_BUFFER_BIT;
  12629. }
  12630. this._gl.clear(mode);
  12631. };
  12632. /**
  12633. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12634. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12635. * @param y defines the y-coordinate of the corner of the clear rectangle
  12636. * @param width defines the width of the clear rectangle
  12637. * @param height defines the height of the clear rectangle
  12638. * @param clearColor defines the clear color
  12639. */
  12640. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12641. var gl = this._gl;
  12642. // Save state
  12643. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12644. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12645. // Change state
  12646. gl.enable(gl.SCISSOR_TEST);
  12647. gl.scissor(x, y, width, height);
  12648. // Clear
  12649. this.clear(clearColor, true, true, true);
  12650. // Restore state
  12651. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12652. if (curScissor === true) {
  12653. gl.enable(gl.SCISSOR_TEST);
  12654. }
  12655. else {
  12656. gl.disable(gl.SCISSOR_TEST);
  12657. }
  12658. };
  12659. /** @hidden */
  12660. Engine.prototype._viewport = function (x, y, width, height) {
  12661. if (x !== this._viewportCached.x ||
  12662. y !== this._viewportCached.y ||
  12663. width !== this._viewportCached.z ||
  12664. height !== this._viewportCached.w) {
  12665. this._viewportCached.x = x;
  12666. this._viewportCached.y = y;
  12667. this._viewportCached.z = width;
  12668. this._viewportCached.w = height;
  12669. this._gl.viewport(x, y, width, height);
  12670. }
  12671. };
  12672. /**
  12673. * Set the WebGL's viewport
  12674. * @param viewport defines the viewport element to be used
  12675. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12676. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12677. */
  12678. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12679. var width = requiredWidth || this.getRenderWidth();
  12680. var height = requiredHeight || this.getRenderHeight();
  12681. var x = viewport.x || 0;
  12682. var y = viewport.y || 0;
  12683. this._cachedViewport = viewport;
  12684. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12685. };
  12686. /**
  12687. * Directly set the WebGL Viewport
  12688. * @param x defines the x coordinate of the viewport (in screen space)
  12689. * @param y defines the y coordinate of the viewport (in screen space)
  12690. * @param width defines the width of the viewport (in screen space)
  12691. * @param height defines the height of the viewport (in screen space)
  12692. * @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
  12693. */
  12694. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12695. var currentViewport = this._cachedViewport;
  12696. this._cachedViewport = null;
  12697. this._viewport(x, y, width, height);
  12698. return currentViewport;
  12699. };
  12700. /**
  12701. * Begin a new frame
  12702. */
  12703. Engine.prototype.beginFrame = function () {
  12704. this.onBeginFrameObservable.notifyObservers(this);
  12705. this._measureFps();
  12706. };
  12707. /**
  12708. * Enf the current frame
  12709. */
  12710. Engine.prototype.endFrame = function () {
  12711. // Force a flush in case we are using a bad OS.
  12712. if (this._badOS) {
  12713. this.flushFramebuffer();
  12714. }
  12715. // Submit frame to the vr device, if enabled
  12716. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12717. // TODO: We should only submit the frame if we read frameData successfully.
  12718. this._vrDisplay.submitFrame();
  12719. }
  12720. this.onEndFrameObservable.notifyObservers(this);
  12721. };
  12722. /**
  12723. * Resize the view according to the canvas' size
  12724. */
  12725. Engine.prototype.resize = function () {
  12726. // We're not resizing the size of the canvas while in VR mode & presenting
  12727. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12728. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12729. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12730. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12731. }
  12732. };
  12733. /**
  12734. * Force a specific size of the canvas
  12735. * @param width defines the new canvas' width
  12736. * @param height defines the new canvas' height
  12737. */
  12738. Engine.prototype.setSize = function (width, height) {
  12739. if (!this._renderingCanvas) {
  12740. return;
  12741. }
  12742. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12743. return;
  12744. }
  12745. this._renderingCanvas.width = width;
  12746. this._renderingCanvas.height = height;
  12747. for (var index = 0; index < this.scenes.length; index++) {
  12748. var scene = this.scenes[index];
  12749. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12750. var cam = scene.cameras[camIndex];
  12751. cam._currentRenderId = 0;
  12752. }
  12753. }
  12754. if (this.onResizeObservable.hasObservers) {
  12755. this.onResizeObservable.notifyObservers(this);
  12756. }
  12757. };
  12758. // WebVR functions
  12759. /**
  12760. * Gets a boolean indicating if a webVR device was detected
  12761. * @returns true if a webVR device was detected
  12762. */
  12763. Engine.prototype.isVRDevicePresent = function () {
  12764. return !!this._vrDisplay;
  12765. };
  12766. /**
  12767. * Gets the current webVR device
  12768. * @returns the current webVR device (or null)
  12769. */
  12770. Engine.prototype.getVRDevice = function () {
  12771. return this._vrDisplay;
  12772. };
  12773. /**
  12774. * Initializes a webVR display and starts listening to display change events
  12775. * The onVRDisplayChangedObservable will be notified upon these changes
  12776. * @returns The onVRDisplayChangedObservable
  12777. */
  12778. Engine.prototype.initWebVR = function () {
  12779. this.initWebVRAsync();
  12780. return this.onVRDisplayChangedObservable;
  12781. };
  12782. /**
  12783. * Initializes a webVR display and starts listening to display change events
  12784. * The onVRDisplayChangedObservable will be notified upon these changes
  12785. * @returns A promise containing a VRDisplay and if vr is supported
  12786. */
  12787. Engine.prototype.initWebVRAsync = function () {
  12788. var _this = this;
  12789. var notifyObservers = function () {
  12790. var eventArgs = {
  12791. vrDisplay: _this._vrDisplay,
  12792. vrSupported: _this._vrSupported
  12793. };
  12794. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12795. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12796. };
  12797. if (!this._onVrDisplayConnect) {
  12798. this._onVrDisplayConnect = function (event) {
  12799. _this._vrDisplay = event.display;
  12800. notifyObservers();
  12801. };
  12802. this._onVrDisplayDisconnect = function () {
  12803. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12804. _this._vrDisplay = undefined;
  12805. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12806. notifyObservers();
  12807. };
  12808. this._onVrDisplayPresentChange = function () {
  12809. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12810. };
  12811. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12812. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12813. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12814. }
  12815. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12816. this._webVRInitPromise.then(notifyObservers);
  12817. return this._webVRInitPromise;
  12818. };
  12819. /**
  12820. * Call this function to switch to webVR mode
  12821. * Will do nothing if webVR is not supported or if there is no webVR device
  12822. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12823. */
  12824. Engine.prototype.enableVR = function () {
  12825. var _this = this;
  12826. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12827. var onResolved = function () {
  12828. _this.onVRRequestPresentComplete.notifyObservers(true);
  12829. _this._onVRFullScreenTriggered();
  12830. };
  12831. var onRejected = function () {
  12832. _this.onVRRequestPresentComplete.notifyObservers(false);
  12833. };
  12834. this.onVRRequestPresentStart.notifyObservers(this);
  12835. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12836. }
  12837. };
  12838. /**
  12839. * Call this function to leave webVR mode
  12840. * Will do nothing if webVR is not supported or if there is no webVR device
  12841. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12842. */
  12843. Engine.prototype.disableVR = function () {
  12844. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12845. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12846. }
  12847. };
  12848. Engine.prototype._getVRDisplaysAsync = function () {
  12849. var _this = this;
  12850. return new Promise(function (res, rej) {
  12851. if (navigator.getVRDisplays) {
  12852. navigator.getVRDisplays().then(function (devices) {
  12853. _this._vrSupported = true;
  12854. // note that devices may actually be an empty array. This is fine;
  12855. // we expect this._vrDisplay to be undefined in this case.
  12856. _this._vrDisplay = devices[0];
  12857. res({
  12858. vrDisplay: _this._vrDisplay,
  12859. vrSupported: _this._vrSupported
  12860. });
  12861. });
  12862. }
  12863. else {
  12864. _this._vrDisplay = undefined;
  12865. _this._vrSupported = false;
  12866. res({
  12867. vrDisplay: _this._vrDisplay,
  12868. vrSupported: _this._vrSupported
  12869. });
  12870. }
  12871. });
  12872. };
  12873. /**
  12874. * Binds the frame buffer to the specified texture.
  12875. * @param texture The texture to render to or null for the default canvas
  12876. * @param faceIndex The face of the texture to render to in case of cube texture
  12877. * @param requiredWidth The width of the target to render to
  12878. * @param requiredHeight The height of the target to render to
  12879. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12880. * @param depthStencilTexture The depth stencil texture to use to render
  12881. * @param lodLevel defines le lod level to bind to the frame buffer
  12882. */
  12883. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12884. if (lodLevel === void 0) { lodLevel = 0; }
  12885. if (this._currentRenderTarget) {
  12886. this.unBindFramebuffer(this._currentRenderTarget);
  12887. }
  12888. this._currentRenderTarget = texture;
  12889. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12890. var gl = this._gl;
  12891. if (texture.isCube) {
  12892. if (faceIndex === undefined) {
  12893. faceIndex = 0;
  12894. }
  12895. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12896. if (depthStencilTexture) {
  12897. if (depthStencilTexture._generateStencilBuffer) {
  12898. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12899. }
  12900. else {
  12901. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12902. }
  12903. }
  12904. }
  12905. if (this._cachedViewport && !forceFullscreenViewport) {
  12906. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12907. }
  12908. else {
  12909. if (!requiredWidth) {
  12910. requiredWidth = texture.width;
  12911. if (lodLevel) {
  12912. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12913. }
  12914. }
  12915. if (!requiredHeight) {
  12916. requiredHeight = texture.height;
  12917. if (lodLevel) {
  12918. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12919. }
  12920. }
  12921. this._viewport(0, 0, requiredWidth, requiredHeight);
  12922. }
  12923. this.wipeCaches();
  12924. };
  12925. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12926. if (this._currentFramebuffer !== framebuffer) {
  12927. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12928. this._currentFramebuffer = framebuffer;
  12929. }
  12930. };
  12931. /**
  12932. * Unbind the current render target texture from the webGL context
  12933. * @param texture defines the render target texture to unbind
  12934. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12935. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12936. */
  12937. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12938. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12939. this._currentRenderTarget = null;
  12940. // If MSAA, we need to bitblt back to main texture
  12941. var gl = this._gl;
  12942. if (texture._MSAAFramebuffer) {
  12943. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12944. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12945. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12946. }
  12947. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12948. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12949. gl.generateMipmap(gl.TEXTURE_2D);
  12950. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12951. }
  12952. if (onBeforeUnbind) {
  12953. if (texture._MSAAFramebuffer) {
  12954. // Bind the correct framebuffer
  12955. this.bindUnboundFramebuffer(texture._framebuffer);
  12956. }
  12957. onBeforeUnbind();
  12958. }
  12959. this.bindUnboundFramebuffer(null);
  12960. };
  12961. /**
  12962. * Unbind a list of render target textures from the webGL context
  12963. * This is used only when drawBuffer extension or webGL2 are active
  12964. * @param textures defines the render target textures to unbind
  12965. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12966. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12967. */
  12968. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12969. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12970. this._currentRenderTarget = null;
  12971. // If MSAA, we need to bitblt back to main texture
  12972. var gl = this._gl;
  12973. if (textures[0]._MSAAFramebuffer) {
  12974. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12975. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12976. var attachments = textures[0]._attachments;
  12977. if (!attachments) {
  12978. attachments = new Array(textures.length);
  12979. textures[0]._attachments = attachments;
  12980. }
  12981. for (var i = 0; i < textures.length; i++) {
  12982. var texture = textures[i];
  12983. for (var j = 0; j < attachments.length; j++) {
  12984. attachments[j] = gl.NONE;
  12985. }
  12986. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12987. gl.readBuffer(attachments[i]);
  12988. gl.drawBuffers(attachments);
  12989. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12990. }
  12991. for (var i = 0; i < attachments.length; i++) {
  12992. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12993. }
  12994. gl.drawBuffers(attachments);
  12995. }
  12996. for (var i = 0; i < textures.length; i++) {
  12997. var texture = textures[i];
  12998. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12999. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13000. gl.generateMipmap(gl.TEXTURE_2D);
  13001. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13002. }
  13003. }
  13004. if (onBeforeUnbind) {
  13005. if (textures[0]._MSAAFramebuffer) {
  13006. // Bind the correct framebuffer
  13007. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13008. }
  13009. onBeforeUnbind();
  13010. }
  13011. this.bindUnboundFramebuffer(null);
  13012. };
  13013. /**
  13014. * Force the mipmap generation for the given render target texture
  13015. * @param texture defines the render target texture to use
  13016. */
  13017. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13018. if (texture.generateMipMaps) {
  13019. var gl = this._gl;
  13020. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13021. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13022. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13023. }
  13024. };
  13025. /**
  13026. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13027. */
  13028. Engine.prototype.flushFramebuffer = function () {
  13029. this._gl.flush();
  13030. };
  13031. /**
  13032. * Unbind the current render target and bind the default framebuffer
  13033. */
  13034. Engine.prototype.restoreDefaultFramebuffer = function () {
  13035. if (this._currentRenderTarget) {
  13036. this.unBindFramebuffer(this._currentRenderTarget);
  13037. }
  13038. else {
  13039. this.bindUnboundFramebuffer(null);
  13040. }
  13041. if (this._cachedViewport) {
  13042. this.setViewport(this._cachedViewport);
  13043. }
  13044. this.wipeCaches();
  13045. };
  13046. // UBOs
  13047. /**
  13048. * Create an uniform buffer
  13049. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13050. * @param elements defines the content of the uniform buffer
  13051. * @returns the webGL uniform buffer
  13052. */
  13053. Engine.prototype.createUniformBuffer = function (elements) {
  13054. var ubo = this._gl.createBuffer();
  13055. if (!ubo) {
  13056. throw new Error("Unable to create uniform buffer");
  13057. }
  13058. this.bindUniformBuffer(ubo);
  13059. if (elements instanceof Float32Array) {
  13060. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13061. }
  13062. else {
  13063. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13064. }
  13065. this.bindUniformBuffer(null);
  13066. ubo.references = 1;
  13067. return ubo;
  13068. };
  13069. /**
  13070. * Create a dynamic uniform buffer
  13071. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13072. * @param elements defines the content of the uniform buffer
  13073. * @returns the webGL uniform buffer
  13074. */
  13075. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13076. var ubo = this._gl.createBuffer();
  13077. if (!ubo) {
  13078. throw new Error("Unable to create dynamic uniform buffer");
  13079. }
  13080. this.bindUniformBuffer(ubo);
  13081. if (elements instanceof Float32Array) {
  13082. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13083. }
  13084. else {
  13085. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13086. }
  13087. this.bindUniformBuffer(null);
  13088. ubo.references = 1;
  13089. return ubo;
  13090. };
  13091. /**
  13092. * Update an existing uniform buffer
  13093. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13094. * @param uniformBuffer defines the target uniform buffer
  13095. * @param elements defines the content to update
  13096. * @param offset defines the offset in the uniform buffer where update should start
  13097. * @param count defines the size of the data to update
  13098. */
  13099. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13100. this.bindUniformBuffer(uniformBuffer);
  13101. if (offset === undefined) {
  13102. offset = 0;
  13103. }
  13104. if (count === undefined) {
  13105. if (elements instanceof Float32Array) {
  13106. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13107. }
  13108. else {
  13109. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13110. }
  13111. }
  13112. else {
  13113. if (elements instanceof Float32Array) {
  13114. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13115. }
  13116. else {
  13117. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13118. }
  13119. }
  13120. this.bindUniformBuffer(null);
  13121. };
  13122. // VBOs
  13123. Engine.prototype._resetVertexBufferBinding = function () {
  13124. this.bindArrayBuffer(null);
  13125. this._cachedVertexBuffers = null;
  13126. };
  13127. /**
  13128. * Creates a vertex buffer
  13129. * @param data the data for the vertex buffer
  13130. * @returns the new WebGL static buffer
  13131. */
  13132. Engine.prototype.createVertexBuffer = function (data) {
  13133. var vbo = this._gl.createBuffer();
  13134. if (!vbo) {
  13135. throw new Error("Unable to create vertex buffer");
  13136. }
  13137. this.bindArrayBuffer(vbo);
  13138. if (data instanceof Array) {
  13139. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13140. }
  13141. else {
  13142. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13143. }
  13144. this._resetVertexBufferBinding();
  13145. vbo.references = 1;
  13146. return vbo;
  13147. };
  13148. /**
  13149. * Creates a dynamic vertex buffer
  13150. * @param data the data for the dynamic vertex buffer
  13151. * @returns the new WebGL dynamic buffer
  13152. */
  13153. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13154. var vbo = this._gl.createBuffer();
  13155. if (!vbo) {
  13156. throw new Error("Unable to create dynamic vertex buffer");
  13157. }
  13158. this.bindArrayBuffer(vbo);
  13159. if (data instanceof Array) {
  13160. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13161. }
  13162. else {
  13163. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13164. }
  13165. this._resetVertexBufferBinding();
  13166. vbo.references = 1;
  13167. return vbo;
  13168. };
  13169. /**
  13170. * Update a dynamic index buffer
  13171. * @param indexBuffer defines the target index buffer
  13172. * @param indices defines the data to update
  13173. * @param offset defines the offset in the target index buffer where update should start
  13174. */
  13175. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13176. if (offset === void 0) { offset = 0; }
  13177. // Force cache update
  13178. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13179. this.bindIndexBuffer(indexBuffer);
  13180. var arrayBuffer;
  13181. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13182. arrayBuffer = indices;
  13183. }
  13184. else {
  13185. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13186. }
  13187. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13188. this._resetIndexBufferBinding();
  13189. };
  13190. /**
  13191. * Updates a dynamic vertex buffer.
  13192. * @param vertexBuffer the vertex buffer to update
  13193. * @param data the data used to update the vertex buffer
  13194. * @param byteOffset the byte offset of the data
  13195. * @param byteLength the byte length of the data
  13196. */
  13197. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13198. this.bindArrayBuffer(vertexBuffer);
  13199. if (byteOffset === undefined) {
  13200. byteOffset = 0;
  13201. }
  13202. if (byteLength === undefined) {
  13203. if (data instanceof Array) {
  13204. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13205. }
  13206. else {
  13207. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13208. }
  13209. }
  13210. else {
  13211. if (data instanceof Array) {
  13212. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13213. }
  13214. else {
  13215. if (data instanceof ArrayBuffer) {
  13216. data = new Uint8Array(data, byteOffset, byteLength);
  13217. }
  13218. else {
  13219. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13220. }
  13221. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13222. }
  13223. }
  13224. this._resetVertexBufferBinding();
  13225. };
  13226. Engine.prototype._resetIndexBufferBinding = function () {
  13227. this.bindIndexBuffer(null);
  13228. this._cachedIndexBuffer = null;
  13229. };
  13230. /**
  13231. * Creates a new index buffer
  13232. * @param indices defines the content of the index buffer
  13233. * @param updatable defines if the index buffer must be updatable
  13234. * @returns a new webGL buffer
  13235. */
  13236. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13237. var vbo = this._gl.createBuffer();
  13238. if (!vbo) {
  13239. throw new Error("Unable to create index buffer");
  13240. }
  13241. this.bindIndexBuffer(vbo);
  13242. // Check for 32 bits indices
  13243. var arrayBuffer;
  13244. var need32Bits = false;
  13245. if (indices instanceof Uint16Array) {
  13246. arrayBuffer = indices;
  13247. }
  13248. else {
  13249. //check 32 bit support
  13250. if (this._caps.uintIndices) {
  13251. if (indices instanceof Uint32Array) {
  13252. arrayBuffer = indices;
  13253. need32Bits = true;
  13254. }
  13255. else {
  13256. //number[] or Int32Array, check if 32 bit is necessary
  13257. for (var index = 0; index < indices.length; index++) {
  13258. if (indices[index] > 65535) {
  13259. need32Bits = true;
  13260. break;
  13261. }
  13262. }
  13263. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13264. }
  13265. }
  13266. else {
  13267. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13268. arrayBuffer = new Uint16Array(indices);
  13269. }
  13270. }
  13271. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13272. this._resetIndexBufferBinding();
  13273. vbo.references = 1;
  13274. vbo.is32Bits = need32Bits;
  13275. return vbo;
  13276. };
  13277. /**
  13278. * Bind a webGL buffer to the webGL context
  13279. * @param buffer defines the buffer to bind
  13280. */
  13281. Engine.prototype.bindArrayBuffer = function (buffer) {
  13282. if (!this._vaoRecordInProgress) {
  13283. this._unbindVertexArrayObject();
  13284. }
  13285. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13286. };
  13287. /**
  13288. * Bind an uniform buffer to the current webGL context
  13289. * @param buffer defines the buffer to bind
  13290. */
  13291. Engine.prototype.bindUniformBuffer = function (buffer) {
  13292. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13293. };
  13294. /**
  13295. * Bind a buffer to the current webGL context at a given location
  13296. * @param buffer defines the buffer to bind
  13297. * @param location defines the index where to bind the buffer
  13298. */
  13299. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13300. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13301. };
  13302. /**
  13303. * Bind a specific block at a given index in a specific shader program
  13304. * @param shaderProgram defines the shader program
  13305. * @param blockName defines the block name
  13306. * @param index defines the index where to bind the block
  13307. */
  13308. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13309. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13310. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13311. };
  13312. ;
  13313. Engine.prototype.bindIndexBuffer = function (buffer) {
  13314. if (!this._vaoRecordInProgress) {
  13315. this._unbindVertexArrayObject();
  13316. }
  13317. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13318. };
  13319. Engine.prototype.bindBuffer = function (buffer, target) {
  13320. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13321. this._gl.bindBuffer(target, buffer);
  13322. this._currentBoundBuffer[target] = buffer;
  13323. }
  13324. };
  13325. /**
  13326. * update the bound buffer with the given data
  13327. * @param data defines the data to update
  13328. */
  13329. Engine.prototype.updateArrayBuffer = function (data) {
  13330. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13331. };
  13332. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13333. var pointer = this._currentBufferPointers[indx];
  13334. var changed = false;
  13335. if (!pointer.active) {
  13336. changed = true;
  13337. pointer.active = true;
  13338. pointer.index = indx;
  13339. pointer.size = size;
  13340. pointer.type = type;
  13341. pointer.normalized = normalized;
  13342. pointer.stride = stride;
  13343. pointer.offset = offset;
  13344. pointer.buffer = buffer;
  13345. }
  13346. else {
  13347. if (pointer.buffer !== buffer) {
  13348. pointer.buffer = buffer;
  13349. changed = true;
  13350. }
  13351. if (pointer.size !== size) {
  13352. pointer.size = size;
  13353. changed = true;
  13354. }
  13355. if (pointer.type !== type) {
  13356. pointer.type = type;
  13357. changed = true;
  13358. }
  13359. if (pointer.normalized !== normalized) {
  13360. pointer.normalized = normalized;
  13361. changed = true;
  13362. }
  13363. if (pointer.stride !== stride) {
  13364. pointer.stride = stride;
  13365. changed = true;
  13366. }
  13367. if (pointer.offset !== offset) {
  13368. pointer.offset = offset;
  13369. changed = true;
  13370. }
  13371. }
  13372. if (changed || this._vaoRecordInProgress) {
  13373. this.bindArrayBuffer(buffer);
  13374. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13375. }
  13376. };
  13377. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13378. if (indexBuffer == null) {
  13379. return;
  13380. }
  13381. if (this._cachedIndexBuffer !== indexBuffer) {
  13382. this._cachedIndexBuffer = indexBuffer;
  13383. this.bindIndexBuffer(indexBuffer);
  13384. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13385. }
  13386. };
  13387. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13388. var attributes = effect.getAttributesNames();
  13389. if (!this._vaoRecordInProgress) {
  13390. this._unbindVertexArrayObject();
  13391. }
  13392. this.unbindAllAttributes();
  13393. for (var index = 0; index < attributes.length; index++) {
  13394. var order = effect.getAttributeLocation(index);
  13395. if (order >= 0) {
  13396. var vertexBuffer = vertexBuffers[attributes[index]];
  13397. if (!vertexBuffer) {
  13398. continue;
  13399. }
  13400. this._gl.enableVertexAttribArray(order);
  13401. if (!this._vaoRecordInProgress) {
  13402. this._vertexAttribArraysEnabled[order] = true;
  13403. }
  13404. var buffer = vertexBuffer.getBuffer();
  13405. if (buffer) {
  13406. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13407. if (vertexBuffer.getIsInstanced()) {
  13408. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13409. if (!this._vaoRecordInProgress) {
  13410. this._currentInstanceLocations.push(order);
  13411. this._currentInstanceBuffers.push(buffer);
  13412. }
  13413. }
  13414. }
  13415. }
  13416. }
  13417. };
  13418. /**
  13419. * Records a vertex array object
  13420. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13421. * @param vertexBuffers defines the list of vertex buffers to store
  13422. * @param indexBuffer defines the index buffer to store
  13423. * @param effect defines the effect to store
  13424. * @returns the new vertex array object
  13425. */
  13426. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13427. var vao = this._gl.createVertexArray();
  13428. this._vaoRecordInProgress = true;
  13429. this._gl.bindVertexArray(vao);
  13430. this._mustWipeVertexAttributes = true;
  13431. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13432. this.bindIndexBuffer(indexBuffer);
  13433. this._vaoRecordInProgress = false;
  13434. this._gl.bindVertexArray(null);
  13435. return vao;
  13436. };
  13437. /**
  13438. * Bind a specific vertex array object
  13439. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13440. * @param vertexArrayObject defines the vertex array object to bind
  13441. * @param indexBuffer defines the index buffer to bind
  13442. */
  13443. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13444. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13445. this._cachedVertexArrayObject = vertexArrayObject;
  13446. this._gl.bindVertexArray(vertexArrayObject);
  13447. this._cachedVertexBuffers = null;
  13448. this._cachedIndexBuffer = null;
  13449. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13450. this._mustWipeVertexAttributes = true;
  13451. }
  13452. };
  13453. /**
  13454. * Bind webGl buffers directly to the webGL context
  13455. * @param vertexBuffer defines the vertex buffer to bind
  13456. * @param indexBuffer defines the index buffer to bind
  13457. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13458. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13459. * @param effect defines the effect associated with the vertex buffer
  13460. */
  13461. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13462. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13463. this._cachedVertexBuffers = vertexBuffer;
  13464. this._cachedEffectForVertexBuffers = effect;
  13465. var attributesCount = effect.getAttributesCount();
  13466. this._unbindVertexArrayObject();
  13467. this.unbindAllAttributes();
  13468. var offset = 0;
  13469. for (var index = 0; index < attributesCount; index++) {
  13470. if (index < vertexDeclaration.length) {
  13471. var order = effect.getAttributeLocation(index);
  13472. if (order >= 0) {
  13473. this._gl.enableVertexAttribArray(order);
  13474. this._vertexAttribArraysEnabled[order] = true;
  13475. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13476. }
  13477. offset += vertexDeclaration[index] * 4;
  13478. }
  13479. }
  13480. }
  13481. this._bindIndexBufferWithCache(indexBuffer);
  13482. };
  13483. Engine.prototype._unbindVertexArrayObject = function () {
  13484. if (!this._cachedVertexArrayObject) {
  13485. return;
  13486. }
  13487. this._cachedVertexArrayObject = null;
  13488. this._gl.bindVertexArray(null);
  13489. };
  13490. /**
  13491. * Bind a list of vertex buffers to the webGL context
  13492. * @param vertexBuffers defines the list of vertex buffers to bind
  13493. * @param indexBuffer defines the index buffer to bind
  13494. * @param effect defines the effect associated with the vertex buffers
  13495. */
  13496. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13497. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13498. this._cachedVertexBuffers = vertexBuffers;
  13499. this._cachedEffectForVertexBuffers = effect;
  13500. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13501. }
  13502. this._bindIndexBufferWithCache(indexBuffer);
  13503. };
  13504. /**
  13505. * Unbind all instance attributes
  13506. */
  13507. Engine.prototype.unbindInstanceAttributes = function () {
  13508. var boundBuffer;
  13509. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13510. var instancesBuffer = this._currentInstanceBuffers[i];
  13511. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13512. boundBuffer = instancesBuffer;
  13513. this.bindArrayBuffer(instancesBuffer);
  13514. }
  13515. var offsetLocation = this._currentInstanceLocations[i];
  13516. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13517. }
  13518. this._currentInstanceBuffers.length = 0;
  13519. this._currentInstanceLocations.length = 0;
  13520. };
  13521. /**
  13522. * Release and free the memory of a vertex array object
  13523. * @param vao defines the vertex array object to delete
  13524. */
  13525. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13526. this._gl.deleteVertexArray(vao);
  13527. };
  13528. /** @hidden */
  13529. Engine.prototype._releaseBuffer = function (buffer) {
  13530. buffer.references--;
  13531. if (buffer.references === 0) {
  13532. this._gl.deleteBuffer(buffer);
  13533. return true;
  13534. }
  13535. return false;
  13536. };
  13537. /**
  13538. * Creates a webGL buffer to use with instanciation
  13539. * @param capacity defines the size of the buffer
  13540. * @returns the webGL buffer
  13541. */
  13542. Engine.prototype.createInstancesBuffer = function (capacity) {
  13543. var buffer = this._gl.createBuffer();
  13544. if (!buffer) {
  13545. throw new Error("Unable to create instance buffer");
  13546. }
  13547. buffer.capacity = capacity;
  13548. this.bindArrayBuffer(buffer);
  13549. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13550. return buffer;
  13551. };
  13552. /**
  13553. * Delete a webGL buffer used with instanciation
  13554. * @param buffer defines the webGL buffer to delete
  13555. */
  13556. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13557. this._gl.deleteBuffer(buffer);
  13558. };
  13559. /**
  13560. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13561. * @param instancesBuffer defines the webGL buffer to update and bind
  13562. * @param data defines the data to store in the buffer
  13563. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13564. */
  13565. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13566. this.bindArrayBuffer(instancesBuffer);
  13567. if (data) {
  13568. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13569. }
  13570. if (offsetLocations[0].index !== undefined) {
  13571. var stride = 0;
  13572. for (var i = 0; i < offsetLocations.length; i++) {
  13573. var ai = offsetLocations[i];
  13574. stride += ai.attributeSize * 4;
  13575. }
  13576. for (var i = 0; i < offsetLocations.length; i++) {
  13577. var ai = offsetLocations[i];
  13578. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13579. this._gl.enableVertexAttribArray(ai.index);
  13580. this._vertexAttribArraysEnabled[ai.index] = true;
  13581. }
  13582. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13583. this._gl.vertexAttribDivisor(ai.index, 1);
  13584. this._currentInstanceLocations.push(ai.index);
  13585. this._currentInstanceBuffers.push(instancesBuffer);
  13586. }
  13587. }
  13588. else {
  13589. for (var index = 0; index < 4; index++) {
  13590. var offsetLocation = offsetLocations[index];
  13591. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13592. this._gl.enableVertexAttribArray(offsetLocation);
  13593. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13594. }
  13595. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13596. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13597. this._currentInstanceLocations.push(offsetLocation);
  13598. this._currentInstanceBuffers.push(instancesBuffer);
  13599. }
  13600. }
  13601. };
  13602. /**
  13603. * Apply all cached states (depth, culling, stencil and alpha)
  13604. */
  13605. Engine.prototype.applyStates = function () {
  13606. this._depthCullingState.apply(this._gl);
  13607. this._stencilState.apply(this._gl);
  13608. this._alphaState.apply(this._gl);
  13609. };
  13610. /**
  13611. * Send a draw order
  13612. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13613. * @param indexStart defines the starting index
  13614. * @param indexCount defines the number of index to draw
  13615. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13616. */
  13617. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13618. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13619. };
  13620. /**
  13621. * Draw a list of points
  13622. * @param verticesStart defines the index of first vertex to draw
  13623. * @param verticesCount defines the count of vertices to draw
  13624. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13625. */
  13626. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13627. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13628. };
  13629. /**
  13630. * Draw a list of unindexed primitives
  13631. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13632. * @param verticesStart defines the index of first vertex to draw
  13633. * @param verticesCount defines the count of vertices to draw
  13634. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13635. */
  13636. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13637. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13638. };
  13639. /**
  13640. * Draw a list of indexed primitives
  13641. * @param fillMode defines the primitive to use
  13642. * @param indexStart defines the starting index
  13643. * @param indexCount defines the number of index to draw
  13644. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13645. */
  13646. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13647. // Apply states
  13648. this.applyStates();
  13649. this._drawCalls.addCount(1, false);
  13650. // Render
  13651. var drawMode = this._drawMode(fillMode);
  13652. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13653. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13654. if (instancesCount) {
  13655. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13656. }
  13657. else {
  13658. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13659. }
  13660. };
  13661. /**
  13662. * Draw a list of unindexed primitives
  13663. * @param fillMode defines the primitive to use
  13664. * @param verticesStart defines the index of first vertex to draw
  13665. * @param verticesCount defines the count of vertices to draw
  13666. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13667. */
  13668. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13669. // Apply states
  13670. this.applyStates();
  13671. this._drawCalls.addCount(1, false);
  13672. var drawMode = this._drawMode(fillMode);
  13673. if (instancesCount) {
  13674. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13675. }
  13676. else {
  13677. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13678. }
  13679. };
  13680. Engine.prototype._drawMode = function (fillMode) {
  13681. switch (fillMode) {
  13682. // Triangle views
  13683. case BABYLON.Material.TriangleFillMode:
  13684. return this._gl.TRIANGLES;
  13685. case BABYLON.Material.PointFillMode:
  13686. return this._gl.POINTS;
  13687. case BABYLON.Material.WireFrameFillMode:
  13688. return this._gl.LINES;
  13689. // Draw modes
  13690. case BABYLON.Material.PointListDrawMode:
  13691. return this._gl.POINTS;
  13692. case BABYLON.Material.LineListDrawMode:
  13693. return this._gl.LINES;
  13694. case BABYLON.Material.LineLoopDrawMode:
  13695. return this._gl.LINE_LOOP;
  13696. case BABYLON.Material.LineStripDrawMode:
  13697. return this._gl.LINE_STRIP;
  13698. case BABYLON.Material.TriangleStripDrawMode:
  13699. return this._gl.TRIANGLE_STRIP;
  13700. case BABYLON.Material.TriangleFanDrawMode:
  13701. return this._gl.TRIANGLE_FAN;
  13702. default:
  13703. return this._gl.TRIANGLES;
  13704. }
  13705. };
  13706. // Shaders
  13707. /** @hidden */
  13708. Engine.prototype._releaseEffect = function (effect) {
  13709. if (this._compiledEffects[effect._key]) {
  13710. delete this._compiledEffects[effect._key];
  13711. this._deleteProgram(effect.getProgram());
  13712. }
  13713. };
  13714. /** @hidden */
  13715. Engine.prototype._deleteProgram = function (program) {
  13716. if (program) {
  13717. program.__SPECTOR_rebuildProgram = null;
  13718. if (program.transformFeedback) {
  13719. this.deleteTransformFeedback(program.transformFeedback);
  13720. program.transformFeedback = null;
  13721. }
  13722. this._gl.deleteProgram(program);
  13723. }
  13724. };
  13725. /**
  13726. * Create a new effect (used to store vertex/fragment shaders)
  13727. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13728. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13729. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13730. * @param samplers defines an array of string used to represent textures
  13731. * @param defines defines the string containing the defines to use to compile the shaders
  13732. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13733. * @param onCompiled defines a function to call when the effect creation is successful
  13734. * @param onError defines a function to call when the effect creation has failed
  13735. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13736. * @returns the new Effect
  13737. */
  13738. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13739. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13740. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13741. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13742. if (this._compiledEffects[name]) {
  13743. var compiledEffect = this._compiledEffects[name];
  13744. if (onCompiled && compiledEffect.isReady()) {
  13745. onCompiled(compiledEffect);
  13746. }
  13747. return compiledEffect;
  13748. }
  13749. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13750. effect._key = name;
  13751. this._compiledEffects[name] = effect;
  13752. return effect;
  13753. };
  13754. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13755. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13756. };
  13757. ;
  13758. Engine.prototype._compileRawShader = function (source, type) {
  13759. var gl = this._gl;
  13760. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13761. gl.shaderSource(shader, source);
  13762. gl.compileShader(shader);
  13763. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13764. var log = gl.getShaderInfoLog(shader);
  13765. if (log) {
  13766. throw new Error(log);
  13767. }
  13768. }
  13769. if (!shader) {
  13770. throw new Error("Something went wrong while compile the shader.");
  13771. }
  13772. return shader;
  13773. };
  13774. ;
  13775. /**
  13776. * Directly creates a webGL program
  13777. * @param vertexCode defines the vertex shader code to use
  13778. * @param fragmentCode defines the fragment shader code to use
  13779. * @param context defines the webGL context to use (if not set, the current one will be used)
  13780. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13781. * @returns the new webGL program
  13782. */
  13783. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13784. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13785. context = context || this._gl;
  13786. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13787. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13788. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13789. };
  13790. /**
  13791. * Creates a webGL program
  13792. * @param vertexCode defines the vertex shader code to use
  13793. * @param fragmentCode defines the fragment shader code to use
  13794. * @param defines defines the string containing the defines to use to compile the shaders
  13795. * @param context defines the webGL context to use (if not set, the current one will be used)
  13796. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13797. * @returns the new webGL program
  13798. */
  13799. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13800. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13801. context = context || this._gl;
  13802. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13803. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13804. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13805. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13806. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13807. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13808. return program;
  13809. };
  13810. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13811. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13812. var shaderProgram = context.createProgram();
  13813. if (!shaderProgram) {
  13814. throw new Error("Unable to create program");
  13815. }
  13816. context.attachShader(shaderProgram, vertexShader);
  13817. context.attachShader(shaderProgram, fragmentShader);
  13818. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13819. var transformFeedback = this.createTransformFeedback();
  13820. this.bindTransformFeedback(transformFeedback);
  13821. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13822. shaderProgram.transformFeedback = transformFeedback;
  13823. }
  13824. context.linkProgram(shaderProgram);
  13825. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13826. this.bindTransformFeedback(null);
  13827. }
  13828. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13829. if (!linked) {
  13830. var error = context.getProgramInfoLog(shaderProgram);
  13831. if (error) {
  13832. throw new Error(error);
  13833. }
  13834. }
  13835. if (this.validateShaderPrograms) {
  13836. context.validateProgram(shaderProgram);
  13837. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13838. if (!validated) {
  13839. var error = context.getProgramInfoLog(shaderProgram);
  13840. if (error) {
  13841. throw new Error(error);
  13842. }
  13843. }
  13844. }
  13845. context.deleteShader(vertexShader);
  13846. context.deleteShader(fragmentShader);
  13847. return shaderProgram;
  13848. };
  13849. /**
  13850. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13851. * @param shaderProgram defines the webGL program to use
  13852. * @param uniformsNames defines the list of uniform names
  13853. * @returns an array of webGL uniform locations
  13854. */
  13855. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13856. var results = new Array();
  13857. for (var index = 0; index < uniformsNames.length; index++) {
  13858. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13859. }
  13860. return results;
  13861. };
  13862. /**
  13863. * Gets the lsit of active attributes for a given webGL program
  13864. * @param shaderProgram defines the webGL program to use
  13865. * @param attributesNames defines the list of attribute names to get
  13866. * @returns an array of indices indicating the offset of each attribute
  13867. */
  13868. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13869. var results = [];
  13870. for (var index = 0; index < attributesNames.length; index++) {
  13871. try {
  13872. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13873. }
  13874. catch (e) {
  13875. results.push(-1);
  13876. }
  13877. }
  13878. return results;
  13879. };
  13880. /**
  13881. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13882. * @param effect defines the effect to activate
  13883. */
  13884. Engine.prototype.enableEffect = function (effect) {
  13885. if (!effect || effect === this._currentEffect) {
  13886. return;
  13887. }
  13888. // Use program
  13889. this.bindSamplers(effect);
  13890. this._currentEffect = effect;
  13891. if (effect.onBind) {
  13892. effect.onBind(effect);
  13893. }
  13894. if (effect._onBindObservable) {
  13895. effect._onBindObservable.notifyObservers(effect);
  13896. }
  13897. };
  13898. /**
  13899. * Set the value of an uniform to an array of int32
  13900. * @param uniform defines the webGL uniform location where to store the value
  13901. * @param array defines the array of int32 to store
  13902. */
  13903. Engine.prototype.setIntArray = function (uniform, array) {
  13904. if (!uniform)
  13905. return;
  13906. this._gl.uniform1iv(uniform, array);
  13907. };
  13908. /**
  13909. * Set the value of an uniform to an array of int32 (stored as vec2)
  13910. * @param uniform defines the webGL uniform location where to store the value
  13911. * @param array defines the array of int32 to store
  13912. */
  13913. Engine.prototype.setIntArray2 = function (uniform, array) {
  13914. if (!uniform || array.length % 2 !== 0)
  13915. return;
  13916. this._gl.uniform2iv(uniform, array);
  13917. };
  13918. /**
  13919. * Set the value of an uniform to an array of int32 (stored as vec3)
  13920. * @param uniform defines the webGL uniform location where to store the value
  13921. * @param array defines the array of int32 to store
  13922. */
  13923. Engine.prototype.setIntArray3 = function (uniform, array) {
  13924. if (!uniform || array.length % 3 !== 0)
  13925. return;
  13926. this._gl.uniform3iv(uniform, array);
  13927. };
  13928. /**
  13929. * Set the value of an uniform to an array of int32 (stored as vec4)
  13930. * @param uniform defines the webGL uniform location where to store the value
  13931. * @param array defines the array of int32 to store
  13932. */
  13933. Engine.prototype.setIntArray4 = function (uniform, array) {
  13934. if (!uniform || array.length % 4 !== 0)
  13935. return;
  13936. this._gl.uniform4iv(uniform, array);
  13937. };
  13938. /**
  13939. * Set the value of an uniform to an array of float32
  13940. * @param uniform defines the webGL uniform location where to store the value
  13941. * @param array defines the array of float32 to store
  13942. */
  13943. Engine.prototype.setFloatArray = function (uniform, array) {
  13944. if (!uniform)
  13945. return;
  13946. this._gl.uniform1fv(uniform, array);
  13947. };
  13948. /**
  13949. * Set the value of an uniform to an array of float32 (stored as vec2)
  13950. * @param uniform defines the webGL uniform location where to store the value
  13951. * @param array defines the array of float32 to store
  13952. */
  13953. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13954. if (!uniform || array.length % 2 !== 0)
  13955. return;
  13956. this._gl.uniform2fv(uniform, array);
  13957. };
  13958. /**
  13959. * Set the value of an uniform to an array of float32 (stored as vec3)
  13960. * @param uniform defines the webGL uniform location where to store the value
  13961. * @param array defines the array of float32 to store
  13962. */
  13963. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13964. if (!uniform || array.length % 3 !== 0)
  13965. return;
  13966. this._gl.uniform3fv(uniform, array);
  13967. };
  13968. /**
  13969. * Set the value of an uniform to an array of float32 (stored as vec4)
  13970. * @param uniform defines the webGL uniform location where to store the value
  13971. * @param array defines the array of float32 to store
  13972. */
  13973. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13974. if (!uniform || array.length % 4 !== 0)
  13975. return;
  13976. this._gl.uniform4fv(uniform, array);
  13977. };
  13978. /**
  13979. * Set the value of an uniform to an array of number
  13980. * @param uniform defines the webGL uniform location where to store the value
  13981. * @param array defines the array of number to store
  13982. */
  13983. Engine.prototype.setArray = function (uniform, array) {
  13984. if (!uniform)
  13985. return;
  13986. this._gl.uniform1fv(uniform, array);
  13987. };
  13988. /**
  13989. * Set the value of an uniform to an array of number (stored as vec2)
  13990. * @param uniform defines the webGL uniform location where to store the value
  13991. * @param array defines the array of number to store
  13992. */
  13993. Engine.prototype.setArray2 = function (uniform, array) {
  13994. if (!uniform || array.length % 2 !== 0)
  13995. return;
  13996. this._gl.uniform2fv(uniform, array);
  13997. };
  13998. /**
  13999. * Set the value of an uniform to an array of number (stored as vec3)
  14000. * @param uniform defines the webGL uniform location where to store the value
  14001. * @param array defines the array of number to store
  14002. */
  14003. Engine.prototype.setArray3 = function (uniform, array) {
  14004. if (!uniform || array.length % 3 !== 0)
  14005. return;
  14006. this._gl.uniform3fv(uniform, array);
  14007. };
  14008. /**
  14009. * Set the value of an uniform to an array of number (stored as vec4)
  14010. * @param uniform defines the webGL uniform location where to store the value
  14011. * @param array defines the array of number to store
  14012. */
  14013. Engine.prototype.setArray4 = function (uniform, array) {
  14014. if (!uniform || array.length % 4 !== 0)
  14015. return;
  14016. this._gl.uniform4fv(uniform, array);
  14017. };
  14018. /**
  14019. * Set the value of an uniform to an array of float32 (stored as matrices)
  14020. * @param uniform defines the webGL uniform location where to store the value
  14021. * @param matrices defines the array of float32 to store
  14022. */
  14023. Engine.prototype.setMatrices = function (uniform, matrices) {
  14024. if (!uniform)
  14025. return;
  14026. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14027. };
  14028. /**
  14029. * Set the value of an uniform to a matrix
  14030. * @param uniform defines the webGL uniform location where to store the value
  14031. * @param matrix defines the matrix to store
  14032. */
  14033. Engine.prototype.setMatrix = function (uniform, matrix) {
  14034. if (!uniform)
  14035. return;
  14036. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14037. };
  14038. /**
  14039. * Set the value of an uniform to a matrix (3x3)
  14040. * @param uniform defines the webGL uniform location where to store the value
  14041. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14042. */
  14043. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14044. if (!uniform)
  14045. return;
  14046. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14047. };
  14048. /**
  14049. * Set the value of an uniform to a matrix (2x2)
  14050. * @param uniform defines the webGL uniform location where to store the value
  14051. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14052. */
  14053. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14054. if (!uniform)
  14055. return;
  14056. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14057. };
  14058. /**
  14059. * Set the value of an uniform to a number (int)
  14060. * @param uniform defines the webGL uniform location where to store the value
  14061. * @param value defines the int number to store
  14062. */
  14063. Engine.prototype.setInt = function (uniform, value) {
  14064. if (!uniform)
  14065. return;
  14066. this._gl.uniform1i(uniform, value);
  14067. };
  14068. /**
  14069. * Set the value of an uniform to a number (float)
  14070. * @param uniform defines the webGL uniform location where to store the value
  14071. * @param value defines the float number to store
  14072. */
  14073. Engine.prototype.setFloat = function (uniform, value) {
  14074. if (!uniform)
  14075. return;
  14076. this._gl.uniform1f(uniform, value);
  14077. };
  14078. /**
  14079. * Set the value of an uniform to a vec2
  14080. * @param uniform defines the webGL uniform location where to store the value
  14081. * @param x defines the 1st component of the value
  14082. * @param y defines the 2nd component of the value
  14083. */
  14084. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14085. if (!uniform)
  14086. return;
  14087. this._gl.uniform2f(uniform, x, y);
  14088. };
  14089. /**
  14090. * Set the value of an uniform to a vec3
  14091. * @param uniform defines the webGL uniform location where to store the value
  14092. * @param x defines the 1st component of the value
  14093. * @param y defines the 2nd component of the value
  14094. * @param z defines the 3rd component of the value
  14095. */
  14096. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14097. if (!uniform)
  14098. return;
  14099. this._gl.uniform3f(uniform, x, y, z);
  14100. };
  14101. /**
  14102. * Set the value of an uniform to a boolean
  14103. * @param uniform defines the webGL uniform location where to store the value
  14104. * @param bool defines the boolean to store
  14105. */
  14106. Engine.prototype.setBool = function (uniform, bool) {
  14107. if (!uniform)
  14108. return;
  14109. this._gl.uniform1i(uniform, bool);
  14110. };
  14111. /**
  14112. * Set the value of an uniform to a vec4
  14113. * @param uniform defines the webGL uniform location where to store the value
  14114. * @param x defines the 1st component of the value
  14115. * @param y defines the 2nd component of the value
  14116. * @param z defines the 3rd component of the value
  14117. * @param w defines the 4th component of the value
  14118. */
  14119. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14120. if (!uniform)
  14121. return;
  14122. this._gl.uniform4f(uniform, x, y, z, w);
  14123. };
  14124. /**
  14125. * Set the value of an uniform to a Color3
  14126. * @param uniform defines the webGL uniform location where to store the value
  14127. * @param color3 defines the color to store
  14128. */
  14129. Engine.prototype.setColor3 = function (uniform, color3) {
  14130. if (!uniform)
  14131. return;
  14132. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14133. };
  14134. /**
  14135. * Set the value of an uniform to a Color3 and an alpha value
  14136. * @param uniform defines the webGL uniform location where to store the value
  14137. * @param color3 defines the color to store
  14138. * @param alpha defines the alpha component to store
  14139. */
  14140. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14141. if (!uniform)
  14142. return;
  14143. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14144. };
  14145. /**
  14146. * Sets a Color4 on a uniform variable
  14147. * @param uniform defines the uniform location
  14148. * @param color4 defines the value to be set
  14149. */
  14150. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14151. if (!uniform)
  14152. return;
  14153. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14154. };
  14155. // States
  14156. /**
  14157. * Set various states to the webGL context
  14158. * @param culling defines backface culling state
  14159. * @param zOffset defines the value to apply to zOffset (0 by default)
  14160. * @param force defines if states must be applied even if cache is up to date
  14161. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14162. */
  14163. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14164. if (zOffset === void 0) { zOffset = 0; }
  14165. if (reverseSide === void 0) { reverseSide = false; }
  14166. // Culling
  14167. if (this._depthCullingState.cull !== culling || force) {
  14168. this._depthCullingState.cull = culling;
  14169. }
  14170. // Cull face
  14171. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14172. if (this._depthCullingState.cullFace !== cullFace || force) {
  14173. this._depthCullingState.cullFace = cullFace;
  14174. }
  14175. // Z offset
  14176. this.setZOffset(zOffset);
  14177. // Front face
  14178. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14179. if (this._depthCullingState.frontFace !== frontFace || force) {
  14180. this._depthCullingState.frontFace = frontFace;
  14181. }
  14182. };
  14183. /**
  14184. * Set the z offset to apply to current rendering
  14185. * @param value defines the offset to apply
  14186. */
  14187. Engine.prototype.setZOffset = function (value) {
  14188. this._depthCullingState.zOffset = value;
  14189. };
  14190. /**
  14191. * Gets the current value of the zOffset
  14192. * @returns the current zOffset state
  14193. */
  14194. Engine.prototype.getZOffset = function () {
  14195. return this._depthCullingState.zOffset;
  14196. };
  14197. /**
  14198. * Enable or disable depth buffering
  14199. * @param enable defines the state to set
  14200. */
  14201. Engine.prototype.setDepthBuffer = function (enable) {
  14202. this._depthCullingState.depthTest = enable;
  14203. };
  14204. /**
  14205. * Gets a boolean indicating if depth writing is enabled
  14206. * @returns the current depth writing state
  14207. */
  14208. Engine.prototype.getDepthWrite = function () {
  14209. return this._depthCullingState.depthMask;
  14210. };
  14211. /**
  14212. * Enable or disable depth writing
  14213. * @param enable defines the state to set
  14214. */
  14215. Engine.prototype.setDepthWrite = function (enable) {
  14216. this._depthCullingState.depthMask = enable;
  14217. };
  14218. /**
  14219. * Enable or disable color writing
  14220. * @param enable defines the state to set
  14221. */
  14222. Engine.prototype.setColorWrite = function (enable) {
  14223. this._gl.colorMask(enable, enable, enable, enable);
  14224. this._colorWrite = enable;
  14225. };
  14226. /**
  14227. * Gets a boolean indicating if color writing is enabled
  14228. * @returns the current color writing state
  14229. */
  14230. Engine.prototype.getColorWrite = function () {
  14231. return this._colorWrite;
  14232. };
  14233. /**
  14234. * Sets alpha constants used by some alpha blending modes
  14235. * @param r defines the red component
  14236. * @param g defines the green component
  14237. * @param b defines the blue component
  14238. * @param a defines the alpha component
  14239. */
  14240. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14241. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14242. };
  14243. /**
  14244. * Sets the current alpha mode
  14245. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14246. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14247. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14248. */
  14249. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14250. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14251. if (this._alphaMode === mode) {
  14252. return;
  14253. }
  14254. switch (mode) {
  14255. case Engine.ALPHA_DISABLE:
  14256. this._alphaState.alphaBlend = false;
  14257. break;
  14258. case Engine.ALPHA_PREMULTIPLIED:
  14259. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14260. this._alphaState.alphaBlend = true;
  14261. break;
  14262. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14263. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14264. this._alphaState.alphaBlend = true;
  14265. break;
  14266. case Engine.ALPHA_COMBINE:
  14267. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14268. this._alphaState.alphaBlend = true;
  14269. break;
  14270. case Engine.ALPHA_ONEONE:
  14271. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14272. this._alphaState.alphaBlend = true;
  14273. break;
  14274. case Engine.ALPHA_ADD:
  14275. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14276. this._alphaState.alphaBlend = true;
  14277. break;
  14278. case Engine.ALPHA_SUBTRACT:
  14279. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14280. this._alphaState.alphaBlend = true;
  14281. break;
  14282. case Engine.ALPHA_MULTIPLY:
  14283. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14284. this._alphaState.alphaBlend = true;
  14285. break;
  14286. case Engine.ALPHA_MAXIMIZED:
  14287. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14288. this._alphaState.alphaBlend = true;
  14289. break;
  14290. case Engine.ALPHA_INTERPOLATE:
  14291. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14292. this._alphaState.alphaBlend = true;
  14293. break;
  14294. case Engine.ALPHA_SCREENMODE:
  14295. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14296. this._alphaState.alphaBlend = true;
  14297. break;
  14298. }
  14299. if (!noDepthWriteChange) {
  14300. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14301. }
  14302. this._alphaMode = mode;
  14303. };
  14304. /**
  14305. * Gets the current alpha mode
  14306. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14307. * @returns the current alpha mode
  14308. */
  14309. Engine.prototype.getAlphaMode = function () {
  14310. return this._alphaMode;
  14311. };
  14312. // Textures
  14313. /**
  14314. * Clears the list of texture accessible through engine.
  14315. * This can help preventing texture load conflict due to name collision.
  14316. */
  14317. Engine.prototype.clearInternalTexturesCache = function () {
  14318. this._internalTexturesCache = [];
  14319. };
  14320. /**
  14321. * Force the entire cache to be cleared
  14322. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14323. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14324. */
  14325. Engine.prototype.wipeCaches = function (bruteForce) {
  14326. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14327. return;
  14328. }
  14329. this._currentEffect = null;
  14330. this._viewportCached.x = 0;
  14331. this._viewportCached.y = 0;
  14332. this._viewportCached.z = 0;
  14333. this._viewportCached.w = 0;
  14334. if (bruteForce) {
  14335. this.resetTextureCache();
  14336. this._currentProgram = null;
  14337. this._stencilState.reset();
  14338. this._depthCullingState.reset();
  14339. this.setDepthFunctionToLessOrEqual();
  14340. this._alphaState.reset();
  14341. this._unpackFlipYCached = null;
  14342. }
  14343. this._resetVertexBufferBinding();
  14344. this._cachedIndexBuffer = null;
  14345. this._cachedEffectForVertexBuffers = null;
  14346. this._unbindVertexArrayObject();
  14347. this.bindIndexBuffer(null);
  14348. };
  14349. /**
  14350. * Set the compressed texture format to use, based on the formats you have, and the formats
  14351. * supported by the hardware / browser.
  14352. *
  14353. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14354. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14355. * to API arguments needed to compressed textures. This puts the burden on the container
  14356. * generator to house the arcane code for determining these for current & future formats.
  14357. *
  14358. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14359. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14360. *
  14361. * Note: The result of this call is not taken into account when a texture is base64.
  14362. *
  14363. * @param formatsAvailable defines the list of those format families you have created
  14364. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14365. *
  14366. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14367. * @returns The extension selected.
  14368. */
  14369. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14370. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14371. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14372. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14373. return this._textureFormatInUse = this._texturesSupported[i];
  14374. }
  14375. }
  14376. }
  14377. // actively set format to nothing, to allow this to be called more than once
  14378. // and possibly fail the 2nd time
  14379. this._textureFormatInUse = null;
  14380. return null;
  14381. };
  14382. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14383. var gl = this._gl;
  14384. var magFilter = gl.NEAREST;
  14385. var minFilter = gl.NEAREST;
  14386. switch (samplingMode) {
  14387. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14388. magFilter = gl.LINEAR;
  14389. if (generateMipMaps) {
  14390. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14391. }
  14392. else {
  14393. minFilter = gl.LINEAR;
  14394. }
  14395. break;
  14396. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14397. magFilter = gl.LINEAR;
  14398. if (generateMipMaps) {
  14399. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14400. }
  14401. else {
  14402. minFilter = gl.LINEAR;
  14403. }
  14404. break;
  14405. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14406. magFilter = gl.NEAREST;
  14407. if (generateMipMaps) {
  14408. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14409. }
  14410. else {
  14411. minFilter = gl.NEAREST;
  14412. }
  14413. break;
  14414. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14415. magFilter = gl.NEAREST;
  14416. if (generateMipMaps) {
  14417. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14418. }
  14419. else {
  14420. minFilter = gl.NEAREST;
  14421. }
  14422. break;
  14423. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14424. magFilter = gl.NEAREST;
  14425. if (generateMipMaps) {
  14426. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14427. }
  14428. else {
  14429. minFilter = gl.LINEAR;
  14430. }
  14431. break;
  14432. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14433. magFilter = gl.NEAREST;
  14434. if (generateMipMaps) {
  14435. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14436. }
  14437. else {
  14438. minFilter = gl.LINEAR;
  14439. }
  14440. break;
  14441. case Engine.TEXTURE_NEAREST_LINEAR:
  14442. magFilter = gl.NEAREST;
  14443. minFilter = gl.LINEAR;
  14444. break;
  14445. case Engine.TEXTURE_NEAREST_NEAREST:
  14446. magFilter = gl.NEAREST;
  14447. minFilter = gl.NEAREST;
  14448. break;
  14449. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14450. magFilter = gl.LINEAR;
  14451. if (generateMipMaps) {
  14452. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14453. }
  14454. else {
  14455. minFilter = gl.NEAREST;
  14456. }
  14457. break;
  14458. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14459. magFilter = gl.LINEAR;
  14460. if (generateMipMaps) {
  14461. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14462. }
  14463. else {
  14464. minFilter = gl.NEAREST;
  14465. }
  14466. break;
  14467. case Engine.TEXTURE_LINEAR_LINEAR:
  14468. magFilter = gl.LINEAR;
  14469. minFilter = gl.LINEAR;
  14470. break;
  14471. case Engine.TEXTURE_LINEAR_NEAREST:
  14472. magFilter = gl.LINEAR;
  14473. minFilter = gl.NEAREST;
  14474. break;
  14475. }
  14476. return {
  14477. min: minFilter,
  14478. mag: magFilter
  14479. };
  14480. };
  14481. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14482. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14483. var img;
  14484. var onload = function () {
  14485. loadedImages[index] = img;
  14486. loadedImages._internalCount++;
  14487. if (scene) {
  14488. scene._removePendingData(img);
  14489. }
  14490. if (loadedImages._internalCount === 6) {
  14491. onfinish(loadedImages);
  14492. }
  14493. };
  14494. var onerror = function (message, exception) {
  14495. if (scene) {
  14496. scene._removePendingData(img);
  14497. }
  14498. if (onErrorCallBack) {
  14499. onErrorCallBack(message, exception);
  14500. }
  14501. };
  14502. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14503. if (scene) {
  14504. scene._addPendingData(img);
  14505. }
  14506. };
  14507. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14508. if (onError === void 0) { onError = null; }
  14509. var loadedImages = [];
  14510. loadedImages._internalCount = 0;
  14511. for (var index = 0; index < 6; index++) {
  14512. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14513. }
  14514. };
  14515. ;
  14516. /** @hidden */
  14517. Engine.prototype._createTexture = function () {
  14518. var texture = this._gl.createTexture();
  14519. if (!texture) {
  14520. throw new Error("Unable to create texture");
  14521. }
  14522. return texture;
  14523. };
  14524. /**
  14525. * Usually called from BABYLON.Texture.ts.
  14526. * Passed information to create a WebGLTexture
  14527. * @param urlArg defines a value which contains one of the following:
  14528. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14529. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14530. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14531. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14532. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14533. * @param scene needed for loading to the correct scene
  14534. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14535. * @param onLoad optional callback to be called upon successful completion
  14536. * @param onError optional callback to be called upon failure
  14537. * @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
  14538. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14539. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14540. * @param forcedExtension defines the extension to use to pick the right loader
  14541. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14542. */
  14543. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14544. var _this = this;
  14545. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14546. if (onLoad === void 0) { onLoad = null; }
  14547. if (onError === void 0) { onError = null; }
  14548. if (buffer === void 0) { buffer = null; }
  14549. if (fallback === void 0) { fallback = null; }
  14550. if (format === void 0) { format = null; }
  14551. if (forcedExtension === void 0) { forcedExtension = null; }
  14552. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14553. var fromData = url.substr(0, 5) === "data:";
  14554. var fromBlob = url.substr(0, 5) === "blob:";
  14555. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14556. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14557. // establish the file extension, if possible
  14558. var lastDot = url.lastIndexOf('.');
  14559. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14560. var loader = null;
  14561. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14562. var availableLoader = _a[_i];
  14563. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14564. loader = availableLoader;
  14565. break;
  14566. }
  14567. }
  14568. if (loader) {
  14569. url = loader.transformUrl(url, this._textureFormatInUse);
  14570. }
  14571. if (scene) {
  14572. scene._addPendingData(texture);
  14573. }
  14574. texture.url = url;
  14575. texture.generateMipMaps = !noMipmap;
  14576. texture.samplingMode = samplingMode;
  14577. texture.invertY = invertY;
  14578. if (!this._doNotHandleContextLost) {
  14579. // Keep a link to the buffer only if we plan to handle context lost
  14580. texture._buffer = buffer;
  14581. }
  14582. var onLoadObserver = null;
  14583. if (onLoad && !fallback) {
  14584. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14585. }
  14586. if (!fallback)
  14587. this._internalTexturesCache.push(texture);
  14588. var onInternalError = function (message, exception) {
  14589. if (scene) {
  14590. scene._removePendingData(texture);
  14591. }
  14592. var customFallback = false;
  14593. if (loader) {
  14594. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14595. if (fallbackUrl) {
  14596. // Add Back
  14597. customFallback = true;
  14598. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14599. }
  14600. }
  14601. if (!customFallback) {
  14602. if (onLoadObserver) {
  14603. texture.onLoadedObservable.remove(onLoadObserver);
  14604. }
  14605. if (BABYLON.Tools.UseFallbackTexture) {
  14606. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14607. }
  14608. }
  14609. if (onError) {
  14610. onError(message || "Unknown error", exception);
  14611. }
  14612. };
  14613. // processing for non-image formats
  14614. if (loader) {
  14615. var callback = function (data) {
  14616. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14617. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14618. done();
  14619. return false;
  14620. }, samplingMode);
  14621. });
  14622. };
  14623. if (!buffer) {
  14624. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14625. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14626. });
  14627. }
  14628. else {
  14629. callback(buffer);
  14630. }
  14631. }
  14632. else {
  14633. var onload = function (img) {
  14634. if (fromBlob && !_this._doNotHandleContextLost) {
  14635. // We need to store the image if we need to rebuild the texture
  14636. // in case of a webgl context lost
  14637. texture._buffer = img;
  14638. }
  14639. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14640. var gl = _this._gl;
  14641. var isPot = (img.width === potWidth && img.height === potHeight);
  14642. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14643. if (isPot) {
  14644. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14645. return false;
  14646. }
  14647. var maxTextureSize = _this._caps.maxTextureSize;
  14648. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14649. _this._prepareWorkingCanvas();
  14650. if (!_this._workingCanvas || !_this._workingContext) {
  14651. return false;
  14652. }
  14653. _this._workingCanvas.width = potWidth;
  14654. _this._workingCanvas.height = potHeight;
  14655. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14656. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14657. texture.width = potWidth;
  14658. texture.height = potHeight;
  14659. return false;
  14660. }
  14661. else {
  14662. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14663. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14664. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14665. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14666. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14667. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14668. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14669. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14670. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14671. _this._releaseTexture(source_1);
  14672. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14673. continuationCallback();
  14674. });
  14675. }
  14676. return true;
  14677. }, samplingMode);
  14678. };
  14679. if (!fromData || isBase64) {
  14680. if (buffer instanceof HTMLImageElement) {
  14681. onload(buffer);
  14682. }
  14683. else {
  14684. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14685. }
  14686. }
  14687. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14688. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14689. }
  14690. else {
  14691. onload(buffer);
  14692. }
  14693. }
  14694. return texture;
  14695. };
  14696. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14697. var _this = this;
  14698. var rtt = this.createRenderTargetTexture({
  14699. width: destination.width,
  14700. height: destination.height,
  14701. }, {
  14702. generateMipMaps: false,
  14703. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14704. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14705. generateDepthBuffer: false,
  14706. generateStencilBuffer: false
  14707. });
  14708. if (!this._rescalePostProcess) {
  14709. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14710. }
  14711. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14712. _this._rescalePostProcess.onApply = function (effect) {
  14713. effect._bindTexture("textureSampler", source);
  14714. };
  14715. var hostingScene = scene;
  14716. if (!hostingScene) {
  14717. hostingScene = _this.scenes[_this.scenes.length - 1];
  14718. }
  14719. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14720. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14721. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14722. _this.unBindFramebuffer(rtt);
  14723. _this._releaseTexture(rtt);
  14724. if (onComplete) {
  14725. onComplete();
  14726. }
  14727. });
  14728. };
  14729. /**
  14730. * Update a raw texture
  14731. * @param texture defines the texture to update
  14732. * @param data defines the data to store in the texture
  14733. * @param format defines the format of the data
  14734. * @param invertY defines if data must be stored with Y axis inverted
  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. */
  14738. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14739. if (compression === void 0) { compression = null; }
  14740. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14741. if (!texture) {
  14742. return;
  14743. }
  14744. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14745. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14746. // babylon's internalFormat but gl's texImage2D format
  14747. var internalFormat = this._getInternalFormat(format);
  14748. var textureType = this._getWebGLTextureType(type);
  14749. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14750. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14751. if (!this._doNotHandleContextLost) {
  14752. texture._bufferView = data;
  14753. texture.format = format;
  14754. texture.type = type;
  14755. texture.invertY = invertY;
  14756. texture._compression = compression;
  14757. }
  14758. if (texture.width % 4 !== 0) {
  14759. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14760. }
  14761. if (compression && data) {
  14762. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14763. }
  14764. else {
  14765. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14766. }
  14767. if (texture.generateMipMaps) {
  14768. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14769. }
  14770. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14771. // this.resetTextureCache();
  14772. texture.isReady = true;
  14773. };
  14774. /**
  14775. * Creates a raw texture
  14776. * @param data defines the data to store in the texture
  14777. * @param width defines the width of the texture
  14778. * @param height defines the height of the texture
  14779. * @param format defines the format of the data
  14780. * @param generateMipMaps defines if the engine should generate the mip levels
  14781. * @param invertY defines if data must be stored with Y axis inverted
  14782. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14783. * @param compression defines the compression used (null by default)
  14784. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14785. * @returns the raw texture inside an InternalTexture
  14786. */
  14787. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14788. if (compression === void 0) { compression = null; }
  14789. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14790. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14791. texture.baseWidth = width;
  14792. texture.baseHeight = height;
  14793. texture.width = width;
  14794. texture.height = height;
  14795. texture.format = format;
  14796. texture.generateMipMaps = generateMipMaps;
  14797. texture.samplingMode = samplingMode;
  14798. texture.invertY = invertY;
  14799. texture._compression = compression;
  14800. texture.type = type;
  14801. if (!this._doNotHandleContextLost) {
  14802. texture._bufferView = data;
  14803. }
  14804. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14805. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14806. // Filters
  14807. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14808. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14809. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14810. if (generateMipMaps) {
  14811. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14812. }
  14813. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14814. this._internalTexturesCache.push(texture);
  14815. return texture;
  14816. };
  14817. /** @hidden */
  14818. Engine.prototype._unpackFlipY = function (value) {
  14819. if (this._unpackFlipYCached !== value) {
  14820. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14821. if (this.enableUnpackFlipYCached) {
  14822. this._unpackFlipYCached = value;
  14823. }
  14824. }
  14825. };
  14826. /** @hidden */
  14827. Engine.prototype._getUnpackAlignement = function () {
  14828. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14829. };
  14830. /**
  14831. * Creates a dynamic texture
  14832. * @param width defines the width of the texture
  14833. * @param height defines the height of the texture
  14834. * @param generateMipMaps defines if the engine should generate the mip levels
  14835. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14836. * @returns the dynamic texture inside an InternalTexture
  14837. */
  14838. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14839. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14840. texture.baseWidth = width;
  14841. texture.baseHeight = height;
  14842. if (generateMipMaps) {
  14843. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14844. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14845. }
  14846. // this.resetTextureCache();
  14847. texture.width = width;
  14848. texture.height = height;
  14849. texture.isReady = false;
  14850. texture.generateMipMaps = generateMipMaps;
  14851. texture.samplingMode = samplingMode;
  14852. this.updateTextureSamplingMode(samplingMode, texture);
  14853. this._internalTexturesCache.push(texture);
  14854. return texture;
  14855. };
  14856. /**
  14857. * Update the sampling mode of a given texture
  14858. * @param samplingMode defines the required sampling mode
  14859. * @param texture defines the texture to update
  14860. */
  14861. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14862. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14863. if (texture.isCube) {
  14864. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14865. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14866. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14867. }
  14868. else if (texture.is3D) {
  14869. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14870. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14871. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14872. }
  14873. else {
  14874. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14875. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14876. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14877. }
  14878. texture.samplingMode = samplingMode;
  14879. };
  14880. /**
  14881. * Update the content of a dynamic texture
  14882. * @param texture defines the texture to update
  14883. * @param canvas defines the canvas containing the source
  14884. * @param invertY defines if data must be stored with Y axis inverted
  14885. * @param premulAlpha defines if alpha is stored as premultiplied
  14886. * @param format defines the format of the data
  14887. */
  14888. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14889. if (premulAlpha === void 0) { premulAlpha = false; }
  14890. if (!texture) {
  14891. return;
  14892. }
  14893. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14894. this._unpackFlipY(invertY);
  14895. if (premulAlpha) {
  14896. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14897. }
  14898. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14899. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14900. if (texture.generateMipMaps) {
  14901. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14902. }
  14903. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14904. if (premulAlpha) {
  14905. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14906. }
  14907. texture.isReady = true;
  14908. };
  14909. /**
  14910. * Update a video texture
  14911. * @param texture defines the texture to update
  14912. * @param video defines the video element to use
  14913. * @param invertY defines if data must be stored with Y axis inverted
  14914. */
  14915. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14916. if (!texture || texture._isDisabled) {
  14917. return;
  14918. }
  14919. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14920. this._unpackFlipY(!invertY); // Video are upside down by default
  14921. try {
  14922. // Testing video texture support
  14923. if (this._videoTextureSupported === undefined) {
  14924. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14925. if (this._gl.getError() !== 0) {
  14926. this._videoTextureSupported = false;
  14927. }
  14928. else {
  14929. this._videoTextureSupported = true;
  14930. }
  14931. }
  14932. // Copy video through the current working canvas if video texture is not supported
  14933. if (!this._videoTextureSupported) {
  14934. if (!texture._workingCanvas) {
  14935. texture._workingCanvas = document.createElement("canvas");
  14936. var context = texture._workingCanvas.getContext("2d");
  14937. if (!context) {
  14938. throw new Error("Unable to get 2d context");
  14939. }
  14940. texture._workingContext = context;
  14941. texture._workingCanvas.width = texture.width;
  14942. texture._workingCanvas.height = texture.height;
  14943. }
  14944. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14945. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14946. }
  14947. else {
  14948. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14949. }
  14950. if (texture.generateMipMaps) {
  14951. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14952. }
  14953. if (!wasPreviouslyBound) {
  14954. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14955. }
  14956. // this.resetTextureCache();
  14957. texture.isReady = true;
  14958. }
  14959. catch (ex) {
  14960. // Something unexpected
  14961. // Let's disable the texture
  14962. texture._isDisabled = true;
  14963. }
  14964. };
  14965. /**
  14966. * Updates a depth texture Comparison Mode and Function.
  14967. * If the comparison Function is equal to 0, the mode will be set to none.
  14968. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14969. * @param texture The texture to set the comparison function for
  14970. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14971. */
  14972. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14973. if (this.webGLVersion === 1) {
  14974. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14975. return;
  14976. }
  14977. var gl = this._gl;
  14978. if (texture.isCube) {
  14979. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14980. if (comparisonFunction === 0) {
  14981. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14982. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14983. }
  14984. else {
  14985. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14986. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14987. }
  14988. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14989. }
  14990. else {
  14991. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14992. if (comparisonFunction === 0) {
  14993. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14994. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14995. }
  14996. else {
  14997. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14999. }
  15000. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15001. }
  15002. texture._comparisonFunction = comparisonFunction;
  15003. };
  15004. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15005. var width = size.width || size;
  15006. var height = size.height || size;
  15007. internalTexture.baseWidth = width;
  15008. internalTexture.baseHeight = height;
  15009. internalTexture.width = width;
  15010. internalTexture.height = height;
  15011. internalTexture.isReady = true;
  15012. internalTexture.samples = 1;
  15013. internalTexture.generateMipMaps = false;
  15014. internalTexture._generateDepthBuffer = true;
  15015. internalTexture._generateStencilBuffer = generateStencil;
  15016. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15017. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15018. internalTexture._comparisonFunction = comparisonFunction;
  15019. var gl = this._gl;
  15020. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15021. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15022. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15023. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15024. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15025. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15026. if (comparisonFunction === 0) {
  15027. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15028. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15029. }
  15030. else {
  15031. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15032. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15033. }
  15034. };
  15035. /**
  15036. * Creates a depth stencil texture.
  15037. * This is only available in WebGL 2 or with the depth texture extension available.
  15038. * @param size The size of face edge in the texture.
  15039. * @param options The options defining the texture.
  15040. * @returns The texture
  15041. */
  15042. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15043. if (options.isCube) {
  15044. var width = size.width || size;
  15045. return this._createDepthStencilCubeTexture(width, options);
  15046. }
  15047. else {
  15048. return this._createDepthStencilTexture(size, options);
  15049. }
  15050. };
  15051. /**
  15052. * Creates a depth stencil texture.
  15053. * This is only available in WebGL 2 or with the depth texture extension available.
  15054. * @param size The size of face edge in the texture.
  15055. * @param options The options defining the texture.
  15056. * @returns The texture
  15057. */
  15058. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15059. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15060. if (!this._caps.depthTextureExtension) {
  15061. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15062. return internalTexture;
  15063. }
  15064. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15065. var gl = this._gl;
  15066. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15067. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15068. if (this.webGLVersion > 1) {
  15069. if (internalOptions.generateStencil) {
  15070. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15071. }
  15072. else {
  15073. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15074. }
  15075. }
  15076. else {
  15077. if (internalOptions.generateStencil) {
  15078. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15079. }
  15080. else {
  15081. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15082. }
  15083. }
  15084. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15085. return internalTexture;
  15086. };
  15087. /**
  15088. * Creates a depth stencil cube texture.
  15089. * This is only available in WebGL 2.
  15090. * @param size The size of face edge in the cube texture.
  15091. * @param options The options defining the cube texture.
  15092. * @returns The cube texture
  15093. */
  15094. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15095. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15096. internalTexture.isCube = true;
  15097. if (this.webGLVersion === 1) {
  15098. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15099. return internalTexture;
  15100. }
  15101. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15102. var gl = this._gl;
  15103. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15104. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15105. // Create the depth/stencil buffer
  15106. for (var face = 0; face < 6; face++) {
  15107. if (internalOptions.generateStencil) {
  15108. 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);
  15109. }
  15110. else {
  15111. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15112. }
  15113. }
  15114. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15115. return internalTexture;
  15116. };
  15117. /**
  15118. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15119. * @param renderTarget The render target to set the frame buffer for
  15120. */
  15121. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15122. // Create the framebuffer
  15123. var internalTexture = renderTarget.getInternalTexture();
  15124. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15125. return;
  15126. }
  15127. var gl = this._gl;
  15128. var depthStencilTexture = renderTarget.depthStencilTexture;
  15129. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15130. if (depthStencilTexture.isCube) {
  15131. if (depthStencilTexture._generateStencilBuffer) {
  15132. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15133. }
  15134. else {
  15135. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15136. }
  15137. }
  15138. else {
  15139. if (depthStencilTexture._generateStencilBuffer) {
  15140. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15141. }
  15142. else {
  15143. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15144. }
  15145. }
  15146. this.bindUnboundFramebuffer(null);
  15147. };
  15148. /**
  15149. * Creates a new render target texture
  15150. * @param size defines the size of the texture
  15151. * @param options defines the options used to create the texture
  15152. * @returns a new render target texture stored in an InternalTexture
  15153. */
  15154. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15155. var fullOptions = new RenderTargetCreationOptions();
  15156. if (options !== undefined && typeof options === "object") {
  15157. fullOptions.generateMipMaps = options.generateMipMaps;
  15158. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15159. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15160. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15161. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15162. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15163. }
  15164. else {
  15165. fullOptions.generateMipMaps = options;
  15166. fullOptions.generateDepthBuffer = true;
  15167. fullOptions.generateStencilBuffer = false;
  15168. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15169. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15170. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15171. }
  15172. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15173. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15174. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15175. }
  15176. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15177. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15178. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15179. }
  15180. var gl = this._gl;
  15181. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15182. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15183. var width = size.width || size;
  15184. var height = size.height || size;
  15185. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15186. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15187. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15188. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15189. }
  15190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15191. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15192. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15194. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15195. // Create the framebuffer
  15196. var currentFrameBuffer = this._currentFramebuffer;
  15197. var framebuffer = gl.createFramebuffer();
  15198. this.bindUnboundFramebuffer(framebuffer);
  15199. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15200. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15201. if (fullOptions.generateMipMaps) {
  15202. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15203. }
  15204. // Unbind
  15205. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15206. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15207. this.bindUnboundFramebuffer(currentFrameBuffer);
  15208. texture._framebuffer = framebuffer;
  15209. texture.baseWidth = width;
  15210. texture.baseHeight = height;
  15211. texture.width = width;
  15212. texture.height = height;
  15213. texture.isReady = true;
  15214. texture.samples = 1;
  15215. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15216. texture.samplingMode = fullOptions.samplingMode;
  15217. texture.type = fullOptions.type;
  15218. texture.format = fullOptions.format;
  15219. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15220. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15221. // this.resetTextureCache();
  15222. this._internalTexturesCache.push(texture);
  15223. return texture;
  15224. };
  15225. /**
  15226. * Create a multi render target texture
  15227. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15228. * @param size defines the size of the texture
  15229. * @param options defines the creation options
  15230. * @returns the cube texture as an InternalTexture
  15231. */
  15232. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15233. var generateMipMaps = false;
  15234. var generateDepthBuffer = true;
  15235. var generateStencilBuffer = false;
  15236. var generateDepthTexture = false;
  15237. var textureCount = 1;
  15238. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15239. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15240. var types = new Array();
  15241. var samplingModes = new Array();
  15242. if (options !== undefined) {
  15243. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15244. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15245. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15246. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15247. textureCount = options.textureCount || 1;
  15248. if (options.types) {
  15249. types = options.types;
  15250. }
  15251. if (options.samplingModes) {
  15252. samplingModes = options.samplingModes;
  15253. }
  15254. }
  15255. var gl = this._gl;
  15256. // Create the framebuffer
  15257. var framebuffer = gl.createFramebuffer();
  15258. this.bindUnboundFramebuffer(framebuffer);
  15259. var width = size.width || size;
  15260. var height = size.height || size;
  15261. var textures = [];
  15262. var attachments = [];
  15263. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15264. for (var i = 0; i < textureCount; i++) {
  15265. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15266. var type = types[i] || defaultType;
  15267. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15268. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15269. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15270. }
  15271. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15272. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15273. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15274. }
  15275. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15276. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15277. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15278. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15279. }
  15280. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15281. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15282. textures.push(texture);
  15283. attachments.push(attachment);
  15284. gl.activeTexture(gl["TEXTURE" + i]);
  15285. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15286. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15287. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15288. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15289. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15290. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15291. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15292. if (generateMipMaps) {
  15293. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15294. }
  15295. // Unbind
  15296. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15297. texture._framebuffer = framebuffer;
  15298. texture._depthStencilBuffer = depthStencilBuffer;
  15299. texture.baseWidth = width;
  15300. texture.baseHeight = height;
  15301. texture.width = width;
  15302. texture.height = height;
  15303. texture.isReady = true;
  15304. texture.samples = 1;
  15305. texture.generateMipMaps = generateMipMaps;
  15306. texture.samplingMode = samplingMode;
  15307. texture.type = type;
  15308. texture._generateDepthBuffer = generateDepthBuffer;
  15309. texture._generateStencilBuffer = generateStencilBuffer;
  15310. texture._attachments = attachments;
  15311. this._internalTexturesCache.push(texture);
  15312. }
  15313. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15314. // Depth texture
  15315. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15316. gl.activeTexture(gl.TEXTURE0);
  15317. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15318. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15319. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15320. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15321. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15322. 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);
  15323. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15324. depthTexture._framebuffer = framebuffer;
  15325. depthTexture.baseWidth = width;
  15326. depthTexture.baseHeight = height;
  15327. depthTexture.width = width;
  15328. depthTexture.height = height;
  15329. depthTexture.isReady = true;
  15330. depthTexture.samples = 1;
  15331. depthTexture.generateMipMaps = generateMipMaps;
  15332. depthTexture.samplingMode = gl.NEAREST;
  15333. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15334. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15335. textures.push(depthTexture);
  15336. this._internalTexturesCache.push(depthTexture);
  15337. }
  15338. gl.drawBuffers(attachments);
  15339. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15340. this.bindUnboundFramebuffer(null);
  15341. this.resetTextureCache();
  15342. return textures;
  15343. };
  15344. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15345. if (samples === void 0) { samples = 1; }
  15346. var depthStencilBuffer = null;
  15347. var gl = this._gl;
  15348. // Create the depth/stencil buffer
  15349. if (generateStencilBuffer) {
  15350. depthStencilBuffer = gl.createRenderbuffer();
  15351. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15352. if (samples > 1) {
  15353. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15354. }
  15355. else {
  15356. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15357. }
  15358. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15359. }
  15360. else if (generateDepthBuffer) {
  15361. depthStencilBuffer = gl.createRenderbuffer();
  15362. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15363. if (samples > 1) {
  15364. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15365. }
  15366. else {
  15367. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15368. }
  15369. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15370. }
  15371. return depthStencilBuffer;
  15372. };
  15373. /**
  15374. * Updates the sample count of a render target texture
  15375. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15376. * @param texture defines the texture to update
  15377. * @param samples defines the sample count to set
  15378. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15379. */
  15380. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15381. if (this.webGLVersion < 2 || !texture) {
  15382. return 1;
  15383. }
  15384. if (texture.samples === samples) {
  15385. return samples;
  15386. }
  15387. var gl = this._gl;
  15388. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15389. // Dispose previous render buffers
  15390. if (texture._depthStencilBuffer) {
  15391. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15392. texture._depthStencilBuffer = null;
  15393. }
  15394. if (texture._MSAAFramebuffer) {
  15395. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15396. texture._MSAAFramebuffer = null;
  15397. }
  15398. if (texture._MSAARenderBuffer) {
  15399. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15400. texture._MSAARenderBuffer = null;
  15401. }
  15402. if (samples > 1) {
  15403. var framebuffer = gl.createFramebuffer();
  15404. if (!framebuffer) {
  15405. throw new Error("Unable to create multi sampled framebuffer");
  15406. }
  15407. texture._MSAAFramebuffer = framebuffer;
  15408. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15409. var colorRenderbuffer = gl.createRenderbuffer();
  15410. if (!colorRenderbuffer) {
  15411. throw new Error("Unable to create multi sampled framebuffer");
  15412. }
  15413. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15414. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15415. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15416. texture._MSAARenderBuffer = colorRenderbuffer;
  15417. }
  15418. else {
  15419. this.bindUnboundFramebuffer(texture._framebuffer);
  15420. }
  15421. texture.samples = samples;
  15422. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15423. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15424. this.bindUnboundFramebuffer(null);
  15425. return samples;
  15426. };
  15427. /**
  15428. * Update the sample count for a given multiple render target texture
  15429. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15430. * @param textures defines the textures to update
  15431. * @param samples defines the sample count to set
  15432. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15433. */
  15434. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15435. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15436. return 1;
  15437. }
  15438. if (textures[0].samples === samples) {
  15439. return samples;
  15440. }
  15441. var gl = this._gl;
  15442. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15443. // Dispose previous render buffers
  15444. if (textures[0]._depthStencilBuffer) {
  15445. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15446. textures[0]._depthStencilBuffer = null;
  15447. }
  15448. if (textures[0]._MSAAFramebuffer) {
  15449. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15450. textures[0]._MSAAFramebuffer = null;
  15451. }
  15452. for (var i = 0; i < textures.length; i++) {
  15453. if (textures[i]._MSAARenderBuffer) {
  15454. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15455. textures[i]._MSAARenderBuffer = null;
  15456. }
  15457. }
  15458. if (samples > 1) {
  15459. var framebuffer = gl.createFramebuffer();
  15460. if (!framebuffer) {
  15461. throw new Error("Unable to create multi sampled framebuffer");
  15462. }
  15463. this.bindUnboundFramebuffer(framebuffer);
  15464. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15465. var attachments = [];
  15466. for (var i = 0; i < textures.length; i++) {
  15467. var texture = textures[i];
  15468. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15469. var colorRenderbuffer = gl.createRenderbuffer();
  15470. if (!colorRenderbuffer) {
  15471. throw new Error("Unable to create multi sampled framebuffer");
  15472. }
  15473. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15474. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15475. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15476. texture._MSAAFramebuffer = framebuffer;
  15477. texture._MSAARenderBuffer = colorRenderbuffer;
  15478. texture.samples = samples;
  15479. texture._depthStencilBuffer = depthStencilBuffer;
  15480. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15481. attachments.push(attachment);
  15482. }
  15483. gl.drawBuffers(attachments);
  15484. }
  15485. else {
  15486. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15487. }
  15488. this.bindUnboundFramebuffer(null);
  15489. return samples;
  15490. };
  15491. /** @hidden */
  15492. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15493. if (faceIndex === void 0) { faceIndex = 0; }
  15494. if (lod === void 0) { lod = 0; }
  15495. var gl = this._gl;
  15496. var target = gl.TEXTURE_2D;
  15497. if (texture.isCube) {
  15498. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15499. }
  15500. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15501. };
  15502. /** @hidden */
  15503. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15504. if (faceIndex === void 0) { faceIndex = 0; }
  15505. if (lod === void 0) { lod = 0; }
  15506. var gl = this._gl;
  15507. var textureType = this._getWebGLTextureType(texture.type);
  15508. var format = this._getInternalFormat(texture.format);
  15509. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15510. this._unpackFlipY(texture.invertY);
  15511. var target = gl.TEXTURE_2D;
  15512. if (texture.isCube) {
  15513. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15514. }
  15515. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15516. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15517. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15518. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15519. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15520. };
  15521. /** @hidden */
  15522. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15523. if (faceIndex === void 0) { faceIndex = 0; }
  15524. if (lod === void 0) { lod = 0; }
  15525. var gl = this._gl;
  15526. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15527. this._bindTextureDirectly(bindTarget, texture, true);
  15528. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15529. this._bindTextureDirectly(bindTarget, null, true);
  15530. };
  15531. /** @hidden */
  15532. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15533. if (faceIndex === void 0) { faceIndex = 0; }
  15534. if (lod === void 0) { lod = 0; }
  15535. var gl = this._gl;
  15536. var textureType = this._getWebGLTextureType(texture.type);
  15537. var format = this._getInternalFormat(texture.format);
  15538. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15539. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15540. this._bindTextureDirectly(bindTarget, texture, true);
  15541. this._unpackFlipY(texture.invertY);
  15542. var target = gl.TEXTURE_2D;
  15543. if (texture.isCube) {
  15544. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15545. }
  15546. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15547. this._bindTextureDirectly(bindTarget, null, true);
  15548. };
  15549. /**
  15550. * Creates a new render target cube texture
  15551. * @param size defines the size of the texture
  15552. * @param options defines the options used to create the texture
  15553. * @returns a new render target cube texture stored in an InternalTexture
  15554. */
  15555. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15556. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15557. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15558. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15559. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15560. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15561. }
  15562. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15563. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15564. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15565. }
  15566. var gl = this._gl;
  15567. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15568. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15569. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15570. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15571. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15572. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15573. }
  15574. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15575. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15576. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15577. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15578. for (var face = 0; face < 6; face++) {
  15579. 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);
  15580. }
  15581. // Create the framebuffer
  15582. var framebuffer = gl.createFramebuffer();
  15583. this.bindUnboundFramebuffer(framebuffer);
  15584. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15585. // MipMaps
  15586. if (fullOptions.generateMipMaps) {
  15587. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15588. }
  15589. // Unbind
  15590. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15591. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15592. this.bindUnboundFramebuffer(null);
  15593. texture._framebuffer = framebuffer;
  15594. texture.width = size;
  15595. texture.height = size;
  15596. texture.isReady = true;
  15597. texture.isCube = true;
  15598. texture.samples = 1;
  15599. texture.generateMipMaps = fullOptions.generateMipMaps;
  15600. texture.samplingMode = fullOptions.samplingMode;
  15601. texture.type = fullOptions.type;
  15602. texture.format = fullOptions.format;
  15603. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15604. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15605. this._internalTexturesCache.push(texture);
  15606. return texture;
  15607. };
  15608. /**
  15609. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15610. * @param rootUrl defines the url where the file to load is located
  15611. * @param scene defines the current scene
  15612. * @param lodScale defines scale to apply to the mip map selection
  15613. * @param lodOffset defines offset to apply to the mip map selection
  15614. * @param onLoad defines an optional callback raised when the texture is loaded
  15615. * @param onError defines an optional callback raised if there is an issue to load the texture
  15616. * @param format defines the format of the data
  15617. * @param forcedExtension defines the extension to use to pick the right loader
  15618. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15619. * @returns the cube texture as an InternalTexture
  15620. */
  15621. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15622. var _this = this;
  15623. if (onLoad === void 0) { onLoad = null; }
  15624. if (onError === void 0) { onError = null; }
  15625. if (forcedExtension === void 0) { forcedExtension = null; }
  15626. if (createPolynomials === void 0) { createPolynomials = true; }
  15627. var callback = function (loadData) {
  15628. if (!loadData) {
  15629. if (onLoad) {
  15630. onLoad(null);
  15631. }
  15632. return;
  15633. }
  15634. var texture = loadData.texture;
  15635. if (!createPolynomials) {
  15636. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15637. }
  15638. else if (loadData.info.sphericalPolynomial) {
  15639. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15640. }
  15641. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15642. if (_this._caps.textureLOD) {
  15643. // Do not add extra process if texture lod is supported.
  15644. if (onLoad) {
  15645. onLoad(texture);
  15646. }
  15647. return;
  15648. }
  15649. var mipSlices = 3;
  15650. var gl = _this._gl;
  15651. var width = loadData.width;
  15652. if (!width) {
  15653. return;
  15654. }
  15655. var textures = [];
  15656. for (var i = 0; i < mipSlices; i++) {
  15657. //compute LOD from even spacing in smoothness (matching shader calculation)
  15658. var smoothness = i / (mipSlices - 1);
  15659. var roughness = 1 - smoothness;
  15660. var minLODIndex = lodOffset; // roughness = 0
  15661. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15662. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15663. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15664. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15665. glTextureFromLod.type = texture.type;
  15666. glTextureFromLod.format = texture.format;
  15667. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15668. glTextureFromLod.height = glTextureFromLod.width;
  15669. glTextureFromLod.isCube = true;
  15670. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15671. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15672. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15673. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15674. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15675. if (loadData.isDDS) {
  15676. var info = loadData.info;
  15677. var data = loadData.data;
  15678. _this._unpackFlipY(info.isCompressed);
  15679. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15680. }
  15681. else {
  15682. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15683. }
  15684. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15685. // Wrap in a base texture for easy binding.
  15686. var lodTexture = new BABYLON.BaseTexture(scene);
  15687. lodTexture.isCube = true;
  15688. lodTexture._texture = glTextureFromLod;
  15689. glTextureFromLod.isReady = true;
  15690. textures.push(lodTexture);
  15691. }
  15692. texture._lodTextureHigh = textures[2];
  15693. texture._lodTextureMid = textures[1];
  15694. texture._lodTextureLow = textures[0];
  15695. if (onLoad) {
  15696. onLoad(texture);
  15697. }
  15698. };
  15699. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15700. };
  15701. /**
  15702. * Creates a cube texture
  15703. * @param rootUrl defines the url where the files to load is located
  15704. * @param scene defines the current scene
  15705. * @param files defines the list of files to load (1 per face)
  15706. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15707. * @param onLoad defines an optional callback raised when the texture is loaded
  15708. * @param onError defines an optional callback raised if there is an issue to load the texture
  15709. * @param format defines the format of the data
  15710. * @param forcedExtension defines the extension to use to pick the right loader
  15711. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15712. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15713. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15714. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15715. * @returns the cube texture as an InternalTexture
  15716. */
  15717. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15718. var _this = this;
  15719. if (onLoad === void 0) { onLoad = null; }
  15720. if (onError === void 0) { onError = null; }
  15721. if (forcedExtension === void 0) { forcedExtension = null; }
  15722. if (createPolynomials === void 0) { createPolynomials = false; }
  15723. if (lodScale === void 0) { lodScale = 0; }
  15724. if (lodOffset === void 0) { lodOffset = 0; }
  15725. if (fallback === void 0) { fallback = null; }
  15726. var gl = this._gl;
  15727. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15728. texture.isCube = true;
  15729. texture.url = rootUrl;
  15730. texture.generateMipMaps = !noMipmap;
  15731. texture._lodGenerationScale = lodScale;
  15732. texture._lodGenerationOffset = lodOffset;
  15733. if (!this._doNotHandleContextLost) {
  15734. texture._extension = forcedExtension;
  15735. texture._files = files;
  15736. }
  15737. var lastDot = rootUrl.lastIndexOf('.');
  15738. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15739. var loader = null;
  15740. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15741. var availableLoader = _a[_i];
  15742. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15743. loader = availableLoader;
  15744. break;
  15745. }
  15746. }
  15747. var onInternalError = function (request, exception) {
  15748. if (loader) {
  15749. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15750. if (fallbackUrl) {
  15751. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15752. }
  15753. }
  15754. if (onError && request) {
  15755. onError(request.status + " " + request.statusText, exception);
  15756. }
  15757. };
  15758. if (loader) {
  15759. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15760. var onloaddata = function (data) {
  15761. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15762. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15763. };
  15764. if (files && files.length === 6) {
  15765. if (loader.supportCascades) {
  15766. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15767. }
  15768. else if (onError) {
  15769. onError("Textures type does not support cascades.");
  15770. }
  15771. }
  15772. else {
  15773. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15774. }
  15775. }
  15776. else {
  15777. if (!files) {
  15778. throw new Error("Cannot load cubemap because files were not defined");
  15779. }
  15780. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15781. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15782. var height = width;
  15783. _this._prepareWorkingCanvas();
  15784. if (!_this._workingCanvas || !_this._workingContext) {
  15785. return;
  15786. }
  15787. _this._workingCanvas.width = width;
  15788. _this._workingCanvas.height = height;
  15789. var faces = [
  15790. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15791. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15792. ];
  15793. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15794. _this._unpackFlipY(false);
  15795. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15796. for (var index = 0; index < faces.length; index++) {
  15797. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15798. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15799. }
  15800. if (!noMipmap) {
  15801. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15802. }
  15803. _this._setCubeMapTextureParams(!noMipmap);
  15804. texture.width = width;
  15805. texture.height = height;
  15806. texture.isReady = true;
  15807. if (format) {
  15808. texture.format = format;
  15809. }
  15810. texture.onLoadedObservable.notifyObservers(texture);
  15811. texture.onLoadedObservable.clear();
  15812. if (onLoad) {
  15813. onLoad();
  15814. }
  15815. }, files, onError);
  15816. }
  15817. this._internalTexturesCache.push(texture);
  15818. return texture;
  15819. };
  15820. /**
  15821. * @hidden
  15822. */
  15823. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15824. var gl = this._gl;
  15825. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15827. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15828. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15829. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15830. // this.resetTextureCache();
  15831. };
  15832. /**
  15833. * Update a raw cube texture
  15834. * @param texture defines the texture to udpdate
  15835. * @param data defines the data to store
  15836. * @param format defines the data format
  15837. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15838. * @param invertY defines if data must be stored with Y axis inverted
  15839. * @param compression defines the compression used (null by default)
  15840. * @param level defines which level of the texture to update
  15841. */
  15842. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15843. if (compression === void 0) { compression = null; }
  15844. if (level === void 0) { level = 0; }
  15845. texture._bufferViewArray = data;
  15846. texture.format = format;
  15847. texture.type = type;
  15848. texture.invertY = invertY;
  15849. texture._compression = compression;
  15850. var gl = this._gl;
  15851. var textureType = this._getWebGLTextureType(type);
  15852. var internalFormat = this._getInternalFormat(format);
  15853. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15854. var needConversion = false;
  15855. if (internalFormat === gl.RGB) {
  15856. internalFormat = gl.RGBA;
  15857. needConversion = true;
  15858. }
  15859. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15860. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15861. if (texture.width % 4 !== 0) {
  15862. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15863. }
  15864. // Data are known to be in +X +Y +Z -X -Y -Z
  15865. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15866. var faceData = data[faceIndex];
  15867. if (compression) {
  15868. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15869. }
  15870. else {
  15871. if (needConversion) {
  15872. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15873. }
  15874. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15875. }
  15876. }
  15877. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15878. if (isPot && texture.generateMipMaps && level === 0) {
  15879. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15880. }
  15881. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15882. // this.resetTextureCache();
  15883. texture.isReady = true;
  15884. };
  15885. /**
  15886. * Creates a new raw cube texture
  15887. * @param data defines the array of data to use to create each face
  15888. * @param size defines the size of the textures
  15889. * @param format defines the format of the data
  15890. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15891. * @param generateMipMaps defines if the engine should generate the mip levels
  15892. * @param invertY defines if data must be stored with Y axis inverted
  15893. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15894. * @param compression defines the compression used (null by default)
  15895. * @returns the cube texture as an InternalTexture
  15896. */
  15897. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15898. if (compression === void 0) { compression = null; }
  15899. var gl = this._gl;
  15900. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15901. texture.isCube = true;
  15902. texture.format = format;
  15903. texture.type = type;
  15904. if (!this._doNotHandleContextLost) {
  15905. texture._bufferViewArray = data;
  15906. }
  15907. var textureType = this._getWebGLTextureType(type);
  15908. var internalFormat = this._getInternalFormat(format);
  15909. if (internalFormat === gl.RGB) {
  15910. internalFormat = gl.RGBA;
  15911. }
  15912. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15913. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15914. generateMipMaps = false;
  15915. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15916. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15917. }
  15918. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15919. generateMipMaps = false;
  15920. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15921. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15922. }
  15923. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15924. generateMipMaps = false;
  15925. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15926. }
  15927. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15928. generateMipMaps = false;
  15929. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15930. }
  15931. var width = size;
  15932. var height = width;
  15933. texture.width = width;
  15934. texture.height = height;
  15935. // Double check on POT to generate Mips.
  15936. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15937. if (!isPot) {
  15938. generateMipMaps = false;
  15939. }
  15940. // Upload data if needed. The texture won't be ready until then.
  15941. if (data) {
  15942. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15943. }
  15944. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15945. // Filters
  15946. if (data && generateMipMaps) {
  15947. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15948. }
  15949. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15950. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15953. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15954. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15955. texture.generateMipMaps = generateMipMaps;
  15956. return texture;
  15957. };
  15958. /**
  15959. * Creates a new raw cube texture from a specified url
  15960. * @param url defines the url where the data is located
  15961. * @param scene defines the current scene
  15962. * @param size defines the size of the textures
  15963. * @param format defines the format of the data
  15964. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15965. * @param noMipmap defines if the engine should avoid generating the mip levels
  15966. * @param callback defines a callback used to extract texture data from loaded data
  15967. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15968. * @param onLoad defines a callback called when texture is loaded
  15969. * @param onError defines a callback called if there is an error
  15970. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15971. * @param invertY defines if data must be stored with Y axis inverted
  15972. * @returns the cube texture as an InternalTexture
  15973. */
  15974. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15975. var _this = this;
  15976. if (onLoad === void 0) { onLoad = null; }
  15977. if (onError === void 0) { onError = null; }
  15978. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15979. if (invertY === void 0) { invertY = false; }
  15980. var gl = this._gl;
  15981. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15982. scene._addPendingData(texture);
  15983. texture.url = url;
  15984. this._internalTexturesCache.push(texture);
  15985. var onerror = function (request, exception) {
  15986. scene._removePendingData(texture);
  15987. if (onError && request) {
  15988. onError(request.status + " " + request.statusText, exception);
  15989. }
  15990. };
  15991. var internalCallback = function (data) {
  15992. var width = texture.width;
  15993. var faceDataArrays = callback(data);
  15994. if (!faceDataArrays) {
  15995. return;
  15996. }
  15997. if (mipmapGenerator) {
  15998. var textureType = _this._getWebGLTextureType(type);
  15999. var internalFormat = _this._getInternalFormat(format);
  16000. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16001. var needConversion = false;
  16002. if (internalFormat === gl.RGB) {
  16003. internalFormat = gl.RGBA;
  16004. needConversion = true;
  16005. }
  16006. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16007. _this._unpackFlipY(false);
  16008. var mipData = mipmapGenerator(faceDataArrays);
  16009. for (var level = 0; level < mipData.length; level++) {
  16010. var mipSize = width >> level;
  16011. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16012. var mipFaceData = mipData[level][faceIndex];
  16013. if (needConversion) {
  16014. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16015. }
  16016. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16017. }
  16018. }
  16019. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16020. }
  16021. else {
  16022. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16023. }
  16024. texture.isReady = true;
  16025. // this.resetTextureCache();
  16026. scene._removePendingData(texture);
  16027. if (onLoad) {
  16028. onLoad();
  16029. }
  16030. };
  16031. this._loadFile(url, function (data) {
  16032. internalCallback(data);
  16033. }, undefined, scene.database, true, onerror);
  16034. return texture;
  16035. };
  16036. ;
  16037. /**
  16038. * Update a raw 3D texture
  16039. * @param texture defines the texture to update
  16040. * @param data defines the data to store
  16041. * @param format defines the data format
  16042. * @param invertY defines if data must be stored with Y axis inverted
  16043. * @param compression defines the used compression (can be null)
  16044. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16045. */
  16046. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16047. if (compression === void 0) { compression = null; }
  16048. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16049. var internalType = this._getWebGLTextureType(textureType);
  16050. var internalFormat = this._getInternalFormat(format);
  16051. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16052. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16053. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16054. if (!this._doNotHandleContextLost) {
  16055. texture._bufferView = data;
  16056. texture.format = format;
  16057. texture.invertY = invertY;
  16058. texture._compression = compression;
  16059. }
  16060. if (texture.width % 4 !== 0) {
  16061. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16062. }
  16063. if (compression && data) {
  16064. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16065. }
  16066. else {
  16067. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16068. }
  16069. if (texture.generateMipMaps) {
  16070. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16071. }
  16072. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16073. // this.resetTextureCache();
  16074. texture.isReady = true;
  16075. };
  16076. /**
  16077. * Creates a new raw 3D texture
  16078. * @param data defines the data used to create the texture
  16079. * @param width defines the width of the texture
  16080. * @param height defines the height of the texture
  16081. * @param depth defines the depth of the texture
  16082. * @param format defines the format of the texture
  16083. * @param generateMipMaps defines if the engine must generate mip levels
  16084. * @param invertY defines if data must be stored with Y axis inverted
  16085. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16086. * @param compression defines the compressed used (can be null)
  16087. * @param textureType defines the compressed used (can be null)
  16088. * @returns a new raw 3D texture (stored in an InternalTexture)
  16089. */
  16090. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16091. if (compression === void 0) { compression = null; }
  16092. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16093. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16094. texture.baseWidth = width;
  16095. texture.baseHeight = height;
  16096. texture.baseDepth = depth;
  16097. texture.width = width;
  16098. texture.height = height;
  16099. texture.depth = depth;
  16100. texture.format = format;
  16101. texture.type = textureType;
  16102. texture.generateMipMaps = generateMipMaps;
  16103. texture.samplingMode = samplingMode;
  16104. texture.is3D = true;
  16105. if (!this._doNotHandleContextLost) {
  16106. texture._bufferView = data;
  16107. }
  16108. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16109. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16110. // Filters
  16111. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16112. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16113. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16114. if (generateMipMaps) {
  16115. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16116. }
  16117. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16118. this._internalTexturesCache.push(texture);
  16119. return texture;
  16120. };
  16121. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16122. var gl = this._gl;
  16123. if (!gl) {
  16124. return;
  16125. }
  16126. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16127. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16128. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16129. if (!noMipmap && !isCompressed) {
  16130. gl.generateMipmap(gl.TEXTURE_2D);
  16131. }
  16132. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16133. // this.resetTextureCache();
  16134. if (scene) {
  16135. scene._removePendingData(texture);
  16136. }
  16137. texture.onLoadedObservable.notifyObservers(texture);
  16138. texture.onLoadedObservable.clear();
  16139. };
  16140. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16141. var _this = this;
  16142. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16143. var maxTextureSize = this.getCaps().maxTextureSize;
  16144. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16145. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16146. var gl = this._gl;
  16147. if (!gl) {
  16148. return;
  16149. }
  16150. if (!texture._webGLTexture) {
  16151. // this.resetTextureCache();
  16152. if (scene) {
  16153. scene._removePendingData(texture);
  16154. }
  16155. return;
  16156. }
  16157. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16158. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16159. texture.baseWidth = width;
  16160. texture.baseHeight = height;
  16161. texture.width = potWidth;
  16162. texture.height = potHeight;
  16163. texture.isReady = true;
  16164. if (processFunction(potWidth, potHeight, function () {
  16165. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16166. })) {
  16167. // Returning as texture needs extra async steps
  16168. return;
  16169. }
  16170. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16171. };
  16172. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16173. // Create new RGBA data container.
  16174. var rgbaData;
  16175. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16176. rgbaData = new Float32Array(width * height * 4);
  16177. }
  16178. else {
  16179. rgbaData = new Uint32Array(width * height * 4);
  16180. }
  16181. // Convert each pixel.
  16182. for (var x = 0; x < width; x++) {
  16183. for (var y = 0; y < height; y++) {
  16184. var index = (y * width + x) * 3;
  16185. var newIndex = (y * width + x) * 4;
  16186. // Map Old Value to new value.
  16187. rgbaData[newIndex + 0] = rgbData[index + 0];
  16188. rgbaData[newIndex + 1] = rgbData[index + 1];
  16189. rgbaData[newIndex + 2] = rgbData[index + 2];
  16190. // Add fully opaque alpha channel.
  16191. rgbaData[newIndex + 3] = 1;
  16192. }
  16193. }
  16194. return rgbaData;
  16195. };
  16196. /** @hidden */
  16197. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16198. var gl = this._gl;
  16199. if (texture._framebuffer) {
  16200. gl.deleteFramebuffer(texture._framebuffer);
  16201. texture._framebuffer = null;
  16202. }
  16203. if (texture._depthStencilBuffer) {
  16204. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16205. texture._depthStencilBuffer = null;
  16206. }
  16207. if (texture._MSAAFramebuffer) {
  16208. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16209. texture._MSAAFramebuffer = null;
  16210. }
  16211. if (texture._MSAARenderBuffer) {
  16212. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16213. texture._MSAARenderBuffer = null;
  16214. }
  16215. };
  16216. /** @hidden */
  16217. Engine.prototype._releaseTexture = function (texture) {
  16218. var gl = this._gl;
  16219. this._releaseFramebufferObjects(texture);
  16220. gl.deleteTexture(texture._webGLTexture);
  16221. // Unbind channels
  16222. this.unbindAllTextures();
  16223. var index = this._internalTexturesCache.indexOf(texture);
  16224. if (index !== -1) {
  16225. this._internalTexturesCache.splice(index, 1);
  16226. }
  16227. // Integrated fixed lod samplers.
  16228. if (texture._lodTextureHigh) {
  16229. texture._lodTextureHigh.dispose();
  16230. }
  16231. if (texture._lodTextureMid) {
  16232. texture._lodTextureMid.dispose();
  16233. }
  16234. if (texture._lodTextureLow) {
  16235. texture._lodTextureLow.dispose();
  16236. }
  16237. // Set output texture of post process to null if the texture has been released/disposed
  16238. this.scenes.forEach(function (scene) {
  16239. scene.postProcesses.forEach(function (postProcess) {
  16240. if (postProcess._outputTexture == texture) {
  16241. postProcess._outputTexture = null;
  16242. }
  16243. });
  16244. scene.cameras.forEach(function (camera) {
  16245. camera._postProcesses.forEach(function (postProcess) {
  16246. if (postProcess) {
  16247. if (postProcess._outputTexture == texture) {
  16248. postProcess._outputTexture = null;
  16249. }
  16250. }
  16251. });
  16252. });
  16253. });
  16254. };
  16255. Engine.prototype.setProgram = function (program) {
  16256. if (this._currentProgram !== program) {
  16257. this._gl.useProgram(program);
  16258. this._currentProgram = program;
  16259. }
  16260. };
  16261. /**
  16262. * Binds an effect to the webGL context
  16263. * @param effect defines the effect to bind
  16264. */
  16265. Engine.prototype.bindSamplers = function (effect) {
  16266. this.setProgram(effect.getProgram());
  16267. var samplers = effect.getSamplers();
  16268. for (var index = 0; index < samplers.length; index++) {
  16269. var uniform = effect.getUniform(samplers[index]);
  16270. if (uniform) {
  16271. this._boundUniforms[index] = uniform;
  16272. }
  16273. }
  16274. this._currentEffect = null;
  16275. };
  16276. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16277. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16278. return;
  16279. }
  16280. // Remove
  16281. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16282. // Bind last to it
  16283. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16284. // Bind to dummy
  16285. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16286. };
  16287. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16288. if (!internalTexture) {
  16289. return -1;
  16290. }
  16291. internalTexture._initialSlot = channel;
  16292. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16293. if (channel !== internalTexture._designatedSlot) {
  16294. this._textureCollisions.addCount(1, false);
  16295. }
  16296. }
  16297. else {
  16298. if (channel !== internalTexture._designatedSlot) {
  16299. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16300. return internalTexture._designatedSlot;
  16301. }
  16302. else {
  16303. // No slot for this texture, let's pick a new one (if we find a free slot)
  16304. if (this._nextFreeTextureSlots.length) {
  16305. return this._nextFreeTextureSlots[0];
  16306. }
  16307. // We need to recycle the oldest bound texture, sorry.
  16308. this._textureCollisions.addCount(1, false);
  16309. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16310. }
  16311. }
  16312. }
  16313. return channel;
  16314. };
  16315. Engine.prototype._linkTrackers = function (previous, next) {
  16316. previous.next = next;
  16317. next.previous = previous;
  16318. };
  16319. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16320. var currentSlot = internalTexture._designatedSlot;
  16321. if (currentSlot === -1) {
  16322. return -1;
  16323. }
  16324. internalTexture._designatedSlot = -1;
  16325. if (this.disableTextureBindingOptimization) {
  16326. return -1;
  16327. }
  16328. // Remove from bound list
  16329. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16330. // Free the slot
  16331. this._boundTexturesCache[currentSlot] = null;
  16332. this._nextFreeTextureSlots.push(currentSlot);
  16333. return currentSlot;
  16334. };
  16335. Engine.prototype._activateCurrentTexture = function () {
  16336. if (this._currentTextureChannel !== this._activeChannel) {
  16337. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16338. this._currentTextureChannel = this._activeChannel;
  16339. }
  16340. };
  16341. /** @hidden */
  16342. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16343. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16344. if (force === void 0) { force = false; }
  16345. var wasPreviouslyBound = false;
  16346. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16347. this._activeChannel = texture._designatedSlot;
  16348. }
  16349. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16350. var isTextureForRendering = texture && texture._initialSlot > -1;
  16351. if (currentTextureBound !== texture || force) {
  16352. if (currentTextureBound) {
  16353. this._removeDesignatedSlot(currentTextureBound);
  16354. }
  16355. this._activateCurrentTexture();
  16356. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16357. this._boundTexturesCache[this._activeChannel] = texture;
  16358. if (texture) {
  16359. if (!this.disableTextureBindingOptimization) {
  16360. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16361. if (slotIndex > -1) {
  16362. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16363. }
  16364. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16365. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16366. }
  16367. texture._designatedSlot = this._activeChannel;
  16368. }
  16369. }
  16370. else if (forTextureDataUpdate) {
  16371. wasPreviouslyBound = true;
  16372. this._activateCurrentTexture();
  16373. }
  16374. if (isTextureForRendering && !forTextureDataUpdate) {
  16375. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16376. }
  16377. return wasPreviouslyBound;
  16378. };
  16379. /** @hidden */
  16380. Engine.prototype._bindTexture = function (channel, texture) {
  16381. if (channel < 0) {
  16382. return;
  16383. }
  16384. if (texture) {
  16385. channel = this._getCorrectTextureChannel(channel, texture);
  16386. }
  16387. this._activeChannel = channel;
  16388. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16389. };
  16390. /**
  16391. * Sets a texture to the webGL context from a postprocess
  16392. * @param channel defines the channel to use
  16393. * @param postProcess defines the source postprocess
  16394. */
  16395. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16396. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16397. };
  16398. /**
  16399. * Binds the output of the passed in post process to the texture channel specified
  16400. * @param channel The channel the texture should be bound to
  16401. * @param postProcess The post process which's output should be bound
  16402. */
  16403. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16404. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16405. };
  16406. /**
  16407. * Unbind all textures from the webGL context
  16408. */
  16409. Engine.prototype.unbindAllTextures = function () {
  16410. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16411. this._activeChannel = channel;
  16412. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16413. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16414. if (this.webGLVersion > 1) {
  16415. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16416. }
  16417. }
  16418. };
  16419. /**
  16420. * Sets a texture to the according uniform.
  16421. * @param channel The texture channel
  16422. * @param uniform The uniform to set
  16423. * @param texture The texture to apply
  16424. */
  16425. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16426. if (channel < 0) {
  16427. return;
  16428. }
  16429. if (uniform) {
  16430. this._boundUniforms[channel] = uniform;
  16431. }
  16432. this._setTexture(channel, texture);
  16433. };
  16434. /**
  16435. * Sets a depth stencil texture from a render target to the according uniform.
  16436. * @param channel The texture channel
  16437. * @param uniform The uniform to set
  16438. * @param texture The render target texture containing the depth stencil texture to apply
  16439. */
  16440. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16441. if (channel < 0) {
  16442. return;
  16443. }
  16444. if (uniform) {
  16445. this._boundUniforms[channel] = uniform;
  16446. }
  16447. if (!texture || !texture.depthStencilTexture) {
  16448. this._setTexture(channel, null);
  16449. }
  16450. else {
  16451. this._setTexture(channel, texture, false, true);
  16452. }
  16453. };
  16454. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16455. var uniform = this._boundUniforms[sourceSlot];
  16456. if (uniform._currentState === destination) {
  16457. return;
  16458. }
  16459. this._gl.uniform1i(uniform, destination);
  16460. uniform._currentState = destination;
  16461. };
  16462. Engine.prototype._getTextureWrapMode = function (mode) {
  16463. switch (mode) {
  16464. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16465. return this._gl.REPEAT;
  16466. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16467. return this._gl.CLAMP_TO_EDGE;
  16468. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16469. return this._gl.MIRRORED_REPEAT;
  16470. }
  16471. return this._gl.REPEAT;
  16472. };
  16473. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16474. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16475. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16476. // Not ready?
  16477. if (!texture) {
  16478. if (this._boundTexturesCache[channel] != null) {
  16479. this._activeChannel = channel;
  16480. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16481. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16482. if (this.webGLVersion > 1) {
  16483. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16484. }
  16485. }
  16486. return false;
  16487. }
  16488. // Video
  16489. if (texture.video) {
  16490. this._activeChannel = channel;
  16491. texture.update();
  16492. }
  16493. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16494. texture.delayLoad();
  16495. return false;
  16496. }
  16497. var internalTexture;
  16498. if (depthStencilTexture) {
  16499. internalTexture = texture.depthStencilTexture;
  16500. }
  16501. else if (texture.isReady()) {
  16502. internalTexture = texture.getInternalTexture();
  16503. }
  16504. else if (texture.isCube) {
  16505. internalTexture = this.emptyCubeTexture;
  16506. }
  16507. else if (texture.is3D) {
  16508. internalTexture = this.emptyTexture3D;
  16509. }
  16510. else {
  16511. internalTexture = this.emptyTexture;
  16512. }
  16513. if (!isPartOfTextureArray) {
  16514. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16515. }
  16516. var needToBind = true;
  16517. if (this._boundTexturesCache[channel] === internalTexture) {
  16518. this._moveBoundTextureOnTop(internalTexture);
  16519. if (!isPartOfTextureArray) {
  16520. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16521. }
  16522. needToBind = false;
  16523. }
  16524. this._activeChannel = channel;
  16525. if (internalTexture && internalTexture.is3D) {
  16526. if (needToBind) {
  16527. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16528. }
  16529. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16530. internalTexture._cachedWrapU = texture.wrapU;
  16531. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16532. }
  16533. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16534. internalTexture._cachedWrapV = texture.wrapV;
  16535. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16536. }
  16537. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16538. internalTexture._cachedWrapR = texture.wrapR;
  16539. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16540. }
  16541. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16542. }
  16543. else if (internalTexture && internalTexture.isCube) {
  16544. if (needToBind) {
  16545. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16546. }
  16547. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16548. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16549. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16550. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16551. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16552. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16553. }
  16554. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16555. }
  16556. else {
  16557. if (needToBind) {
  16558. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16559. }
  16560. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16561. internalTexture._cachedWrapU = texture.wrapU;
  16562. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16563. }
  16564. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16565. internalTexture._cachedWrapV = texture.wrapV;
  16566. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16567. }
  16568. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16569. }
  16570. return true;
  16571. };
  16572. /**
  16573. * Sets an array of texture to the webGL context
  16574. * @param channel defines the channel where the texture array must be set
  16575. * @param uniform defines the associated uniform location
  16576. * @param textures defines the array of textures to bind
  16577. */
  16578. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16579. if (channel < 0 || !uniform) {
  16580. return;
  16581. }
  16582. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16583. this._textureUnits = new Int32Array(textures.length);
  16584. }
  16585. for (var i = 0; i < textures.length; i++) {
  16586. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16587. }
  16588. this._gl.uniform1iv(uniform, this._textureUnits);
  16589. for (var index = 0; index < textures.length; index++) {
  16590. this._setTexture(this._textureUnits[index], textures[index], true);
  16591. }
  16592. };
  16593. /** @hidden */
  16594. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16595. var internalTexture = texture.getInternalTexture();
  16596. if (!internalTexture) {
  16597. return;
  16598. }
  16599. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16600. var value = texture.anisotropicFilteringLevel;
  16601. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16602. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16603. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16604. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16605. }
  16606. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16607. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16608. internalTexture._cachedAnisotropicFilteringLevel = value;
  16609. }
  16610. };
  16611. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16612. this._bindTextureDirectly(target, texture, true, true);
  16613. this._gl.texParameterf(target, parameter, value);
  16614. };
  16615. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16616. if (texture) {
  16617. this._bindTextureDirectly(target, texture, true, true);
  16618. }
  16619. this._gl.texParameteri(target, parameter, value);
  16620. };
  16621. /**
  16622. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16623. * @param x defines the x coordinate of the rectangle where pixels must be read
  16624. * @param y defines the y coordinate of the rectangle where pixels must be read
  16625. * @param width defines the width of the rectangle where pixels must be read
  16626. * @param height defines the height of the rectangle where pixels must be read
  16627. * @returns a Uint8Array containing RGBA colors
  16628. */
  16629. Engine.prototype.readPixels = function (x, y, width, height) {
  16630. var data = new Uint8Array(height * width * 4);
  16631. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16632. return data;
  16633. };
  16634. /**
  16635. * Add an externaly attached data from its key.
  16636. * This method call will fail and return false, if such key already exists.
  16637. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16638. * @param key the unique key that identifies the data
  16639. * @param data the data object to associate to the key for this Engine instance
  16640. * @return true if no such key were already present and the data was added successfully, false otherwise
  16641. */
  16642. Engine.prototype.addExternalData = function (key, data) {
  16643. if (!this._externalData) {
  16644. this._externalData = new BABYLON.StringDictionary();
  16645. }
  16646. return this._externalData.add(key, data);
  16647. };
  16648. /**
  16649. * Get an externaly attached data from its key
  16650. * @param key the unique key that identifies the data
  16651. * @return the associated data, if present (can be null), or undefined if not present
  16652. */
  16653. Engine.prototype.getExternalData = function (key) {
  16654. if (!this._externalData) {
  16655. this._externalData = new BABYLON.StringDictionary();
  16656. }
  16657. return this._externalData.get(key);
  16658. };
  16659. /**
  16660. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16661. * @param key the unique key that identifies the data
  16662. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16663. * @return the associated data, can be null if the factory returned null.
  16664. */
  16665. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16666. if (!this._externalData) {
  16667. this._externalData = new BABYLON.StringDictionary();
  16668. }
  16669. return this._externalData.getOrAddWithFactory(key, factory);
  16670. };
  16671. /**
  16672. * Remove an externaly attached data from the Engine instance
  16673. * @param key the unique key that identifies the data
  16674. * @return true if the data was successfully removed, false if it doesn't exist
  16675. */
  16676. Engine.prototype.removeExternalData = function (key) {
  16677. if (!this._externalData) {
  16678. this._externalData = new BABYLON.StringDictionary();
  16679. }
  16680. return this._externalData.remove(key);
  16681. };
  16682. /**
  16683. * Unbind all vertex attributes from the webGL context
  16684. */
  16685. Engine.prototype.unbindAllAttributes = function () {
  16686. if (this._mustWipeVertexAttributes) {
  16687. this._mustWipeVertexAttributes = false;
  16688. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16689. this._gl.disableVertexAttribArray(i);
  16690. this._vertexAttribArraysEnabled[i] = false;
  16691. this._currentBufferPointers[i].active = false;
  16692. }
  16693. return;
  16694. }
  16695. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16696. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16697. continue;
  16698. }
  16699. this._gl.disableVertexAttribArray(i);
  16700. this._vertexAttribArraysEnabled[i] = false;
  16701. this._currentBufferPointers[i].active = false;
  16702. }
  16703. };
  16704. /**
  16705. * 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
  16706. */
  16707. Engine.prototype.releaseEffects = function () {
  16708. for (var name in this._compiledEffects) {
  16709. this._deleteProgram(this._compiledEffects[name]._program);
  16710. }
  16711. this._compiledEffects = {};
  16712. };
  16713. /**
  16714. * Dispose and release all associated resources
  16715. */
  16716. Engine.prototype.dispose = function () {
  16717. this.hideLoadingUI();
  16718. this.stopRenderLoop();
  16719. // Release postProcesses
  16720. while (this.postProcesses.length) {
  16721. this.postProcesses[0].dispose();
  16722. }
  16723. // Empty texture
  16724. if (this._emptyTexture) {
  16725. this._releaseTexture(this._emptyTexture);
  16726. this._emptyTexture = null;
  16727. }
  16728. if (this._emptyCubeTexture) {
  16729. this._releaseTexture(this._emptyCubeTexture);
  16730. this._emptyCubeTexture = null;
  16731. }
  16732. // Rescale PP
  16733. if (this._rescalePostProcess) {
  16734. this._rescalePostProcess.dispose();
  16735. }
  16736. // Release scenes
  16737. while (this.scenes.length) {
  16738. this.scenes[0].dispose();
  16739. }
  16740. // Release audio engine
  16741. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  16742. Engine.audioEngine.dispose();
  16743. }
  16744. // Release effects
  16745. this.releaseEffects();
  16746. // Unbind
  16747. this.unbindAllAttributes();
  16748. this._boundUniforms = [];
  16749. if (this._dummyFramebuffer) {
  16750. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16751. }
  16752. //WebVR
  16753. this.disableVR();
  16754. // Events
  16755. if (BABYLON.Tools.IsWindowObjectExist()) {
  16756. window.removeEventListener("blur", this._onBlur);
  16757. window.removeEventListener("focus", this._onFocus);
  16758. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16759. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16760. if (this._renderingCanvas) {
  16761. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16762. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16763. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16764. if (!this._doNotHandleContextLost) {
  16765. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16766. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16767. }
  16768. }
  16769. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16770. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16771. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16772. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16773. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16774. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16775. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16776. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16777. if (this._onVrDisplayConnect) {
  16778. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16779. if (this._onVrDisplayDisconnect) {
  16780. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16781. }
  16782. if (this._onVrDisplayPresentChange) {
  16783. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16784. }
  16785. this._onVrDisplayConnect = null;
  16786. this._onVrDisplayDisconnect = null;
  16787. }
  16788. }
  16789. // Remove from Instances
  16790. var index = Engine.Instances.indexOf(this);
  16791. if (index >= 0) {
  16792. Engine.Instances.splice(index, 1);
  16793. }
  16794. this._workingCanvas = null;
  16795. this._workingContext = null;
  16796. this._currentBufferPointers = [];
  16797. this._renderingCanvas = null;
  16798. this._currentProgram = null;
  16799. this._bindedRenderFunction = null;
  16800. this.onResizeObservable.clear();
  16801. this.onCanvasBlurObservable.clear();
  16802. this.onCanvasFocusObservable.clear();
  16803. this.onCanvasPointerOutObservable.clear();
  16804. this.onBeginFrameObservable.clear();
  16805. this.onEndFrameObservable.clear();
  16806. BABYLON.Effect.ResetCache();
  16807. // Abort active requests
  16808. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16809. var request = _a[_i];
  16810. request.abort();
  16811. }
  16812. };
  16813. // Loading screen
  16814. /**
  16815. * Display the loading screen
  16816. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16817. */
  16818. Engine.prototype.displayLoadingUI = function () {
  16819. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16820. return;
  16821. }
  16822. var loadingScreen = this.loadingScreen;
  16823. if (loadingScreen) {
  16824. loadingScreen.displayLoadingUI();
  16825. }
  16826. };
  16827. /**
  16828. * Hide the loading screen
  16829. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16830. */
  16831. Engine.prototype.hideLoadingUI = function () {
  16832. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16833. return;
  16834. }
  16835. var loadingScreen = this.loadingScreen;
  16836. if (loadingScreen) {
  16837. loadingScreen.hideLoadingUI();
  16838. }
  16839. };
  16840. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16841. /**
  16842. * Gets the current loading screen object
  16843. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16844. */
  16845. get: function () {
  16846. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16847. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16848. return this._loadingScreen;
  16849. },
  16850. /**
  16851. * Sets the current loading screen object
  16852. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16853. */
  16854. set: function (loadingScreen) {
  16855. this._loadingScreen = loadingScreen;
  16856. },
  16857. enumerable: true,
  16858. configurable: true
  16859. });
  16860. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16861. /**
  16862. * Sets the current loading screen text
  16863. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16864. */
  16865. set: function (text) {
  16866. this.loadingScreen.loadingUIText = text;
  16867. },
  16868. enumerable: true,
  16869. configurable: true
  16870. });
  16871. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16872. /**
  16873. * Sets the current loading screen background color
  16874. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16875. */
  16876. set: function (color) {
  16877. this.loadingScreen.loadingUIBackgroundColor = color;
  16878. },
  16879. enumerable: true,
  16880. configurable: true
  16881. });
  16882. /**
  16883. * Attach a new callback raised when context lost event is fired
  16884. * @param callback defines the callback to call
  16885. */
  16886. Engine.prototype.attachContextLostEvent = function (callback) {
  16887. if (this._renderingCanvas) {
  16888. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16889. }
  16890. };
  16891. /**
  16892. * Attach a new callback raised when context restored event is fired
  16893. * @param callback defines the callback to call
  16894. */
  16895. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16896. if (this._renderingCanvas) {
  16897. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16898. }
  16899. };
  16900. /**
  16901. * Gets the source code of the vertex shader associated with a specific webGL program
  16902. * @param program defines the program to use
  16903. * @returns a string containing the source code of the vertex shader associated with the program
  16904. */
  16905. Engine.prototype.getVertexShaderSource = function (program) {
  16906. var shaders = this._gl.getAttachedShaders(program);
  16907. if (!shaders) {
  16908. return null;
  16909. }
  16910. return this._gl.getShaderSource(shaders[0]);
  16911. };
  16912. /**
  16913. * Gets the source code of the fragment shader associated with a specific webGL program
  16914. * @param program defines the program to use
  16915. * @returns a string containing the source code of the fragment shader associated with the program
  16916. */
  16917. Engine.prototype.getFragmentShaderSource = function (program) {
  16918. var shaders = this._gl.getAttachedShaders(program);
  16919. if (!shaders) {
  16920. return null;
  16921. }
  16922. return this._gl.getShaderSource(shaders[1]);
  16923. };
  16924. /**
  16925. * Get the current error code of the webGL context
  16926. * @returns the error code
  16927. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16928. */
  16929. Engine.prototype.getError = function () {
  16930. return this._gl.getError();
  16931. };
  16932. // FPS
  16933. /**
  16934. * Gets the current framerate
  16935. * @returns a number representing the framerate
  16936. */
  16937. Engine.prototype.getFps = function () {
  16938. return this._fps;
  16939. };
  16940. /**
  16941. * Gets the time spent between current and previous frame
  16942. * @returns a number representing the delta time in ms
  16943. */
  16944. Engine.prototype.getDeltaTime = function () {
  16945. return this._deltaTime;
  16946. };
  16947. Engine.prototype._measureFps = function () {
  16948. this._performanceMonitor.sampleFrame();
  16949. this._fps = this._performanceMonitor.averageFPS;
  16950. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16951. };
  16952. /** @hidden */
  16953. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  16954. if (faceIndex === void 0) { faceIndex = -1; }
  16955. if (level === void 0) { level = 0; }
  16956. if (buffer === void 0) { buffer = null; }
  16957. var gl = this._gl;
  16958. if (!this._dummyFramebuffer) {
  16959. var dummy = gl.createFramebuffer();
  16960. if (!dummy) {
  16961. throw new Error("Unable to create dummy framebuffer");
  16962. }
  16963. this._dummyFramebuffer = dummy;
  16964. }
  16965. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16966. if (faceIndex > -1) {
  16967. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16968. }
  16969. else {
  16970. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16971. }
  16972. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16973. switch (readType) {
  16974. case gl.UNSIGNED_BYTE:
  16975. if (!buffer) {
  16976. buffer = new Uint8Array(4 * width * height);
  16977. }
  16978. readType = gl.UNSIGNED_BYTE;
  16979. break;
  16980. default:
  16981. if (!buffer) {
  16982. buffer = new Float32Array(4 * width * height);
  16983. }
  16984. readType = gl.FLOAT;
  16985. break;
  16986. }
  16987. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16988. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16989. return buffer;
  16990. };
  16991. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16992. if (this._webGLVersion > 1) {
  16993. return this._caps.colorBufferFloat;
  16994. }
  16995. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16996. };
  16997. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16998. if (this._webGLVersion > 1) {
  16999. return this._caps.colorBufferFloat;
  17000. }
  17001. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17002. };
  17003. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17004. Engine.prototype._canRenderToFramebuffer = function (type) {
  17005. var gl = this._gl;
  17006. //clear existing errors
  17007. while (gl.getError() !== gl.NO_ERROR) { }
  17008. var successful = true;
  17009. var texture = gl.createTexture();
  17010. gl.bindTexture(gl.TEXTURE_2D, texture);
  17011. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17012. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17013. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17014. var fb = gl.createFramebuffer();
  17015. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17016. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17017. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17018. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17019. successful = successful && (gl.getError() === gl.NO_ERROR);
  17020. //try render by clearing frame buffer's color buffer
  17021. if (successful) {
  17022. gl.clear(gl.COLOR_BUFFER_BIT);
  17023. successful = successful && (gl.getError() === gl.NO_ERROR);
  17024. }
  17025. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17026. if (successful) {
  17027. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17028. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17029. var readFormat = gl.RGBA;
  17030. var readType = gl.UNSIGNED_BYTE;
  17031. var buffer = new Uint8Array(4);
  17032. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17033. successful = successful && (gl.getError() === gl.NO_ERROR);
  17034. }
  17035. //clean up
  17036. gl.deleteTexture(texture);
  17037. gl.deleteFramebuffer(fb);
  17038. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17039. //clear accumulated errors
  17040. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17041. return successful;
  17042. };
  17043. /** @hidden */
  17044. Engine.prototype._getWebGLTextureType = function (type) {
  17045. if (this._webGLVersion === 1) {
  17046. switch (type) {
  17047. case Engine.TEXTURETYPE_FLOAT:
  17048. return this._gl.FLOAT;
  17049. case Engine.TEXTURETYPE_HALF_FLOAT:
  17050. return this._gl.HALF_FLOAT_OES;
  17051. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17052. return this._gl.UNSIGNED_BYTE;
  17053. }
  17054. return this._gl.UNSIGNED_BYTE;
  17055. }
  17056. switch (type) {
  17057. case Engine.TEXTURETYPE_BYTE:
  17058. return this._gl.BYTE;
  17059. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17060. return this._gl.UNSIGNED_BYTE;
  17061. case Engine.TEXTURETYPE_SHORT:
  17062. return this._gl.SHORT;
  17063. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17064. return this._gl.UNSIGNED_SHORT;
  17065. case Engine.TEXTURETYPE_INT:
  17066. return this._gl.INT;
  17067. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17068. return this._gl.UNSIGNED_INT;
  17069. case Engine.TEXTURETYPE_FLOAT:
  17070. return this._gl.FLOAT;
  17071. case Engine.TEXTURETYPE_HALF_FLOAT:
  17072. return this._gl.HALF_FLOAT;
  17073. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17074. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17075. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17076. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17077. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17078. return this._gl.UNSIGNED_SHORT_5_6_5;
  17079. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17080. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17081. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17082. return this._gl.UNSIGNED_INT_24_8;
  17083. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17084. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17085. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17086. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17087. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17088. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17089. }
  17090. return this._gl.UNSIGNED_BYTE;
  17091. };
  17092. ;
  17093. Engine.prototype._getInternalFormat = function (format) {
  17094. var internalFormat = this._gl.RGBA;
  17095. switch (format) {
  17096. case Engine.TEXTUREFORMAT_ALPHA:
  17097. internalFormat = this._gl.ALPHA;
  17098. break;
  17099. case Engine.TEXTUREFORMAT_LUMINANCE:
  17100. internalFormat = this._gl.LUMINANCE;
  17101. break;
  17102. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17103. internalFormat = this._gl.LUMINANCE_ALPHA;
  17104. break;
  17105. case Engine.TEXTUREFORMAT_RED:
  17106. internalFormat = this._gl.RED;
  17107. break;
  17108. case Engine.TEXTUREFORMAT_RG:
  17109. internalFormat = this._gl.RG;
  17110. break;
  17111. case Engine.TEXTUREFORMAT_RGB:
  17112. internalFormat = this._gl.RGB;
  17113. break;
  17114. case Engine.TEXTUREFORMAT_RGBA:
  17115. internalFormat = this._gl.RGBA;
  17116. break;
  17117. }
  17118. if (this._webGLVersion > 1) {
  17119. switch (format) {
  17120. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17121. internalFormat = this._gl.RED_INTEGER;
  17122. break;
  17123. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17124. internalFormat = this._gl.RG_INTEGER;
  17125. break;
  17126. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17127. internalFormat = this._gl.RGB_INTEGER;
  17128. break;
  17129. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17130. internalFormat = this._gl.RGBA_INTEGER;
  17131. break;
  17132. }
  17133. }
  17134. return internalFormat;
  17135. };
  17136. /** @hidden */
  17137. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17138. if (this._webGLVersion === 1) {
  17139. if (format !== undefined) {
  17140. switch (format) {
  17141. case Engine.TEXTUREFORMAT_ALPHA:
  17142. return this._gl.ALPHA;
  17143. case Engine.TEXTUREFORMAT_LUMINANCE:
  17144. return this._gl.LUMINANCE;
  17145. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17146. return this._gl.LUMINANCE_ALPHA;
  17147. }
  17148. }
  17149. return this._gl.RGBA;
  17150. }
  17151. switch (type) {
  17152. case Engine.TEXTURETYPE_BYTE:
  17153. switch (format) {
  17154. case Engine.TEXTUREFORMAT_RED:
  17155. return this._gl.R8_SNORM;
  17156. case Engine.TEXTUREFORMAT_RG:
  17157. return this._gl.RG8_SNORM;
  17158. case Engine.TEXTUREFORMAT_RGB:
  17159. return this._gl.RGB8_SNORM;
  17160. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17161. return this._gl.R8I;
  17162. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17163. return this._gl.RG8I;
  17164. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17165. return this._gl.RGB8I;
  17166. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17167. return this._gl.RGBA8I;
  17168. default:
  17169. return this._gl.RGBA8_SNORM;
  17170. }
  17171. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17172. switch (format) {
  17173. case Engine.TEXTUREFORMAT_RED:
  17174. return this._gl.R8;
  17175. case Engine.TEXTUREFORMAT_RG:
  17176. return this._gl.RG8;
  17177. case Engine.TEXTUREFORMAT_RGB:
  17178. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17179. case Engine.TEXTUREFORMAT_RGBA:
  17180. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17181. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17182. return this._gl.R8UI;
  17183. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17184. return this._gl.RG8UI;
  17185. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17186. return this._gl.RGB8UI;
  17187. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17188. return this._gl.RGBA8UI;
  17189. default:
  17190. return this._gl.RGBA8;
  17191. }
  17192. case Engine.TEXTURETYPE_SHORT:
  17193. switch (format) {
  17194. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17195. return this._gl.R16I;
  17196. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17197. return this._gl.RG16I;
  17198. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17199. return this._gl.RGB16I;
  17200. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17201. return this._gl.RGBA16I;
  17202. default:
  17203. return this._gl.RGBA16I;
  17204. }
  17205. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17206. switch (format) {
  17207. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17208. return this._gl.R16UI;
  17209. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17210. return this._gl.RG16UI;
  17211. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17212. return this._gl.RGB16UI;
  17213. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17214. return this._gl.RGBA16UI;
  17215. default:
  17216. return this._gl.RGBA16UI;
  17217. }
  17218. case Engine.TEXTURETYPE_INT:
  17219. switch (format) {
  17220. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17221. return this._gl.R32I;
  17222. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17223. return this._gl.RG32I;
  17224. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17225. return this._gl.RGB32I;
  17226. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17227. return this._gl.RGBA32I;
  17228. default:
  17229. return this._gl.RGBA32I;
  17230. }
  17231. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17232. switch (format) {
  17233. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17234. return this._gl.R32UI;
  17235. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17236. return this._gl.RG32UI;
  17237. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17238. return this._gl.RGB32UI;
  17239. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17240. return this._gl.RGBA32UI;
  17241. default:
  17242. return this._gl.RGBA32UI;
  17243. }
  17244. case Engine.TEXTURETYPE_FLOAT:
  17245. switch (format) {
  17246. case Engine.TEXTUREFORMAT_RED:
  17247. return this._gl.R32F; // By default. Other possibility is R16F.
  17248. case Engine.TEXTUREFORMAT_RG:
  17249. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17250. case Engine.TEXTUREFORMAT_RGB:
  17251. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17252. case Engine.TEXTUREFORMAT_RGBA:
  17253. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17254. default:
  17255. return this._gl.RGBA32F;
  17256. }
  17257. case Engine.TEXTURETYPE_HALF_FLOAT:
  17258. switch (format) {
  17259. case Engine.TEXTUREFORMAT_RED:
  17260. return this._gl.R16F;
  17261. case Engine.TEXTUREFORMAT_RG:
  17262. return this._gl.RG16F;
  17263. case Engine.TEXTUREFORMAT_RGB:
  17264. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17265. case Engine.TEXTUREFORMAT_RGBA:
  17266. return this._gl.RGBA16F;
  17267. default:
  17268. return this._gl.RGBA16F;
  17269. }
  17270. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17271. return this._gl.RGB565;
  17272. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17273. return this._gl.R11F_G11F_B10F;
  17274. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17275. return this._gl.RGB9_E5;
  17276. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17277. return this._gl.RGBA4;
  17278. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17279. return this._gl.RGB5_A1;
  17280. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17281. switch (format) {
  17282. case Engine.TEXTUREFORMAT_RGBA:
  17283. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17284. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17285. return this._gl.RGB10_A2UI;
  17286. default:
  17287. return this._gl.RGB10_A2;
  17288. }
  17289. }
  17290. return this._gl.RGBA8;
  17291. };
  17292. ;
  17293. /** @hidden */
  17294. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17295. if (type === Engine.TEXTURETYPE_FLOAT) {
  17296. return this._gl.RGBA32F;
  17297. }
  17298. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17299. return this._gl.RGBA16F;
  17300. }
  17301. return this._gl.RGBA8;
  17302. };
  17303. ;
  17304. /** @hidden */
  17305. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17306. var _this = this;
  17307. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17308. this._activeRequests.push(request);
  17309. request.onCompleteObservable.add(function (request) {
  17310. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17311. });
  17312. return request;
  17313. };
  17314. /** @hidden */
  17315. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17316. var _this = this;
  17317. return new Promise(function (resolve, reject) {
  17318. _this._loadFile(url, function (data) {
  17319. resolve(data);
  17320. }, undefined, database, useArrayBuffer, function (request, exception) {
  17321. reject(exception);
  17322. });
  17323. });
  17324. };
  17325. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17326. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17327. var onload = function (data) {
  17328. loadedFiles[index] = data;
  17329. loadedFiles._internalCount++;
  17330. if (loadedFiles._internalCount === 6) {
  17331. onfinish(loadedFiles);
  17332. }
  17333. };
  17334. var onerror = function (request, exception) {
  17335. if (onErrorCallBack && request) {
  17336. onErrorCallBack(request.status + " " + request.statusText, exception);
  17337. }
  17338. };
  17339. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17340. };
  17341. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17342. if (onError === void 0) { onError = null; }
  17343. var loadedFiles = [];
  17344. loadedFiles._internalCount = 0;
  17345. for (var index = 0; index < 6; index++) {
  17346. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17347. }
  17348. };
  17349. // Statics
  17350. /**
  17351. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17352. * @returns true if the engine can be created
  17353. * @ignorenaming
  17354. */
  17355. Engine.isSupported = function () {
  17356. try {
  17357. var tempcanvas = document.createElement("canvas");
  17358. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17359. return gl != null && !!window.WebGLRenderingContext;
  17360. }
  17361. catch (e) {
  17362. return false;
  17363. }
  17364. };
  17365. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17366. Engine.ExceptionList = [
  17367. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17368. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17369. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17370. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17371. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17372. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17373. ];
  17374. /** Gets the list of created engines */
  17375. Engine.Instances = new Array();
  17376. /**
  17377. * Hidden
  17378. */
  17379. Engine._TextureLoaders = [];
  17380. // Const statics
  17381. /** Defines that alpha blending is disabled */
  17382. Engine.ALPHA_DISABLE = 0;
  17383. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17384. Engine.ALPHA_ADD = 1;
  17385. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17386. Engine.ALPHA_COMBINE = 2;
  17387. /** Defines that alpha blending to DEST - SRC * DEST */
  17388. Engine.ALPHA_SUBTRACT = 3;
  17389. /** Defines that alpha blending to SRC * DEST */
  17390. Engine.ALPHA_MULTIPLY = 4;
  17391. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17392. Engine.ALPHA_MAXIMIZED = 5;
  17393. /** Defines that alpha blending to SRC + DEST */
  17394. Engine.ALPHA_ONEONE = 6;
  17395. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17396. Engine.ALPHA_PREMULTIPLIED = 7;
  17397. /**
  17398. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17399. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17400. */
  17401. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17402. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17403. Engine.ALPHA_INTERPOLATE = 9;
  17404. /**
  17405. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17406. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17407. */
  17408. Engine.ALPHA_SCREENMODE = 10;
  17409. /** Defines that the ressource is not delayed*/
  17410. Engine.DELAYLOADSTATE_NONE = 0;
  17411. /** Defines that the ressource was successfully delay loaded */
  17412. Engine.DELAYLOADSTATE_LOADED = 1;
  17413. /** Defines that the ressource is currently delay loading */
  17414. Engine.DELAYLOADSTATE_LOADING = 2;
  17415. /** Defines that the ressource is delayed and has not started loading */
  17416. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17417. // Depht or Stencil test Constants.
  17418. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17419. Engine.NEVER = 0x0200;
  17420. /** 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 */
  17421. Engine.ALWAYS = 0x0207;
  17422. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17423. Engine.LESS = 0x0201;
  17424. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17425. Engine.EQUAL = 0x0202;
  17426. /** 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 */
  17427. Engine.LEQUAL = 0x0203;
  17428. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17429. Engine.GREATER = 0x0204;
  17430. /** 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 */
  17431. Engine.GEQUAL = 0x0206;
  17432. /** 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 */
  17433. Engine.NOTEQUAL = 0x0205;
  17434. // Stencil Actions Constants.
  17435. /** Passed to stencilOperation to specify that stencil value must be kept */
  17436. Engine.KEEP = 0x1E00;
  17437. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17438. Engine.REPLACE = 0x1E01;
  17439. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17440. Engine.INCR = 0x1E02;
  17441. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17442. Engine.DECR = 0x1E03;
  17443. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17444. Engine.INVERT = 0x150A;
  17445. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17446. Engine.INCR_WRAP = 0x8507;
  17447. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17448. Engine.DECR_WRAP = 0x8508;
  17449. /** Texture is not repeating outside of 0..1 UVs */
  17450. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17451. /** Texture is repeating outside of 0..1 UVs */
  17452. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17453. /** Texture is repeating and mirrored */
  17454. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17455. /** ALPHA */
  17456. Engine.TEXTUREFORMAT_ALPHA = 0;
  17457. /** LUMINANCE */
  17458. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17459. /** LUMINANCE_ALPHA */
  17460. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17461. /** RGB */
  17462. Engine.TEXTUREFORMAT_RGB = 4;
  17463. /** RGBA */
  17464. Engine.TEXTUREFORMAT_RGBA = 5;
  17465. /** RED */
  17466. Engine.TEXTUREFORMAT_RED = 6;
  17467. /** RED (2nd reference) */
  17468. Engine.TEXTUREFORMAT_R = 6;
  17469. /** RG */
  17470. Engine.TEXTUREFORMAT_RG = 7;
  17471. /** RED_INTEGER */
  17472. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17473. /** RED_INTEGER (2nd reference) */
  17474. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17475. /** RG_INTEGER */
  17476. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17477. /** RGB_INTEGER */
  17478. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17479. /** RGBA_INTEGER */
  17480. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17481. /** UNSIGNED_BYTE */
  17482. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17483. /** UNSIGNED_BYTE (2nd reference) */
  17484. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17485. /** FLOAT */
  17486. Engine.TEXTURETYPE_FLOAT = 1;
  17487. /** HALF_FLOAT */
  17488. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17489. /** BYTE */
  17490. Engine.TEXTURETYPE_BYTE = 3;
  17491. /** SHORT */
  17492. Engine.TEXTURETYPE_SHORT = 4;
  17493. /** UNSIGNED_SHORT */
  17494. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17495. /** INT */
  17496. Engine.TEXTURETYPE_INT = 6;
  17497. /** UNSIGNED_INT */
  17498. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17499. /** UNSIGNED_SHORT_4_4_4_4 */
  17500. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17501. /** UNSIGNED_SHORT_5_5_5_1 */
  17502. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17503. /** UNSIGNED_SHORT_5_6_5 */
  17504. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17505. /** UNSIGNED_INT_2_10_10_10_REV */
  17506. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17507. /** UNSIGNED_INT_24_8 */
  17508. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17509. /** UNSIGNED_INT_10F_11F_11F_REV */
  17510. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17511. /** UNSIGNED_INT_5_9_9_9_REV */
  17512. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17513. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17514. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17515. /** nearest is mag = nearest and min = nearest and mip = linear */
  17516. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17517. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17518. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17519. /** Trilinear is mag = linear and min = linear and mip = linear */
  17520. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17521. /** nearest is mag = nearest and min = nearest and mip = linear */
  17522. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17523. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17524. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17525. /** Trilinear is mag = linear and min = linear and mip = linear */
  17526. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17527. /** mag = nearest and min = nearest and mip = nearest */
  17528. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17529. /** mag = nearest and min = linear and mip = nearest */
  17530. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17531. /** mag = nearest and min = linear and mip = linear */
  17532. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17533. /** mag = nearest and min = linear and mip = none */
  17534. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17535. /** mag = nearest and min = nearest and mip = none */
  17536. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17537. /** mag = linear and min = nearest and mip = nearest */
  17538. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17539. /** mag = linear and min = nearest and mip = linear */
  17540. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17541. /** mag = linear and min = linear and mip = none */
  17542. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17543. /** mag = linear and min = nearest and mip = none */
  17544. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17545. /** Explicit coordinates mode */
  17546. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17547. /** Spherical coordinates mode */
  17548. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17549. /** Planar coordinates mode */
  17550. Engine.TEXTURE_PLANAR_MODE = 2;
  17551. /** Cubic coordinates mode */
  17552. Engine.TEXTURE_CUBIC_MODE = 3;
  17553. /** Projection coordinates mode */
  17554. Engine.TEXTURE_PROJECTION_MODE = 4;
  17555. /** Skybox coordinates mode */
  17556. Engine.TEXTURE_SKYBOX_MODE = 5;
  17557. /** Inverse Cubic coordinates mode */
  17558. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17559. /** Equirectangular coordinates mode */
  17560. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17561. /** Equirectangular Fixed coordinates mode */
  17562. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17563. /** Equirectangular Fixed Mirrored coordinates mode */
  17564. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17565. // Texture rescaling mode
  17566. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17567. Engine.SCALEMODE_FLOOR = 1;
  17568. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17569. Engine.SCALEMODE_NEAREST = 2;
  17570. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17571. Engine.SCALEMODE_CEILING = 3;
  17572. // Updatable statics so stick with vars here
  17573. /**
  17574. * Gets or sets the epsilon value used by collision engine
  17575. */
  17576. Engine.CollisionsEpsilon = 0.001;
  17577. /**
  17578. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17579. */
  17580. Engine.CodeRepository = "src/";
  17581. /**
  17582. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17583. */
  17584. Engine.ShadersRepository = "src/Shaders/";
  17585. return Engine;
  17586. }());
  17587. BABYLON.Engine = Engine;
  17588. })(BABYLON || (BABYLON = {}));
  17589. //# sourceMappingURL=babylon.engine.js.map
  17590. var BABYLON;
  17591. (function (BABYLON) {
  17592. /**
  17593. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17594. */
  17595. var Node = /** @class */ (function () {
  17596. /**
  17597. * Creates a new Node
  17598. * @param {string} name - the name and id to be given to this node
  17599. * @param {BABYLON.Scene} the scene this node will be added to
  17600. */
  17601. function Node(name, scene) {
  17602. if (scene === void 0) { scene = null; }
  17603. /**
  17604. * Gets or sets a string used to store user defined state for the node
  17605. */
  17606. this.state = "";
  17607. /**
  17608. * Gets or sets an object used to store user defined information for the node
  17609. */
  17610. this.metadata = null;
  17611. /**
  17612. * Gets or sets a boolean used to define if the node must be serialized
  17613. */
  17614. this.doNotSerialize = false;
  17615. /** @hidden */
  17616. this._isDisposed = false;
  17617. /**
  17618. * Gets a list of Animations associated with the node
  17619. */
  17620. this.animations = new Array();
  17621. this._ranges = {};
  17622. this._isEnabled = true;
  17623. this._isParentEnabled = true;
  17624. this._isReady = true;
  17625. /** @hidden */
  17626. this._currentRenderId = -1;
  17627. this._parentRenderId = -1;
  17628. this._childRenderId = -1;
  17629. /** @hidden */
  17630. this._worldMatrix = BABYLON.Matrix.Identity();
  17631. /** @hidden */
  17632. this._worldMatrixDeterminant = 0;
  17633. this._animationPropertiesOverride = null;
  17634. /**
  17635. * An event triggered when the mesh is disposed
  17636. */
  17637. this.onDisposeObservable = new BABYLON.Observable();
  17638. // Behaviors
  17639. this._behaviors = new Array();
  17640. this.name = name;
  17641. this.id = name;
  17642. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17643. this.uniqueId = this._scene.getUniqueId();
  17644. this._initCache();
  17645. this._scene.rootNodes.push(this);
  17646. }
  17647. /**
  17648. * Add a new node constructor
  17649. * @param type defines the type name of the node to construct
  17650. * @param constructorFunc defines the constructor function
  17651. */
  17652. Node.AddNodeConstructor = function (type, constructorFunc) {
  17653. this._NodeConstructors[type] = constructorFunc;
  17654. };
  17655. /**
  17656. * Returns a node constructor based on type name
  17657. * @param type defines the type name
  17658. * @param name defines the new node name
  17659. * @param scene defines the hosting scene
  17660. * @param options defines optional options to transmit to constructors
  17661. * @returns the new constructor or null
  17662. */
  17663. Node.Construct = function (type, name, scene, options) {
  17664. var constructorFunc = this._NodeConstructors[type];
  17665. if (!constructorFunc) {
  17666. return null;
  17667. }
  17668. return constructorFunc(name, scene, options);
  17669. };
  17670. /**
  17671. * Gets a boolean indicating if the node has been disposed
  17672. * @returns true if the node was disposed
  17673. */
  17674. Node.prototype.isDisposed = function () {
  17675. return this._isDisposed;
  17676. };
  17677. Object.defineProperty(Node.prototype, "parent", {
  17678. get: function () {
  17679. return this._parentNode;
  17680. },
  17681. /**
  17682. * Gets or sets the parent of the node
  17683. */
  17684. set: function (parent) {
  17685. if (this._parentNode === parent) {
  17686. return;
  17687. }
  17688. var previousParentNode = this._parentNode;
  17689. // Remove self from list of children of parent
  17690. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17691. var index = this._parentNode._children.indexOf(this);
  17692. if (index !== -1) {
  17693. this._parentNode._children.splice(index, 1);
  17694. }
  17695. if (!parent) {
  17696. // Need to add this node to the rootNodes
  17697. this._scene.rootNodes.push(this);
  17698. }
  17699. }
  17700. // Store new parent
  17701. this._parentNode = parent;
  17702. // Add as child to new parent
  17703. if (this._parentNode) {
  17704. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17705. this._parentNode._children = new Array();
  17706. }
  17707. this._parentNode._children.push(this);
  17708. if (!previousParentNode) {
  17709. // Need to remove from rootNodes
  17710. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17711. if (rootNodeIndex > -1) {
  17712. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17713. }
  17714. }
  17715. }
  17716. // Enabled state
  17717. this._syncParentEnabledState();
  17718. },
  17719. enumerable: true,
  17720. configurable: true
  17721. });
  17722. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17723. /**
  17724. * Gets or sets the animation properties override
  17725. */
  17726. get: function () {
  17727. if (!this._animationPropertiesOverride) {
  17728. return this._scene.animationPropertiesOverride;
  17729. }
  17730. return this._animationPropertiesOverride;
  17731. },
  17732. set: function (value) {
  17733. this._animationPropertiesOverride = value;
  17734. },
  17735. enumerable: true,
  17736. configurable: true
  17737. });
  17738. /**
  17739. * Gets a string idenfifying the name of the class
  17740. * @returns "Node" string
  17741. */
  17742. Node.prototype.getClassName = function () {
  17743. return "Node";
  17744. };
  17745. Object.defineProperty(Node.prototype, "onDispose", {
  17746. /**
  17747. * Sets a callback that will be raised when the node will be disposed
  17748. */
  17749. set: function (callback) {
  17750. if (this._onDisposeObserver) {
  17751. this.onDisposeObservable.remove(this._onDisposeObserver);
  17752. }
  17753. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17754. },
  17755. enumerable: true,
  17756. configurable: true
  17757. });
  17758. /**
  17759. * Gets the scene of the node
  17760. * @returns a {BABYLON.Scene}
  17761. */
  17762. Node.prototype.getScene = function () {
  17763. return this._scene;
  17764. };
  17765. /**
  17766. * Gets the engine of the node
  17767. * @returns a {BABYLON.Engine}
  17768. */
  17769. Node.prototype.getEngine = function () {
  17770. return this._scene.getEngine();
  17771. };
  17772. /**
  17773. * Attach a behavior to the node
  17774. * @see http://doc.babylonjs.com/features/behaviour
  17775. * @param behavior defines the behavior to attach
  17776. * @returns the current Node
  17777. */
  17778. Node.prototype.addBehavior = function (behavior) {
  17779. var _this = this;
  17780. var index = this._behaviors.indexOf(behavior);
  17781. if (index !== -1) {
  17782. return this;
  17783. }
  17784. behavior.init();
  17785. if (this._scene.isLoading) {
  17786. // We defer the attach when the scene will be loaded
  17787. this._scene.onDataLoadedObservable.addOnce(function () {
  17788. behavior.attach(_this);
  17789. });
  17790. }
  17791. else {
  17792. behavior.attach(this);
  17793. }
  17794. this._behaviors.push(behavior);
  17795. return this;
  17796. };
  17797. /**
  17798. * Remove an attached behavior
  17799. * @see http://doc.babylonjs.com/features/behaviour
  17800. * @param behavior defines the behavior to attach
  17801. * @returns the current Node
  17802. */
  17803. Node.prototype.removeBehavior = function (behavior) {
  17804. var index = this._behaviors.indexOf(behavior);
  17805. if (index === -1) {
  17806. return this;
  17807. }
  17808. this._behaviors[index].detach();
  17809. this._behaviors.splice(index, 1);
  17810. return this;
  17811. };
  17812. Object.defineProperty(Node.prototype, "behaviors", {
  17813. /**
  17814. * Gets the list of attached behaviors
  17815. * @see http://doc.babylonjs.com/features/behaviour
  17816. */
  17817. get: function () {
  17818. return this._behaviors;
  17819. },
  17820. enumerable: true,
  17821. configurable: true
  17822. });
  17823. /**
  17824. * Gets an attached behavior by name
  17825. * @param name defines the name of the behavior to look for
  17826. * @see http://doc.babylonjs.com/features/behaviour
  17827. * @returns null if behavior was not found else the requested behavior
  17828. */
  17829. Node.prototype.getBehaviorByName = function (name) {
  17830. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17831. var behavior = _a[_i];
  17832. if (behavior.name === name) {
  17833. return behavior;
  17834. }
  17835. }
  17836. return null;
  17837. };
  17838. /**
  17839. * Returns the latest update of the World matrix
  17840. * @returns a Matrix
  17841. */
  17842. Node.prototype.getWorldMatrix = function () {
  17843. if (this._currentRenderId !== this._scene.getRenderId()) {
  17844. this.computeWorldMatrix();
  17845. }
  17846. return this._worldMatrix;
  17847. };
  17848. /** @hidden */
  17849. Node.prototype._getWorldMatrixDeterminant = function () {
  17850. return this._worldMatrixDeterminant;
  17851. };
  17852. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17853. /**
  17854. * Returns directly the latest state of the mesh World matrix.
  17855. * A Matrix is returned.
  17856. */
  17857. get: function () {
  17858. return this._worldMatrix;
  17859. },
  17860. enumerable: true,
  17861. configurable: true
  17862. });
  17863. // override it in derived class if you add new variables to the cache
  17864. // and call the parent class method
  17865. /** @hidden */
  17866. Node.prototype._initCache = function () {
  17867. this._cache = {};
  17868. this._cache.parent = undefined;
  17869. };
  17870. /** @hidden */
  17871. Node.prototype.updateCache = function (force) {
  17872. if (!force && this.isSynchronized())
  17873. return;
  17874. this._cache.parent = this.parent;
  17875. this._updateCache();
  17876. };
  17877. // override it in derived class if you add new variables to the cache
  17878. // and call the parent class method if !ignoreParentClass
  17879. /** @hidden */
  17880. Node.prototype._updateCache = function (ignoreParentClass) {
  17881. };
  17882. // override it in derived class if you add new variables to the cache
  17883. /** @hidden */
  17884. Node.prototype._isSynchronized = function () {
  17885. return true;
  17886. };
  17887. /** @hidden */
  17888. Node.prototype._markSyncedWithParent = function () {
  17889. if (this._parentNode) {
  17890. this._parentRenderId = this._parentNode._childRenderId;
  17891. }
  17892. };
  17893. /** @hidden */
  17894. Node.prototype.isSynchronizedWithParent = function () {
  17895. if (!this._parentNode) {
  17896. return true;
  17897. }
  17898. if (this._parentRenderId !== this._parentNode._childRenderId) {
  17899. return false;
  17900. }
  17901. return this._parentNode.isSynchronized();
  17902. };
  17903. /** @hidden */
  17904. Node.prototype.isSynchronized = function () {
  17905. if (this._cache.parent != this._parentNode) {
  17906. this._cache.parent = this._parentNode;
  17907. return false;
  17908. }
  17909. if (this._parentNode && !this.isSynchronizedWithParent()) {
  17910. return false;
  17911. }
  17912. return this._isSynchronized();
  17913. };
  17914. /**
  17915. * Is this node ready to be used/rendered
  17916. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17917. * @return true if the node is ready
  17918. */
  17919. Node.prototype.isReady = function (completeCheck) {
  17920. if (completeCheck === void 0) { completeCheck = false; }
  17921. return this._isReady;
  17922. };
  17923. /**
  17924. * Is this node enabled?
  17925. * 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
  17926. * @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
  17927. * @return whether this node (and its parent) is enabled
  17928. */
  17929. Node.prototype.isEnabled = function (checkAncestors) {
  17930. if (checkAncestors === void 0) { checkAncestors = true; }
  17931. if (checkAncestors === false) {
  17932. return this._isEnabled;
  17933. }
  17934. if (!this._isEnabled) {
  17935. return false;
  17936. }
  17937. return this._isParentEnabled;
  17938. };
  17939. /** @hidden */
  17940. Node.prototype._syncParentEnabledState = function () {
  17941. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  17942. if (this._children) {
  17943. this._children.forEach(function (c) {
  17944. c._syncParentEnabledState(); // Force children to update accordingly
  17945. });
  17946. }
  17947. };
  17948. /**
  17949. * Set the enabled state of this node
  17950. * @param value defines the new enabled state
  17951. */
  17952. Node.prototype.setEnabled = function (value) {
  17953. this._isEnabled = value;
  17954. this._syncParentEnabledState();
  17955. };
  17956. /**
  17957. * Is this node a descendant of the given node?
  17958. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17959. * @param ancestor defines the parent node to inspect
  17960. * @returns a boolean indicating if this node is a descendant of the given node
  17961. */
  17962. Node.prototype.isDescendantOf = function (ancestor) {
  17963. if (this.parent) {
  17964. if (this.parent === ancestor) {
  17965. return true;
  17966. }
  17967. return this.parent.isDescendantOf(ancestor);
  17968. }
  17969. return false;
  17970. };
  17971. /** @hidden */
  17972. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17973. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17974. if (!this._children) {
  17975. return;
  17976. }
  17977. for (var index = 0; index < this._children.length; index++) {
  17978. var item = this._children[index];
  17979. if (!predicate || predicate(item)) {
  17980. results.push(item);
  17981. }
  17982. if (!directDescendantsOnly) {
  17983. item._getDescendants(results, false, predicate);
  17984. }
  17985. }
  17986. };
  17987. /**
  17988. * Will return all nodes that have this node as ascendant
  17989. * @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
  17990. * @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
  17991. * @return all children nodes of all types
  17992. */
  17993. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17994. var results = new Array();
  17995. this._getDescendants(results, directDescendantsOnly, predicate);
  17996. return results;
  17997. };
  17998. /**
  17999. * Get all child-meshes of this node
  18000. * @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
  18001. * @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
  18002. * @returns an array of {BABYLON.AbstractMesh}
  18003. */
  18004. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18005. var results = [];
  18006. this._getDescendants(results, directDescendantsOnly, function (node) {
  18007. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18008. });
  18009. return results;
  18010. };
  18011. /**
  18012. * Get all child-transformNodes of this node
  18013. * @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
  18014. * @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
  18015. * @returns an array of {BABYLON.TransformNode}
  18016. */
  18017. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18018. var results = [];
  18019. this._getDescendants(results, directDescendantsOnly, function (node) {
  18020. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18021. });
  18022. return results;
  18023. };
  18024. /**
  18025. * Get all direct children of this node
  18026. * @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
  18027. * @returns an array of {BABYLON.Node}
  18028. */
  18029. Node.prototype.getChildren = function (predicate) {
  18030. if (!predicate) {
  18031. return this._children;
  18032. }
  18033. return this.getDescendants(true, predicate);
  18034. };
  18035. /** @hidden */
  18036. Node.prototype._setReady = function (state) {
  18037. if (state === this._isReady) {
  18038. return;
  18039. }
  18040. if (!state) {
  18041. this._isReady = false;
  18042. return;
  18043. }
  18044. if (this.onReady) {
  18045. this.onReady(this);
  18046. }
  18047. this._isReady = true;
  18048. };
  18049. /**
  18050. * Get an animation by name
  18051. * @param name defines the name of the animation to look for
  18052. * @returns null if not found else the requested animation
  18053. */
  18054. Node.prototype.getAnimationByName = function (name) {
  18055. for (var i = 0; i < this.animations.length; i++) {
  18056. var animation = this.animations[i];
  18057. if (animation.name === name) {
  18058. return animation;
  18059. }
  18060. }
  18061. return null;
  18062. };
  18063. /**
  18064. * Creates an animation range for this node
  18065. * @param name defines the name of the range
  18066. * @param from defines the starting key
  18067. * @param to defines the end key
  18068. */
  18069. Node.prototype.createAnimationRange = function (name, from, to) {
  18070. // check name not already in use
  18071. if (!this._ranges[name]) {
  18072. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18073. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18074. if (this.animations[i]) {
  18075. this.animations[i].createRange(name, from, to);
  18076. }
  18077. }
  18078. }
  18079. };
  18080. /**
  18081. * Delete a specific animation range
  18082. * @param name defines the name of the range to delete
  18083. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18084. */
  18085. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18086. if (deleteFrames === void 0) { deleteFrames = true; }
  18087. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18088. if (this.animations[i]) {
  18089. this.animations[i].deleteRange(name, deleteFrames);
  18090. }
  18091. }
  18092. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18093. };
  18094. /**
  18095. * Get an animation range by name
  18096. * @param name defines the name of the animation range to look for
  18097. * @returns null if not found else the requested animation range
  18098. */
  18099. Node.prototype.getAnimationRange = function (name) {
  18100. return this._ranges[name];
  18101. };
  18102. /**
  18103. * Will start the animation sequence
  18104. * @param name defines the range frames for animation sequence
  18105. * @param loop defines if the animation should loop (false by default)
  18106. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18107. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18108. * @returns the object created for this animation. If range does not exist, it will return null
  18109. */
  18110. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18111. var range = this.getAnimationRange(name);
  18112. if (!range) {
  18113. return null;
  18114. }
  18115. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18116. };
  18117. /**
  18118. * Serialize animation ranges into a JSON compatible object
  18119. * @returns serialization object
  18120. */
  18121. Node.prototype.serializeAnimationRanges = function () {
  18122. var serializationRanges = [];
  18123. for (var name in this._ranges) {
  18124. var localRange = this._ranges[name];
  18125. if (!localRange) {
  18126. continue;
  18127. }
  18128. var range = {};
  18129. range.name = name;
  18130. range.from = localRange.from;
  18131. range.to = localRange.to;
  18132. serializationRanges.push(range);
  18133. }
  18134. return serializationRanges;
  18135. };
  18136. /**
  18137. * Computes the world matrix of the node
  18138. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18139. * @returns the world matrix
  18140. */
  18141. Node.prototype.computeWorldMatrix = function (force) {
  18142. if (!this._worldMatrix) {
  18143. this._worldMatrix = BABYLON.Matrix.Identity();
  18144. }
  18145. return this._worldMatrix;
  18146. };
  18147. /**
  18148. * Releases resources associated with this node.
  18149. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18150. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18151. */
  18152. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18153. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18154. if (!doNotRecurse) {
  18155. var nodes = this.getDescendants(true);
  18156. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18157. var node = nodes_1[_i];
  18158. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18159. }
  18160. }
  18161. else {
  18162. var transformNodes = this.getChildTransformNodes(true);
  18163. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18164. var transformNode = transformNodes_1[_a];
  18165. transformNode.parent = null;
  18166. transformNode.computeWorldMatrix(true);
  18167. }
  18168. }
  18169. if (!this.parent) {
  18170. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18171. if (rootNodeIndex > -1) {
  18172. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18173. }
  18174. }
  18175. else {
  18176. this.parent = null;
  18177. }
  18178. // Callback
  18179. this.onDisposeObservable.notifyObservers(this);
  18180. this.onDisposeObservable.clear();
  18181. // Behaviors
  18182. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18183. var behavior = _c[_b];
  18184. behavior.detach();
  18185. }
  18186. this._behaviors = [];
  18187. this._isDisposed = true;
  18188. };
  18189. /**
  18190. * Parse animation range data from a serialization object and store them into a given node
  18191. * @param node defines where to store the animation ranges
  18192. * @param parsedNode defines the serialization object to read data from
  18193. * @param scene defines the hosting scene
  18194. */
  18195. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18196. if (parsedNode.ranges) {
  18197. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18198. var data = parsedNode.ranges[index];
  18199. node.createAnimationRange(data.name, data.from, data.to);
  18200. }
  18201. }
  18202. };
  18203. Node._NodeConstructors = {};
  18204. __decorate([
  18205. BABYLON.serialize()
  18206. ], Node.prototype, "name", void 0);
  18207. __decorate([
  18208. BABYLON.serialize()
  18209. ], Node.prototype, "id", void 0);
  18210. __decorate([
  18211. BABYLON.serialize()
  18212. ], Node.prototype, "uniqueId", void 0);
  18213. __decorate([
  18214. BABYLON.serialize()
  18215. ], Node.prototype, "state", void 0);
  18216. __decorate([
  18217. BABYLON.serialize()
  18218. ], Node.prototype, "metadata", void 0);
  18219. return Node;
  18220. }());
  18221. BABYLON.Node = Node;
  18222. })(BABYLON || (BABYLON = {}));
  18223. //# sourceMappingURL=babylon.node.js.map
  18224. var BABYLON;
  18225. (function (BABYLON) {
  18226. // This matrix is used as a value to reset the bounding box.
  18227. var _identityMatrix = BABYLON.Matrix.Identity();
  18228. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18229. var BoundingSphere = /** @class */ (function () {
  18230. /**
  18231. * Creates a new bounding sphere
  18232. * @param min defines the minimum vector (in local space)
  18233. * @param max defines the maximum vector (in local space)
  18234. */
  18235. function BoundingSphere(min, max) {
  18236. this.center = BABYLON.Vector3.Zero();
  18237. this.centerWorld = BABYLON.Vector3.Zero();
  18238. this.reConstruct(min, max);
  18239. }
  18240. /**
  18241. * Recreates the entire bounding sphere 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. BoundingSphere.prototype.reConstruct = function (min, max) {
  18246. this.minimum = min.clone();
  18247. this.maximum = max.clone();
  18248. var distance = BABYLON.Vector3.Distance(min, max);
  18249. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18250. this.radius = distance * 0.5;
  18251. this.centerWorld.set(0, 0, 0);
  18252. this._update(_identityMatrix);
  18253. };
  18254. /**
  18255. * Scale the current bounding sphere by applying a scale factor
  18256. * @param factor defines the scale factor to apply
  18257. * @returns the current bounding box
  18258. */
  18259. BoundingSphere.prototype.scale = function (factor) {
  18260. var newRadius = this.radius * factor;
  18261. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18262. var min = this.center.subtract(_tempRadiusVector);
  18263. var max = this.center.add(_tempRadiusVector);
  18264. this.reConstruct(min, max);
  18265. return this;
  18266. };
  18267. // Methods
  18268. /** @hidden */
  18269. BoundingSphere.prototype._update = function (world) {
  18270. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18271. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18272. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18273. };
  18274. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18275. for (var i = 0; i < 6; i++) {
  18276. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18277. return false;
  18278. }
  18279. return true;
  18280. };
  18281. BoundingSphere.prototype.intersectsPoint = function (point) {
  18282. var x = this.centerWorld.x - point.x;
  18283. var y = this.centerWorld.y - point.y;
  18284. var z = this.centerWorld.z - point.z;
  18285. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18286. if (this.radiusWorld < distance)
  18287. return false;
  18288. return true;
  18289. };
  18290. // Statics
  18291. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18292. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18293. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18294. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18295. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18296. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18297. return false;
  18298. return true;
  18299. };
  18300. return BoundingSphere;
  18301. }());
  18302. BABYLON.BoundingSphere = BoundingSphere;
  18303. })(BABYLON || (BABYLON = {}));
  18304. //# sourceMappingURL=babylon.boundingSphere.js.map
  18305. var BABYLON;
  18306. (function (BABYLON) {
  18307. var BoundingBox = /** @class */ (function () {
  18308. /**
  18309. * Creates a new bounding box
  18310. * @param min defines the minimum vector (in local space)
  18311. * @param max defines the maximum vector (in local space)
  18312. */
  18313. function BoundingBox(min, max) {
  18314. this.vectorsWorld = new Array();
  18315. this.reConstruct(min, max);
  18316. }
  18317. // Methods
  18318. /**
  18319. * Recreates the entire bounding box from scratch
  18320. * @param min defines the new minimum vector (in local space)
  18321. * @param max defines the new maximum vector (in local space)
  18322. */
  18323. BoundingBox.prototype.reConstruct = function (min, max) {
  18324. this.minimum = min.clone();
  18325. this.maximum = max.clone();
  18326. // Bounding vectors
  18327. this.vectors = [
  18328. this.minimum.clone(),
  18329. this.maximum.clone(),
  18330. this.minimum.clone(),
  18331. this.minimum.clone(),
  18332. this.minimum.clone(),
  18333. this.maximum.clone(),
  18334. this.maximum.clone(),
  18335. this.maximum.clone()
  18336. ];
  18337. this.vectors[2].x = this.maximum.x;
  18338. this.vectors[3].y = this.maximum.y;
  18339. this.vectors[4].z = this.maximum.z;
  18340. this.vectors[5].z = this.minimum.z;
  18341. this.vectors[6].x = this.minimum.x;
  18342. this.vectors[7].y = this.minimum.y;
  18343. // OBB
  18344. this.center = this.maximum.add(this.minimum).scale(0.5);
  18345. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18346. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18347. // World
  18348. for (var index = 0; index < this.vectors.length; index++) {
  18349. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18350. }
  18351. this.minimumWorld = BABYLON.Vector3.Zero();
  18352. this.maximumWorld = BABYLON.Vector3.Zero();
  18353. this.centerWorld = BABYLON.Vector3.Zero();
  18354. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18355. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18356. };
  18357. /**
  18358. * Scale the current bounding box by applying a scale factor
  18359. * @param factor defines the scale factor to apply
  18360. * @returns the current bounding box
  18361. */
  18362. BoundingBox.prototype.scale = function (factor) {
  18363. var diff = this.maximum.subtract(this.minimum);
  18364. var distance = diff.length() * factor;
  18365. diff.normalize();
  18366. var newRadius = diff.scale(distance / 2);
  18367. var min = this.center.subtract(newRadius);
  18368. var max = this.center.add(newRadius);
  18369. this.reConstruct(min, max);
  18370. return this;
  18371. };
  18372. BoundingBox.prototype.getWorldMatrix = function () {
  18373. return this._worldMatrix;
  18374. };
  18375. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18376. this._worldMatrix.copyFrom(matrix);
  18377. return this;
  18378. };
  18379. /** @hidden */
  18380. BoundingBox.prototype._update = function (world) {
  18381. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18382. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18383. for (var index = 0; index < this.vectors.length; index++) {
  18384. var v = this.vectorsWorld[index];
  18385. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18386. if (v.x < this.minimumWorld.x)
  18387. this.minimumWorld.x = v.x;
  18388. if (v.y < this.minimumWorld.y)
  18389. this.minimumWorld.y = v.y;
  18390. if (v.z < this.minimumWorld.z)
  18391. this.minimumWorld.z = v.z;
  18392. if (v.x > this.maximumWorld.x)
  18393. this.maximumWorld.x = v.x;
  18394. if (v.y > this.maximumWorld.y)
  18395. this.maximumWorld.y = v.y;
  18396. if (v.z > this.maximumWorld.z)
  18397. this.maximumWorld.z = v.z;
  18398. }
  18399. // Extend
  18400. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18401. this.extendSizeWorld.scaleInPlace(0.5);
  18402. // OBB
  18403. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18404. this.centerWorld.scaleInPlace(0.5);
  18405. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18406. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18407. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18408. this._worldMatrix = world;
  18409. };
  18410. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18411. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18412. };
  18413. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18414. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18415. };
  18416. BoundingBox.prototype.intersectsPoint = function (point) {
  18417. var delta = -BABYLON.Epsilon;
  18418. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18419. return false;
  18420. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18421. return false;
  18422. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18423. return false;
  18424. return true;
  18425. };
  18426. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18427. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18428. };
  18429. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18430. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18431. return false;
  18432. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18433. return false;
  18434. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18435. return false;
  18436. return true;
  18437. };
  18438. // Statics
  18439. BoundingBox.Intersects = function (box0, box1) {
  18440. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18441. return false;
  18442. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18443. return false;
  18444. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18445. return false;
  18446. return true;
  18447. };
  18448. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18449. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18450. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18451. return (num <= (sphereRadius * sphereRadius));
  18452. };
  18453. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18454. for (var p = 0; p < 6; p++) {
  18455. for (var i = 0; i < 8; i++) {
  18456. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18457. return false;
  18458. }
  18459. }
  18460. }
  18461. return true;
  18462. };
  18463. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18464. for (var p = 0; p < 6; p++) {
  18465. var inCount = 8;
  18466. for (var i = 0; i < 8; i++) {
  18467. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18468. --inCount;
  18469. }
  18470. else {
  18471. break;
  18472. }
  18473. }
  18474. if (inCount === 0)
  18475. return false;
  18476. }
  18477. return true;
  18478. };
  18479. return BoundingBox;
  18480. }());
  18481. BABYLON.BoundingBox = BoundingBox;
  18482. })(BABYLON || (BABYLON = {}));
  18483. //# sourceMappingURL=babylon.boundingBox.js.map
  18484. var BABYLON;
  18485. (function (BABYLON) {
  18486. var computeBoxExtents = function (axis, box) {
  18487. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18488. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18489. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18490. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18491. var r = r0 + r1 + r2;
  18492. return {
  18493. min: p - r,
  18494. max: p + r
  18495. };
  18496. };
  18497. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18498. var axisOverlap = function (axis, box0, box1) {
  18499. var result0 = computeBoxExtents(axis, box0);
  18500. var result1 = computeBoxExtents(axis, box1);
  18501. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18502. };
  18503. var BoundingInfo = /** @class */ (function () {
  18504. function BoundingInfo(minimum, maximum) {
  18505. this.minimum = minimum;
  18506. this.maximum = maximum;
  18507. this._isLocked = false;
  18508. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18509. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18510. }
  18511. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18512. get: function () {
  18513. return this._isLocked;
  18514. },
  18515. set: function (value) {
  18516. this._isLocked = value;
  18517. },
  18518. enumerable: true,
  18519. configurable: true
  18520. });
  18521. // Methods
  18522. BoundingInfo.prototype.update = function (world) {
  18523. if (this._isLocked) {
  18524. return;
  18525. }
  18526. this.boundingBox._update(world);
  18527. this.boundingSphere._update(world);
  18528. };
  18529. /**
  18530. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18531. * @param center New center of the bounding info
  18532. * @param extend New extend of the bounding info
  18533. */
  18534. BoundingInfo.prototype.centerOn = function (center, extend) {
  18535. this.minimum = center.subtract(extend);
  18536. this.maximum = center.add(extend);
  18537. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18538. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18539. return this;
  18540. };
  18541. /**
  18542. * Scale the current bounding info by applying a scale factor
  18543. * @param factor defines the scale factor to apply
  18544. * @returns the current bounding info
  18545. */
  18546. BoundingInfo.prototype.scale = function (factor) {
  18547. this.boundingBox.scale(factor);
  18548. this.boundingSphere.scale(factor);
  18549. return this;
  18550. };
  18551. /**
  18552. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18553. * @param frustumPlanes defines the frustum to test
  18554. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18555. * @returns true if the bounding info is in the frustum planes
  18556. */
  18557. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18558. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18559. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18560. return false;
  18561. }
  18562. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18563. return true;
  18564. }
  18565. return this.boundingBox.isInFrustum(frustumPlanes);
  18566. };
  18567. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18568. /**
  18569. * Gets the world distance between the min and max points of the bounding box
  18570. */
  18571. get: function () {
  18572. var boundingBox = this.boundingBox;
  18573. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18574. return size.length();
  18575. },
  18576. enumerable: true,
  18577. configurable: true
  18578. });
  18579. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18580. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18581. };
  18582. /** @hidden */
  18583. BoundingInfo.prototype._checkCollision = function (collider) {
  18584. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18585. };
  18586. BoundingInfo.prototype.intersectsPoint = function (point) {
  18587. if (!this.boundingSphere.centerWorld) {
  18588. return false;
  18589. }
  18590. if (!this.boundingSphere.intersectsPoint(point)) {
  18591. return false;
  18592. }
  18593. if (!this.boundingBox.intersectsPoint(point)) {
  18594. return false;
  18595. }
  18596. return true;
  18597. };
  18598. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18599. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18600. return false;
  18601. }
  18602. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18603. return false;
  18604. }
  18605. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18606. return false;
  18607. }
  18608. if (!precise) {
  18609. return true;
  18610. }
  18611. var box0 = this.boundingBox;
  18612. var box1 = boundingInfo.boundingBox;
  18613. if (!axisOverlap(box0.directions[0], box0, box1))
  18614. return false;
  18615. if (!axisOverlap(box0.directions[1], box0, box1))
  18616. return false;
  18617. if (!axisOverlap(box0.directions[2], box0, box1))
  18618. return false;
  18619. if (!axisOverlap(box1.directions[0], box0, box1))
  18620. return false;
  18621. if (!axisOverlap(box1.directions[1], box0, box1))
  18622. return false;
  18623. if (!axisOverlap(box1.directions[2], box0, box1))
  18624. return false;
  18625. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18626. return false;
  18627. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18628. return false;
  18629. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18630. return false;
  18631. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18632. return false;
  18633. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18634. return false;
  18635. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18636. return false;
  18637. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18638. return false;
  18639. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18640. return false;
  18641. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18642. return false;
  18643. return true;
  18644. };
  18645. return BoundingInfo;
  18646. }());
  18647. BABYLON.BoundingInfo = BoundingInfo;
  18648. })(BABYLON || (BABYLON = {}));
  18649. //# sourceMappingURL=babylon.boundingInfo.js.map
  18650. var BABYLON;
  18651. (function (BABYLON) {
  18652. var TransformNode = /** @class */ (function (_super) {
  18653. __extends(TransformNode, _super);
  18654. function TransformNode(name, scene, isPure) {
  18655. if (scene === void 0) { scene = null; }
  18656. if (isPure === void 0) { isPure = true; }
  18657. var _this = _super.call(this, name, scene) || this;
  18658. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18659. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18660. _this._up = new BABYLON.Vector3(0, 1, 0);
  18661. _this._right = new BABYLON.Vector3(1, 0, 0);
  18662. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18663. // Properties
  18664. _this._position = BABYLON.Vector3.Zero();
  18665. _this._rotation = BABYLON.Vector3.Zero();
  18666. _this._scaling = BABYLON.Vector3.One();
  18667. _this._isDirty = false;
  18668. /**
  18669. * Set the billboard mode. Default is 0.
  18670. *
  18671. * | Value | Type | Description |
  18672. * | --- | --- | --- |
  18673. * | 0 | BILLBOARDMODE_NONE | |
  18674. * | 1 | BILLBOARDMODE_X | |
  18675. * | 2 | BILLBOARDMODE_Y | |
  18676. * | 4 | BILLBOARDMODE_Z | |
  18677. * | 7 | BILLBOARDMODE_ALL | |
  18678. *
  18679. */
  18680. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18681. _this.scalingDeterminant = 1;
  18682. _this.infiniteDistance = false;
  18683. /**
  18684. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18685. * By default the system will update normals to compensate
  18686. */
  18687. _this.ignoreNonUniformScaling = false;
  18688. _this._localWorld = BABYLON.Matrix.Zero();
  18689. _this._absolutePosition = BABYLON.Vector3.Zero();
  18690. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18691. _this._postMultiplyPivotMatrix = false;
  18692. _this._isWorldMatrixFrozen = false;
  18693. /**
  18694. * An event triggered after the world matrix is updated
  18695. */
  18696. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18697. _this._nonUniformScaling = false;
  18698. if (isPure) {
  18699. _this.getScene().addTransformNode(_this);
  18700. }
  18701. return _this;
  18702. }
  18703. /**
  18704. * Gets a string identifying the name of the class
  18705. * @returns "TransformNode" string
  18706. */
  18707. TransformNode.prototype.getClassName = function () {
  18708. return "TransformNode";
  18709. };
  18710. Object.defineProperty(TransformNode.prototype, "position", {
  18711. /**
  18712. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18713. */
  18714. get: function () {
  18715. return this._position;
  18716. },
  18717. set: function (newPosition) {
  18718. this._position = newPosition;
  18719. this._isDirty = true;
  18720. },
  18721. enumerable: true,
  18722. configurable: true
  18723. });
  18724. Object.defineProperty(TransformNode.prototype, "rotation", {
  18725. /**
  18726. * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18727. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18728. */
  18729. get: function () {
  18730. return this._rotation;
  18731. },
  18732. set: function (newRotation) {
  18733. this._rotation = newRotation;
  18734. this._isDirty = true;
  18735. },
  18736. enumerable: true,
  18737. configurable: true
  18738. });
  18739. Object.defineProperty(TransformNode.prototype, "scaling", {
  18740. /**
  18741. * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18742. */
  18743. get: function () {
  18744. return this._scaling;
  18745. },
  18746. set: function (newScaling) {
  18747. this._scaling = newScaling;
  18748. this._isDirty = true;
  18749. },
  18750. enumerable: true,
  18751. configurable: true
  18752. });
  18753. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18754. /**
  18755. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18756. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18757. */
  18758. get: function () {
  18759. return this._rotationQuaternion;
  18760. },
  18761. set: function (quaternion) {
  18762. this._rotationQuaternion = quaternion;
  18763. //reset the rotation vector.
  18764. if (quaternion && this.rotation.length()) {
  18765. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18766. }
  18767. },
  18768. enumerable: true,
  18769. configurable: true
  18770. });
  18771. Object.defineProperty(TransformNode.prototype, "forward", {
  18772. /**
  18773. * The forward direction of that transform in world space.
  18774. */
  18775. get: function () {
  18776. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18777. },
  18778. enumerable: true,
  18779. configurable: true
  18780. });
  18781. Object.defineProperty(TransformNode.prototype, "up", {
  18782. /**
  18783. * The up direction of that transform in world space.
  18784. */
  18785. get: function () {
  18786. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18787. },
  18788. enumerable: true,
  18789. configurable: true
  18790. });
  18791. Object.defineProperty(TransformNode.prototype, "right", {
  18792. /**
  18793. * The right direction of that transform in world space.
  18794. */
  18795. get: function () {
  18796. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18797. },
  18798. enumerable: true,
  18799. configurable: true
  18800. });
  18801. /**
  18802. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18803. * Returns the TransformNode.
  18804. */
  18805. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18806. this._poseMatrix.copyFrom(matrix);
  18807. return this;
  18808. };
  18809. /**
  18810. * Returns the mesh Pose matrix.
  18811. * Returned object : Matrix
  18812. */
  18813. TransformNode.prototype.getPoseMatrix = function () {
  18814. return this._poseMatrix;
  18815. };
  18816. /** @hidden */
  18817. TransformNode.prototype._isSynchronized = function () {
  18818. if (this._isDirty) {
  18819. return false;
  18820. }
  18821. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18822. return false;
  18823. if (this._cache.pivotMatrixUpdated) {
  18824. return false;
  18825. }
  18826. if (this.infiniteDistance) {
  18827. return false;
  18828. }
  18829. if (!this._cache.position.equals(this._position))
  18830. return false;
  18831. if (this._rotationQuaternion) {
  18832. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18833. return false;
  18834. }
  18835. else if (!this._cache.rotation.equals(this._rotation))
  18836. return false;
  18837. if (!this._cache.scaling.equals(this._scaling))
  18838. return false;
  18839. return true;
  18840. };
  18841. /** @hidden */
  18842. TransformNode.prototype._initCache = function () {
  18843. _super.prototype._initCache.call(this);
  18844. this._cache.localMatrixUpdated = false;
  18845. this._cache.position = BABYLON.Vector3.Zero();
  18846. this._cache.scaling = BABYLON.Vector3.Zero();
  18847. this._cache.rotation = BABYLON.Vector3.Zero();
  18848. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18849. this._cache.billboardMode = -1;
  18850. };
  18851. TransformNode.prototype.markAsDirty = function (property) {
  18852. if (property === "rotation") {
  18853. this.rotationQuaternion = null;
  18854. }
  18855. this._currentRenderId = Number.MAX_VALUE;
  18856. this._isDirty = true;
  18857. return this;
  18858. };
  18859. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18860. /**
  18861. * Returns the current mesh absolute position.
  18862. * Returns a Vector3.
  18863. */
  18864. get: function () {
  18865. return this._absolutePosition;
  18866. },
  18867. enumerable: true,
  18868. configurable: true
  18869. });
  18870. /**
  18871. * Sets a new matrix to apply before all other transformation
  18872. * @param matrix defines the transform matrix
  18873. * @returns the current TransformNode
  18874. */
  18875. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18876. return this.setPivotMatrix(matrix, false);
  18877. };
  18878. /**
  18879. * Sets a new pivot matrix to the current node
  18880. * @param matrix defines the new pivot matrix to use
  18881. * @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
  18882. * @returns the current TransformNode
  18883. */
  18884. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18885. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18886. this._pivotMatrix = matrix.clone();
  18887. this._cache.pivotMatrixUpdated = true;
  18888. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18889. if (this._postMultiplyPivotMatrix) {
  18890. if (!this._pivotMatrixInverse) {
  18891. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18892. }
  18893. else {
  18894. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18895. }
  18896. }
  18897. return this;
  18898. };
  18899. /**
  18900. * Returns the mesh pivot matrix.
  18901. * Default : Identity.
  18902. * A Matrix is returned.
  18903. */
  18904. TransformNode.prototype.getPivotMatrix = function () {
  18905. return this._pivotMatrix;
  18906. };
  18907. /**
  18908. * Prevents the World matrix to be computed any longer.
  18909. * Returns the TransformNode.
  18910. */
  18911. TransformNode.prototype.freezeWorldMatrix = function () {
  18912. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18913. this.computeWorldMatrix(true);
  18914. this._isWorldMatrixFrozen = true;
  18915. return this;
  18916. };
  18917. /**
  18918. * Allows back the World matrix computation.
  18919. * Returns the TransformNode.
  18920. */
  18921. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18922. this._isWorldMatrixFrozen = false;
  18923. this.computeWorldMatrix(true);
  18924. return this;
  18925. };
  18926. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18927. /**
  18928. * True if the World matrix has been frozen.
  18929. * Returns a boolean.
  18930. */
  18931. get: function () {
  18932. return this._isWorldMatrixFrozen;
  18933. },
  18934. enumerable: true,
  18935. configurable: true
  18936. });
  18937. /**
  18938. * Retuns the mesh absolute position in the World.
  18939. * Returns a Vector3.
  18940. */
  18941. TransformNode.prototype.getAbsolutePosition = function () {
  18942. this.computeWorldMatrix();
  18943. return this._absolutePosition;
  18944. };
  18945. /**
  18946. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18947. * Returns the TransformNode.
  18948. */
  18949. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18950. if (!absolutePosition) {
  18951. return this;
  18952. }
  18953. var absolutePositionX;
  18954. var absolutePositionY;
  18955. var absolutePositionZ;
  18956. if (absolutePosition.x === undefined) {
  18957. if (arguments.length < 3) {
  18958. return this;
  18959. }
  18960. absolutePositionX = arguments[0];
  18961. absolutePositionY = arguments[1];
  18962. absolutePositionZ = arguments[2];
  18963. }
  18964. else {
  18965. absolutePositionX = absolutePosition.x;
  18966. absolutePositionY = absolutePosition.y;
  18967. absolutePositionZ = absolutePosition.z;
  18968. }
  18969. if (this.parent) {
  18970. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18971. invertParentWorldMatrix.invert();
  18972. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18973. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18974. }
  18975. else {
  18976. this.position.x = absolutePositionX;
  18977. this.position.y = absolutePositionY;
  18978. this.position.z = absolutePositionZ;
  18979. }
  18980. return this;
  18981. };
  18982. /**
  18983. * Sets the mesh position in its local space.
  18984. * Returns the TransformNode.
  18985. */
  18986. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18987. this.computeWorldMatrix();
  18988. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18989. return this;
  18990. };
  18991. /**
  18992. * Returns the mesh position in the local space from the current World matrix values.
  18993. * Returns a new Vector3.
  18994. */
  18995. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18996. this.computeWorldMatrix();
  18997. var invLocalWorldMatrix = this._localWorld.clone();
  18998. invLocalWorldMatrix.invert();
  18999. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19000. };
  19001. /**
  19002. * Translates the mesh along the passed Vector3 in its local space.
  19003. * Returns the TransformNode.
  19004. */
  19005. TransformNode.prototype.locallyTranslate = function (vector3) {
  19006. this.computeWorldMatrix(true);
  19007. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19008. return this;
  19009. };
  19010. /**
  19011. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19012. * @param targetPoint the position (must be in same space as current mesh) to look at
  19013. * @param yawCor optional yaw (y-axis) correction in radians
  19014. * @param pitchCor optional pitch (x-axis) correction in radians
  19015. * @param rollCor optional roll (z-axis) correction in radians
  19016. * @param space the choosen space of the target
  19017. * @returns the TransformNode.
  19018. */
  19019. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19020. if (yawCor === void 0) { yawCor = 0; }
  19021. if (pitchCor === void 0) { pitchCor = 0; }
  19022. if (rollCor === void 0) { rollCor = 0; }
  19023. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19024. var dv = TransformNode._lookAtVectorCache;
  19025. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19026. targetPoint.subtractToRef(pos, dv);
  19027. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19028. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19029. var pitch = Math.atan2(dv.y, len);
  19030. if (this.rotationQuaternion) {
  19031. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19032. }
  19033. else {
  19034. this.rotation.x = pitch + pitchCor;
  19035. this.rotation.y = yaw + yawCor;
  19036. this.rotation.z = rollCor;
  19037. }
  19038. return this;
  19039. };
  19040. /**
  19041. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19042. * This Vector3 is expressed in the World space.
  19043. */
  19044. TransformNode.prototype.getDirection = function (localAxis) {
  19045. var result = BABYLON.Vector3.Zero();
  19046. this.getDirectionToRef(localAxis, result);
  19047. return result;
  19048. };
  19049. /**
  19050. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19051. * localAxis is expressed in the mesh local space.
  19052. * result is computed in the Wordl space from the mesh World matrix.
  19053. * Returns the TransformNode.
  19054. */
  19055. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19056. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19057. return this;
  19058. };
  19059. /**
  19060. * Sets a new pivot point to the current node
  19061. * @param point defines the new pivot point to use
  19062. * @param space defines if the point is in world or local space (local by default)
  19063. * @returns the current TransformNode
  19064. */
  19065. TransformNode.prototype.setPivotPoint = function (point, space) {
  19066. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19067. if (this.getScene().getRenderId() == 0) {
  19068. this.computeWorldMatrix(true);
  19069. }
  19070. var wm = this.getWorldMatrix();
  19071. if (space == BABYLON.Space.WORLD) {
  19072. var tmat = BABYLON.Tmp.Matrix[0];
  19073. wm.invertToRef(tmat);
  19074. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19075. }
  19076. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19077. };
  19078. /**
  19079. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19080. */
  19081. TransformNode.prototype.getPivotPoint = function () {
  19082. var point = BABYLON.Vector3.Zero();
  19083. this.getPivotPointToRef(point);
  19084. return point;
  19085. };
  19086. /**
  19087. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19088. * Returns the TransformNode.
  19089. */
  19090. TransformNode.prototype.getPivotPointToRef = function (result) {
  19091. result.x = -this._pivotMatrix.m[12];
  19092. result.y = -this._pivotMatrix.m[13];
  19093. result.z = -this._pivotMatrix.m[14];
  19094. return this;
  19095. };
  19096. /**
  19097. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19098. */
  19099. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19100. var point = BABYLON.Vector3.Zero();
  19101. this.getAbsolutePivotPointToRef(point);
  19102. return point;
  19103. };
  19104. /**
  19105. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19106. * Returns the TransformNode.
  19107. */
  19108. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19109. result.x = this._pivotMatrix.m[12];
  19110. result.y = this._pivotMatrix.m[13];
  19111. result.z = this._pivotMatrix.m[14];
  19112. this.getPivotPointToRef(result);
  19113. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19114. return this;
  19115. };
  19116. /**
  19117. * Defines the passed node as the parent of the current node.
  19118. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19119. * Returns the TransformNode.
  19120. */
  19121. TransformNode.prototype.setParent = function (node) {
  19122. if (!node && !this.parent) {
  19123. return this;
  19124. }
  19125. if (!node) {
  19126. var rotation = BABYLON.Tmp.Quaternion[0];
  19127. var position = BABYLON.Tmp.Vector3[0];
  19128. var scale = BABYLON.Tmp.Vector3[1];
  19129. if (this.parent && this.parent.computeWorldMatrix) {
  19130. this.parent.computeWorldMatrix(true);
  19131. }
  19132. this.computeWorldMatrix(true);
  19133. this.getWorldMatrix().decompose(scale, rotation, position);
  19134. if (this.rotationQuaternion) {
  19135. this.rotationQuaternion.copyFrom(rotation);
  19136. }
  19137. else {
  19138. rotation.toEulerAnglesToRef(this.rotation);
  19139. }
  19140. this.scaling.x = scale.x;
  19141. this.scaling.y = scale.y;
  19142. this.scaling.z = scale.z;
  19143. this.position.x = position.x;
  19144. this.position.y = position.y;
  19145. this.position.z = position.z;
  19146. }
  19147. else {
  19148. var rotation = BABYLON.Tmp.Quaternion[0];
  19149. var position = BABYLON.Tmp.Vector3[0];
  19150. var scale = BABYLON.Tmp.Vector3[1];
  19151. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19152. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19153. this.computeWorldMatrix(true);
  19154. node.computeWorldMatrix(true);
  19155. node.getWorldMatrix().invertToRef(invParentMatrix);
  19156. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19157. diffMatrix.decompose(scale, rotation, position);
  19158. if (this.rotationQuaternion) {
  19159. this.rotationQuaternion.copyFrom(rotation);
  19160. }
  19161. else {
  19162. rotation.toEulerAnglesToRef(this.rotation);
  19163. }
  19164. this.position.x = position.x;
  19165. this.position.y = position.y;
  19166. this.position.z = position.z;
  19167. this.scaling.x = scale.x;
  19168. this.scaling.y = scale.y;
  19169. this.scaling.z = scale.z;
  19170. }
  19171. this.parent = node;
  19172. return this;
  19173. };
  19174. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19175. get: function () {
  19176. return this._nonUniformScaling;
  19177. },
  19178. enumerable: true,
  19179. configurable: true
  19180. });
  19181. /** @hidden */
  19182. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19183. if (this._nonUniformScaling === value) {
  19184. return false;
  19185. }
  19186. this._nonUniformScaling = value;
  19187. return true;
  19188. };
  19189. /**
  19190. * Attach the current TransformNode to another TransformNode associated with a bone
  19191. * @param bone Bone affecting the TransformNode
  19192. * @param affectedTransformNode TransformNode associated with the bone
  19193. */
  19194. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19195. this._transformToBoneReferal = affectedTransformNode;
  19196. this.parent = bone;
  19197. if (bone.getWorldMatrix().determinant() < 0) {
  19198. this.scalingDeterminant *= -1;
  19199. }
  19200. return this;
  19201. };
  19202. TransformNode.prototype.detachFromBone = function () {
  19203. if (!this.parent) {
  19204. return this;
  19205. }
  19206. if (this.parent.getWorldMatrix().determinant() < 0) {
  19207. this.scalingDeterminant *= -1;
  19208. }
  19209. this._transformToBoneReferal = null;
  19210. this.parent = null;
  19211. return this;
  19212. };
  19213. /**
  19214. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19215. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19216. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19217. * The passed axis is also normalized.
  19218. * Returns the TransformNode.
  19219. */
  19220. TransformNode.prototype.rotate = function (axis, amount, space) {
  19221. axis.normalize();
  19222. if (!this.rotationQuaternion) {
  19223. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19224. this.rotation = BABYLON.Vector3.Zero();
  19225. }
  19226. var rotationQuaternion;
  19227. if (!space || space === BABYLON.Space.LOCAL) {
  19228. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19229. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19230. }
  19231. else {
  19232. if (this.parent) {
  19233. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19234. invertParentWorldMatrix.invert();
  19235. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19236. }
  19237. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19238. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19239. }
  19240. return this;
  19241. };
  19242. /**
  19243. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19244. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19245. * The passed axis is also normalized.
  19246. * Returns the TransformNode.
  19247. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19248. */
  19249. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19250. axis.normalize();
  19251. if (!this.rotationQuaternion) {
  19252. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19253. this.rotation.copyFromFloats(0, 0, 0);
  19254. }
  19255. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19256. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19257. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19258. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19259. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19260. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19261. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19262. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19263. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19264. return this;
  19265. };
  19266. /**
  19267. * Translates the mesh along the axis vector for the passed distance in the given space.
  19268. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19269. * Returns the TransformNode.
  19270. */
  19271. TransformNode.prototype.translate = function (axis, distance, space) {
  19272. var displacementVector = axis.scale(distance);
  19273. if (!space || space === BABYLON.Space.LOCAL) {
  19274. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19275. this.setPositionWithLocalVector(tempV3);
  19276. }
  19277. else {
  19278. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19279. }
  19280. return this;
  19281. };
  19282. /**
  19283. * Adds a rotation step to the mesh current rotation.
  19284. * x, y, z are Euler angles expressed in radians.
  19285. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19286. * This means this rotation is made in the mesh local space only.
  19287. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19288. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19289. * ```javascript
  19290. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19291. * ```
  19292. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19293. * 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.
  19294. * Returns the TransformNode.
  19295. */
  19296. TransformNode.prototype.addRotation = function (x, y, z) {
  19297. var rotationQuaternion;
  19298. if (this.rotationQuaternion) {
  19299. rotationQuaternion = this.rotationQuaternion;
  19300. }
  19301. else {
  19302. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19303. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19304. }
  19305. var accumulation = BABYLON.Tmp.Quaternion[0];
  19306. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19307. rotationQuaternion.multiplyInPlace(accumulation);
  19308. if (!this.rotationQuaternion) {
  19309. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19310. }
  19311. return this;
  19312. };
  19313. /**
  19314. * Computes the world matrix of the node
  19315. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19316. * @returns the world matrix
  19317. */
  19318. TransformNode.prototype.computeWorldMatrix = function (force) {
  19319. if (this._isWorldMatrixFrozen) {
  19320. return this._worldMatrix;
  19321. }
  19322. if (!force && this.isSynchronized()) {
  19323. this._currentRenderId = this.getScene().getRenderId();
  19324. return this._worldMatrix;
  19325. }
  19326. this._updateCache();
  19327. this._cache.position.copyFrom(this.position);
  19328. this._cache.scaling.copyFrom(this.scaling);
  19329. this._cache.pivotMatrixUpdated = false;
  19330. this._cache.billboardMode = this.billboardMode;
  19331. this._currentRenderId = this.getScene().getRenderId();
  19332. this._childRenderId = this.getScene().getRenderId();
  19333. this._isDirty = false;
  19334. // Scaling
  19335. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19336. // Rotation
  19337. //rotate, if quaternion is set and rotation was used
  19338. if (this.rotationQuaternion) {
  19339. var len = this.rotation.length();
  19340. if (len) {
  19341. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19342. this.rotation.copyFromFloats(0, 0, 0);
  19343. }
  19344. }
  19345. if (this.rotationQuaternion) {
  19346. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19347. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19348. }
  19349. else {
  19350. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19351. this._cache.rotation.copyFrom(this.rotation);
  19352. }
  19353. // Translation
  19354. var camera = this.getScene().activeCamera;
  19355. if (this.infiniteDistance && !this.parent && camera) {
  19356. var cameraWorldMatrix = camera.getWorldMatrix();
  19357. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19358. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19359. }
  19360. else {
  19361. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19362. }
  19363. // Composing transformations
  19364. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19365. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19366. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19367. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19368. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19369. // Need to decompose each rotation here
  19370. var currentPosition = BABYLON.Tmp.Vector3[3];
  19371. if (this.parent && this.parent.getWorldMatrix) {
  19372. if (this._transformToBoneReferal) {
  19373. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19374. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19375. }
  19376. else {
  19377. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19378. }
  19379. }
  19380. else {
  19381. currentPosition.copyFrom(this.position);
  19382. }
  19383. currentPosition.subtractInPlace(camera.globalPosition);
  19384. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19385. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19386. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19387. }
  19388. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19389. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19390. }
  19391. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19392. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19393. }
  19394. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19395. }
  19396. else {
  19397. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19398. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19399. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19400. }
  19401. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19402. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19403. }
  19404. // Post multiply inverse of pivotMatrix
  19405. if (this._postMultiplyPivotMatrix) {
  19406. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19407. }
  19408. // Local world
  19409. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19410. // Parent
  19411. if (this.parent && this.parent.getWorldMatrix) {
  19412. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19413. if (this._transformToBoneReferal) {
  19414. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19415. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19416. }
  19417. else {
  19418. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19419. }
  19420. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19421. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19422. this._worldMatrix.copyFrom(this._localWorld);
  19423. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19424. }
  19425. else {
  19426. if (this._transformToBoneReferal) {
  19427. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19428. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19429. }
  19430. else {
  19431. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19432. }
  19433. }
  19434. this._markSyncedWithParent();
  19435. }
  19436. else {
  19437. this._worldMatrix.copyFrom(this._localWorld);
  19438. }
  19439. // Normal matrix
  19440. if (!this.ignoreNonUniformScaling) {
  19441. if (this.scaling.isNonUniform) {
  19442. this._updateNonUniformScalingState(true);
  19443. }
  19444. else if (this.parent && this.parent._nonUniformScaling) {
  19445. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19446. }
  19447. else {
  19448. this._updateNonUniformScalingState(false);
  19449. }
  19450. }
  19451. else {
  19452. this._updateNonUniformScalingState(false);
  19453. }
  19454. this._afterComputeWorldMatrix();
  19455. // Absolute position
  19456. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19457. // Callbacks
  19458. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19459. if (!this._poseMatrix) {
  19460. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19461. }
  19462. // Cache the determinant
  19463. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19464. return this._worldMatrix;
  19465. };
  19466. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19467. };
  19468. /**
  19469. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19470. * @param func: callback function to add
  19471. *
  19472. * Returns the TransformNode.
  19473. */
  19474. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19475. this.onAfterWorldMatrixUpdateObservable.add(func);
  19476. return this;
  19477. };
  19478. /**
  19479. * Removes a registered callback function.
  19480. * Returns the TransformNode.
  19481. */
  19482. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19483. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19484. return this;
  19485. };
  19486. /**
  19487. * Clone the current transform node
  19488. * Returns the new transform node
  19489. * @param name Name of the new clone
  19490. * @param newParent New parent for the clone
  19491. * @param doNotCloneChildren Do not clone children hierarchy
  19492. */
  19493. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19494. var _this = this;
  19495. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19496. result.name = name;
  19497. result.id = name;
  19498. if (newParent) {
  19499. result.parent = newParent;
  19500. }
  19501. if (!doNotCloneChildren) {
  19502. // Children
  19503. var directDescendants = this.getDescendants(true);
  19504. for (var index = 0; index < directDescendants.length; index++) {
  19505. var child = directDescendants[index];
  19506. if (child.clone) {
  19507. child.clone(name + "." + child.name, result);
  19508. }
  19509. }
  19510. }
  19511. return result;
  19512. };
  19513. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19514. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19515. serializationObject.type = this.getClassName();
  19516. // Parent
  19517. if (this.parent) {
  19518. serializationObject.parentId = this.parent.id;
  19519. }
  19520. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19521. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19522. }
  19523. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19524. serializationObject.isEnabled = this.isEnabled();
  19525. // Parent
  19526. if (this.parent) {
  19527. serializationObject.parentId = this.parent.id;
  19528. }
  19529. return serializationObject;
  19530. };
  19531. // Statics
  19532. /**
  19533. * Returns a new TransformNode object parsed from the source provided.
  19534. * The parameter `parsedMesh` is the source.
  19535. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19536. */
  19537. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19538. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19539. if (BABYLON.Tags) {
  19540. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19541. }
  19542. if (parsedTransformNode.localMatrix) {
  19543. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19544. }
  19545. else if (parsedTransformNode.pivotMatrix) {
  19546. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19547. }
  19548. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19549. // Parent
  19550. if (parsedTransformNode.parentId) {
  19551. transformNode._waitingParentId = parsedTransformNode.parentId;
  19552. }
  19553. return transformNode;
  19554. };
  19555. /**
  19556. * Releases resources associated with this transform node.
  19557. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19558. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19559. */
  19560. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19561. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19562. // Animations
  19563. this.getScene().stopAnimation(this);
  19564. // Remove from scene
  19565. this.getScene().removeTransformNode(this);
  19566. this.onAfterWorldMatrixUpdateObservable.clear();
  19567. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19568. };
  19569. // Statics
  19570. TransformNode.BILLBOARDMODE_NONE = 0;
  19571. TransformNode.BILLBOARDMODE_X = 1;
  19572. TransformNode.BILLBOARDMODE_Y = 2;
  19573. TransformNode.BILLBOARDMODE_Z = 4;
  19574. TransformNode.BILLBOARDMODE_ALL = 7;
  19575. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19576. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19577. __decorate([
  19578. BABYLON.serializeAsVector3("position")
  19579. ], TransformNode.prototype, "_position", void 0);
  19580. __decorate([
  19581. BABYLON.serializeAsVector3("rotation")
  19582. ], TransformNode.prototype, "_rotation", void 0);
  19583. __decorate([
  19584. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19585. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19586. __decorate([
  19587. BABYLON.serializeAsVector3("scaling")
  19588. ], TransformNode.prototype, "_scaling", void 0);
  19589. __decorate([
  19590. BABYLON.serialize()
  19591. ], TransformNode.prototype, "billboardMode", void 0);
  19592. __decorate([
  19593. BABYLON.serialize()
  19594. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19595. __decorate([
  19596. BABYLON.serialize()
  19597. ], TransformNode.prototype, "infiniteDistance", void 0);
  19598. __decorate([
  19599. BABYLON.serialize()
  19600. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19601. return TransformNode;
  19602. }(BABYLON.Node));
  19603. BABYLON.TransformNode = TransformNode;
  19604. })(BABYLON || (BABYLON = {}));
  19605. //# sourceMappingURL=babylon.transformNode.js.map
  19606. var BABYLON;
  19607. (function (BABYLON) {
  19608. /**
  19609. * Class used to store all common mesh properties
  19610. */
  19611. var AbstractMesh = /** @class */ (function (_super) {
  19612. __extends(AbstractMesh, _super);
  19613. // Constructor
  19614. /**
  19615. * Creates a new AbstractMesh
  19616. * @param name defines the name of the mesh
  19617. * @param scene defines the hosting scene
  19618. */
  19619. function AbstractMesh(name, scene) {
  19620. if (scene === void 0) { scene = null; }
  19621. var _this = _super.call(this, name, scene, false) || this;
  19622. _this._facetNb = 0; // facet number
  19623. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19624. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19625. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19626. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19627. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19628. _this._subDiv = {
  19629. max: 1,
  19630. X: 1,
  19631. Y: 1,
  19632. Z: 1
  19633. };
  19634. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19635. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19636. /** Gets ot sets the culling strategy to use to find visible meshes */
  19637. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19638. // Events
  19639. /**
  19640. * An event triggered when this mesh collides with another one
  19641. */
  19642. _this.onCollideObservable = new BABYLON.Observable();
  19643. /**
  19644. * An event triggered when the collision's position changes
  19645. */
  19646. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19647. /**
  19648. * An event triggered when material is changed
  19649. */
  19650. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19651. // Properties
  19652. /**
  19653. * Gets or sets the orientation for POV movement & rotation
  19654. */
  19655. _this.definedFacingForward = true;
  19656. /**
  19657. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19658. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19659. * * 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.
  19660. * @see http://doc.babylonjs.com/features/occlusionquery
  19661. */
  19662. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19663. /**
  19664. * 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:
  19665. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19666. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19667. * * 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.
  19668. * @see http://doc.babylonjs.com/features/occlusionquery
  19669. */
  19670. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19671. /**
  19672. * 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.
  19673. * The default value is -1 which means don't break the query and wait till the result
  19674. * @see http://doc.babylonjs.com/features/occlusionquery
  19675. */
  19676. _this.occlusionRetryCount = -1;
  19677. /** @hidden */
  19678. _this._occlusionInternalRetryCounter = 0;
  19679. /** @hidden */
  19680. _this._isOccluded = false;
  19681. /** @hidden */
  19682. _this._isOcclusionQueryInProgress = false;
  19683. _this._visibility = 1.0;
  19684. /** Gets or sets the alpha index used to sort transparent meshes
  19685. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19686. */
  19687. _this.alphaIndex = Number.MAX_VALUE;
  19688. /**
  19689. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19690. */
  19691. _this.isVisible = true;
  19692. /**
  19693. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19694. */
  19695. _this.isPickable = true;
  19696. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19697. _this.showSubMeshesBoundingBox = false;
  19698. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19699. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19700. */
  19701. _this.isBlocker = false;
  19702. /**
  19703. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19704. */
  19705. _this.enablePointerMoveEvents = false;
  19706. /**
  19707. * Specifies the rendering group id for this mesh (0 by default)
  19708. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19709. */
  19710. _this.renderingGroupId = 0;
  19711. _this._receiveShadows = false;
  19712. /** Defines color to use when rendering outline */
  19713. _this.outlineColor = BABYLON.Color3.Red();
  19714. /** Define width to use when rendering outline */
  19715. _this.outlineWidth = 0.02;
  19716. /** Defines color to use when rendering overlay */
  19717. _this.overlayColor = BABYLON.Color3.Red();
  19718. /** Defines alpha to use when rendering overlay */
  19719. _this.overlayAlpha = 0.5;
  19720. _this._hasVertexAlpha = false;
  19721. _this._useVertexColors = true;
  19722. _this._computeBonesUsingShaders = true;
  19723. _this._numBoneInfluencers = 4;
  19724. _this._applyFog = true;
  19725. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19726. _this.useOctreeForRenderingSelection = true;
  19727. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19728. _this.useOctreeForPicking = true;
  19729. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19730. _this.useOctreeForCollisions = true;
  19731. _this._layerMask = 0x0FFFFFFF;
  19732. /**
  19733. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19734. */
  19735. _this.alwaysSelectAsActiveMesh = false;
  19736. /**
  19737. * Gets or sets the current action manager
  19738. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19739. */
  19740. _this.actionManager = null;
  19741. // Collisions
  19742. _this._checkCollisions = false;
  19743. _this._collisionMask = -1;
  19744. _this._collisionGroup = -1;
  19745. /**
  19746. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19747. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19748. */
  19749. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19750. /**
  19751. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19752. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19753. */
  19754. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19755. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19756. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19757. // Edges
  19758. /**
  19759. * Defines edge width used when edgesRenderer is enabled
  19760. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19761. */
  19762. _this.edgesWidth = 1;
  19763. /**
  19764. * Defines edge color used when edgesRenderer is enabled
  19765. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19766. */
  19767. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19768. // Cache
  19769. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19770. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19771. /** @hidden */
  19772. _this._renderId = 0;
  19773. /** @hidden */
  19774. _this._intersectionsInProgress = new Array();
  19775. /** @hidden */
  19776. _this._unIndexed = false;
  19777. /** @hidden */
  19778. _this._lightSources = new Array();
  19779. /**
  19780. * An event triggered when the mesh is rebuilt.
  19781. */
  19782. _this.onRebuildObservable = new BABYLON.Observable();
  19783. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19784. if (collidedMesh === void 0) { collidedMesh = null; }
  19785. //TODO move this to the collision coordinator!
  19786. if (_this.getScene().workerCollisions)
  19787. newPosition.multiplyInPlace(_this._collider._radius);
  19788. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19789. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19790. _this.position.addInPlace(_this._diffPositionForCollisions);
  19791. }
  19792. if (collidedMesh) {
  19793. _this.onCollideObservable.notifyObservers(collidedMesh);
  19794. }
  19795. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19796. };
  19797. _this.getScene().addMesh(_this);
  19798. _this._resyncLightSources();
  19799. return _this;
  19800. }
  19801. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19802. /**
  19803. * No billboard
  19804. */
  19805. get: function () {
  19806. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19812. /** Billboard on X axis */
  19813. get: function () {
  19814. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19815. },
  19816. enumerable: true,
  19817. configurable: true
  19818. });
  19819. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19820. /** Billboard on Y axis */
  19821. get: function () {
  19822. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19823. },
  19824. enumerable: true,
  19825. configurable: true
  19826. });
  19827. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19828. /** Billboard on Z axis */
  19829. get: function () {
  19830. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19836. /** Billboard on all axes */
  19837. get: function () {
  19838. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19839. },
  19840. enumerable: true,
  19841. configurable: true
  19842. });
  19843. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19844. /**
  19845. * Gets the number of facets in the mesh
  19846. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19847. */
  19848. get: function () {
  19849. return this._facetNb;
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19855. /**
  19856. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19857. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19858. */
  19859. get: function () {
  19860. return this._partitioningSubdivisions;
  19861. },
  19862. set: function (nb) {
  19863. this._partitioningSubdivisions = nb;
  19864. },
  19865. enumerable: true,
  19866. configurable: true
  19867. });
  19868. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19869. /**
  19870. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19871. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19872. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19873. */
  19874. get: function () {
  19875. return this._partitioningBBoxRatio;
  19876. },
  19877. set: function (ratio) {
  19878. this._partitioningBBoxRatio = ratio;
  19879. },
  19880. enumerable: true,
  19881. configurable: true
  19882. });
  19883. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19884. /**
  19885. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19886. * Works only for updatable meshes.
  19887. * Doesn't work with multi-materials
  19888. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19889. */
  19890. get: function () {
  19891. return this._facetDepthSort;
  19892. },
  19893. set: function (sort) {
  19894. this._facetDepthSort = sort;
  19895. },
  19896. enumerable: true,
  19897. configurable: true
  19898. });
  19899. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19900. /**
  19901. * The location (Vector3) where the facet depth sort must be computed from.
  19902. * By default, the active camera position.
  19903. * Used only when facet depth sort is enabled
  19904. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19905. */
  19906. get: function () {
  19907. return this._facetDepthSortFrom;
  19908. },
  19909. set: function (location) {
  19910. this._facetDepthSortFrom = location;
  19911. },
  19912. enumerable: true,
  19913. configurable: true
  19914. });
  19915. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19916. /**
  19917. * gets a boolean indicating if facetData is enabled
  19918. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19919. */
  19920. get: function () {
  19921. return this._facetDataEnabled;
  19922. },
  19923. enumerable: true,
  19924. configurable: true
  19925. });
  19926. /** @hidden */
  19927. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19928. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19929. return false;
  19930. }
  19931. this._markSubMeshesAsMiscDirty();
  19932. return true;
  19933. };
  19934. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19935. /** Set a function to call when this mesh collides with another one */
  19936. set: function (callback) {
  19937. if (this._onCollideObserver) {
  19938. this.onCollideObservable.remove(this._onCollideObserver);
  19939. }
  19940. this._onCollideObserver = this.onCollideObservable.add(callback);
  19941. },
  19942. enumerable: true,
  19943. configurable: true
  19944. });
  19945. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19946. /** Set a function to call when the collision's position changes */
  19947. set: function (callback) {
  19948. if (this._onCollisionPositionChangeObserver) {
  19949. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19950. }
  19951. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19952. },
  19953. enumerable: true,
  19954. configurable: true
  19955. });
  19956. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19957. /**
  19958. * 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
  19959. * @see http://doc.babylonjs.com/features/occlusionquery
  19960. */
  19961. get: function () {
  19962. return this._isOccluded;
  19963. },
  19964. set: function (value) {
  19965. this._isOccluded = value;
  19966. },
  19967. enumerable: true,
  19968. configurable: true
  19969. });
  19970. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19971. /**
  19972. * Flag to check the progress status of the query
  19973. * @see http://doc.babylonjs.com/features/occlusionquery
  19974. */
  19975. get: function () {
  19976. return this._isOcclusionQueryInProgress;
  19977. },
  19978. enumerable: true,
  19979. configurable: true
  19980. });
  19981. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19982. /**
  19983. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19984. */
  19985. get: function () {
  19986. return this._visibility;
  19987. },
  19988. /**
  19989. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19990. */
  19991. set: function (value) {
  19992. if (this._visibility === value) {
  19993. return;
  19994. }
  19995. this._visibility = value;
  19996. this._markSubMeshesAsMiscDirty();
  19997. },
  19998. enumerable: true,
  19999. configurable: true
  20000. });
  20001. Object.defineProperty(AbstractMesh.prototype, "material", {
  20002. /** Gets or sets current material */
  20003. get: function () {
  20004. return this._material;
  20005. },
  20006. set: function (value) {
  20007. if (this._material === value) {
  20008. return;
  20009. }
  20010. this._material = value;
  20011. if (this.onMaterialChangedObservable.hasObservers) {
  20012. this.onMaterialChangedObservable.notifyObservers(this);
  20013. }
  20014. if (!this.subMeshes) {
  20015. return;
  20016. }
  20017. this._unBindEffect();
  20018. },
  20019. enumerable: true,
  20020. configurable: true
  20021. });
  20022. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20023. /**
  20024. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20025. * @see http://doc.babylonjs.com/babylon101/shadows
  20026. */
  20027. get: function () {
  20028. return this._receiveShadows;
  20029. },
  20030. set: function (value) {
  20031. if (this._receiveShadows === value) {
  20032. return;
  20033. }
  20034. this._receiveShadows = value;
  20035. this._markSubMeshesAsLightDirty();
  20036. },
  20037. enumerable: true,
  20038. configurable: true
  20039. });
  20040. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20041. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20042. get: function () {
  20043. return this._hasVertexAlpha;
  20044. },
  20045. set: function (value) {
  20046. if (this._hasVertexAlpha === value) {
  20047. return;
  20048. }
  20049. this._hasVertexAlpha = value;
  20050. this._markSubMeshesAsAttributesDirty();
  20051. this._markSubMeshesAsMiscDirty();
  20052. },
  20053. enumerable: true,
  20054. configurable: true
  20055. });
  20056. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20057. /** 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) */
  20058. get: function () {
  20059. return this._useVertexColors;
  20060. },
  20061. set: function (value) {
  20062. if (this._useVertexColors === value) {
  20063. return;
  20064. }
  20065. this._useVertexColors = value;
  20066. this._markSubMeshesAsAttributesDirty();
  20067. },
  20068. enumerable: true,
  20069. configurable: true
  20070. });
  20071. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20072. /**
  20073. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20074. */
  20075. get: function () {
  20076. return this._computeBonesUsingShaders;
  20077. },
  20078. set: function (value) {
  20079. if (this._computeBonesUsingShaders === value) {
  20080. return;
  20081. }
  20082. this._computeBonesUsingShaders = value;
  20083. this._markSubMeshesAsAttributesDirty();
  20084. },
  20085. enumerable: true,
  20086. configurable: true
  20087. });
  20088. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20089. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20090. get: function () {
  20091. return this._numBoneInfluencers;
  20092. },
  20093. set: function (value) {
  20094. if (this._numBoneInfluencers === value) {
  20095. return;
  20096. }
  20097. this._numBoneInfluencers = value;
  20098. this._markSubMeshesAsAttributesDirty();
  20099. },
  20100. enumerable: true,
  20101. configurable: true
  20102. });
  20103. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20104. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20105. get: function () {
  20106. return this._applyFog;
  20107. },
  20108. set: function (value) {
  20109. if (this._applyFog === value) {
  20110. return;
  20111. }
  20112. this._applyFog = value;
  20113. this._markSubMeshesAsMiscDirty();
  20114. },
  20115. enumerable: true,
  20116. configurable: true
  20117. });
  20118. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20119. /**
  20120. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20121. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20122. */
  20123. get: function () {
  20124. return this._layerMask;
  20125. },
  20126. set: function (value) {
  20127. if (value === this._layerMask) {
  20128. return;
  20129. }
  20130. this._layerMask = value;
  20131. this._resyncLightSources();
  20132. },
  20133. enumerable: true,
  20134. configurable: true
  20135. });
  20136. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20137. /**
  20138. * Gets or sets a collision mask used to mask collisions (default is -1).
  20139. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20140. */
  20141. get: function () {
  20142. return this._collisionMask;
  20143. },
  20144. set: function (mask) {
  20145. this._collisionMask = !isNaN(mask) ? mask : -1;
  20146. },
  20147. enumerable: true,
  20148. configurable: true
  20149. });
  20150. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20151. /**
  20152. * Gets or sets the current collision group mask (-1 by default).
  20153. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20154. */
  20155. get: function () {
  20156. return this._collisionGroup;
  20157. },
  20158. set: function (mask) {
  20159. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20160. },
  20161. enumerable: true,
  20162. configurable: true
  20163. });
  20164. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20165. /** @hidden */
  20166. get: function () {
  20167. return null;
  20168. },
  20169. enumerable: true,
  20170. configurable: true
  20171. });
  20172. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20173. get: function () {
  20174. return this._skeleton;
  20175. },
  20176. /**
  20177. * Gets or sets a skeleton to apply skining transformations
  20178. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20179. */
  20180. set: function (value) {
  20181. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20182. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20183. }
  20184. if (value && value.needInitialSkinMatrix) {
  20185. value._registerMeshWithPoseMatrix(this);
  20186. }
  20187. this._skeleton = value;
  20188. if (!this._skeleton) {
  20189. this._bonesTransformMatrices = null;
  20190. }
  20191. this._markSubMeshesAsAttributesDirty();
  20192. },
  20193. enumerable: true,
  20194. configurable: true
  20195. });
  20196. /**
  20197. * Returns the string "AbstractMesh"
  20198. * @returns "AbstractMesh"
  20199. */
  20200. AbstractMesh.prototype.getClassName = function () {
  20201. return "AbstractMesh";
  20202. };
  20203. /**
  20204. * Gets a string representation of the current mesh
  20205. * @param fullDetails defines a boolean indicating if full details must be included
  20206. * @returns a string representation of the current mesh
  20207. */
  20208. AbstractMesh.prototype.toString = function (fullDetails) {
  20209. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20210. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20211. if (this._skeleton) {
  20212. ret += ", skeleton: " + this._skeleton.name;
  20213. }
  20214. if (fullDetails) {
  20215. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20216. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20217. }
  20218. return ret;
  20219. };
  20220. /** @hidden */
  20221. AbstractMesh.prototype._rebuild = function () {
  20222. this.onRebuildObservable.notifyObservers(this);
  20223. if (this._occlusionQuery) {
  20224. this._occlusionQuery = null;
  20225. }
  20226. if (!this.subMeshes) {
  20227. return;
  20228. }
  20229. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20230. var subMesh = _a[_i];
  20231. subMesh._rebuild();
  20232. }
  20233. };
  20234. /** @hidden */
  20235. AbstractMesh.prototype._resyncLightSources = function () {
  20236. this._lightSources.length = 0;
  20237. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20238. var light = _a[_i];
  20239. if (!light.isEnabled()) {
  20240. continue;
  20241. }
  20242. if (light.canAffectMesh(this)) {
  20243. this._lightSources.push(light);
  20244. }
  20245. }
  20246. this._markSubMeshesAsLightDirty();
  20247. };
  20248. /** @hidden */
  20249. AbstractMesh.prototype._resyncLighSource = function (light) {
  20250. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20251. var index = this._lightSources.indexOf(light);
  20252. if (index === -1) {
  20253. if (!isIn) {
  20254. return;
  20255. }
  20256. this._lightSources.push(light);
  20257. }
  20258. else {
  20259. if (isIn) {
  20260. return;
  20261. }
  20262. this._lightSources.splice(index, 1);
  20263. }
  20264. this._markSubMeshesAsLightDirty();
  20265. };
  20266. /** @hidden */
  20267. AbstractMesh.prototype._unBindEffect = function () {
  20268. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20269. var subMesh = _a[_i];
  20270. subMesh.setEffect(null);
  20271. }
  20272. };
  20273. /** @hidden */
  20274. AbstractMesh.prototype._removeLightSource = function (light) {
  20275. var index = this._lightSources.indexOf(light);
  20276. if (index === -1) {
  20277. return;
  20278. }
  20279. this._lightSources.splice(index, 1);
  20280. this._markSubMeshesAsLightDirty();
  20281. };
  20282. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20283. if (!this.subMeshes) {
  20284. return;
  20285. }
  20286. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20287. var subMesh = _a[_i];
  20288. if (subMesh._materialDefines) {
  20289. func(subMesh._materialDefines);
  20290. }
  20291. }
  20292. };
  20293. /** @hidden */
  20294. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20295. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20296. };
  20297. /** @hidden */
  20298. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20299. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20300. };
  20301. /** @hidden */
  20302. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20303. if (!this.subMeshes) {
  20304. return;
  20305. }
  20306. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20307. var subMesh = _a[_i];
  20308. var material = subMesh.getMaterial();
  20309. if (material) {
  20310. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20311. }
  20312. }
  20313. };
  20314. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20315. /**
  20316. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20317. */
  20318. get: function () {
  20319. return this._scaling;
  20320. },
  20321. set: function (newScaling) {
  20322. this._scaling = newScaling;
  20323. if (this.physicsImpostor) {
  20324. this.physicsImpostor.forceUpdate();
  20325. }
  20326. },
  20327. enumerable: true,
  20328. configurable: true
  20329. });
  20330. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20331. // Methods
  20332. /**
  20333. * Returns true if the mesh is blocked. Implemented by child classes
  20334. */
  20335. get: function () {
  20336. return false;
  20337. },
  20338. enumerable: true,
  20339. configurable: true
  20340. });
  20341. /**
  20342. * Returns the mesh itself by default. Implemented by child classes
  20343. * @param camera defines the camera to use to pick the right LOD level
  20344. * @returns the currentAbstractMesh
  20345. */
  20346. AbstractMesh.prototype.getLOD = function (camera) {
  20347. return this;
  20348. };
  20349. /**
  20350. * Returns 0 by default. Implemented by child classes
  20351. * @returns an integer
  20352. */
  20353. AbstractMesh.prototype.getTotalVertices = function () {
  20354. return 0;
  20355. };
  20356. /**
  20357. * Returns null by default. Implemented by child classes
  20358. * @returns null
  20359. */
  20360. AbstractMesh.prototype.getIndices = function () {
  20361. return null;
  20362. };
  20363. /**
  20364. * Returns the array of the requested vertex data kind. Implemented by child classes
  20365. * @param kind defines the vertex data kind to use
  20366. * @returns null
  20367. */
  20368. AbstractMesh.prototype.getVerticesData = function (kind) {
  20369. return null;
  20370. };
  20371. /**
  20372. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20373. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20374. * Note that a new underlying VertexBuffer object is created each call.
  20375. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20376. * @param kind defines vertex data kind:
  20377. * * BABYLON.VertexBuffer.PositionKind
  20378. * * BABYLON.VertexBuffer.UVKind
  20379. * * BABYLON.VertexBuffer.UV2Kind
  20380. * * BABYLON.VertexBuffer.UV3Kind
  20381. * * BABYLON.VertexBuffer.UV4Kind
  20382. * * BABYLON.VertexBuffer.UV5Kind
  20383. * * BABYLON.VertexBuffer.UV6Kind
  20384. * * BABYLON.VertexBuffer.ColorKind
  20385. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20386. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20387. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20388. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20389. * @param data defines the data source
  20390. * @param updatable defines if the data must be flagged as updatable (or static)
  20391. * @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
  20392. * @returns the current mesh
  20393. */
  20394. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20395. return this;
  20396. };
  20397. /**
  20398. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20399. * If the mesh has no geometry, it is simply returned as it is.
  20400. * @param kind defines vertex data kind:
  20401. * * BABYLON.VertexBuffer.PositionKind
  20402. * * BABYLON.VertexBuffer.UVKind
  20403. * * BABYLON.VertexBuffer.UV2Kind
  20404. * * BABYLON.VertexBuffer.UV3Kind
  20405. * * BABYLON.VertexBuffer.UV4Kind
  20406. * * BABYLON.VertexBuffer.UV5Kind
  20407. * * BABYLON.VertexBuffer.UV6Kind
  20408. * * BABYLON.VertexBuffer.ColorKind
  20409. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20410. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20411. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20412. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20413. * @param data defines the data source
  20414. * @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
  20415. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20416. * @returns the current mesh
  20417. */
  20418. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20419. return this;
  20420. };
  20421. /**
  20422. * Sets the mesh indices,
  20423. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20424. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20425. * @param totalVertices Defines the total number of vertices
  20426. * @returns the current mesh
  20427. */
  20428. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20429. return this;
  20430. };
  20431. /**
  20432. * Gets a boolean indicating if specific vertex data is present
  20433. * @param kind defines the vertex data kind to use
  20434. * @returns true is data kind is present
  20435. */
  20436. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20437. return false;
  20438. };
  20439. /**
  20440. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20441. * @returns a BoundingInfo
  20442. */
  20443. AbstractMesh.prototype.getBoundingInfo = function () {
  20444. if (this._masterMesh) {
  20445. return this._masterMesh.getBoundingInfo();
  20446. }
  20447. if (!this._boundingInfo) {
  20448. // this._boundingInfo is being created here
  20449. this._updateBoundingInfo();
  20450. }
  20451. // cannot be null.
  20452. return this._boundingInfo;
  20453. };
  20454. /**
  20455. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20456. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20457. * @returns the current mesh
  20458. */
  20459. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20460. if (includeDescendants === void 0) { includeDescendants = true; }
  20461. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20462. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20463. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20464. if (maxDimension === 0) {
  20465. return this;
  20466. }
  20467. var scale = 1 / maxDimension;
  20468. this.scaling.scaleInPlace(scale);
  20469. return this;
  20470. };
  20471. /**
  20472. * Overwrite the current bounding info
  20473. * @param boundingInfo defines the new bounding info
  20474. * @returns the current mesh
  20475. */
  20476. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20477. this._boundingInfo = boundingInfo;
  20478. return this;
  20479. };
  20480. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20481. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20482. get: function () {
  20483. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20484. },
  20485. enumerable: true,
  20486. configurable: true
  20487. });
  20488. /** @hidden */
  20489. AbstractMesh.prototype._preActivate = function () {
  20490. };
  20491. /** @hidden */
  20492. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20493. };
  20494. /** @hidden */
  20495. AbstractMesh.prototype._activate = function (renderId) {
  20496. this._renderId = renderId;
  20497. };
  20498. /**
  20499. * Gets the current world matrix
  20500. * @returns a Matrix
  20501. */
  20502. AbstractMesh.prototype.getWorldMatrix = function () {
  20503. if (this._masterMesh) {
  20504. return this._masterMesh.getWorldMatrix();
  20505. }
  20506. return _super.prototype.getWorldMatrix.call(this);
  20507. };
  20508. /** @hidden */
  20509. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20510. if (this._masterMesh) {
  20511. return this._masterMesh._getWorldMatrixDeterminant();
  20512. }
  20513. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20514. };
  20515. // ================================== Point of View Movement =================================
  20516. /**
  20517. * Perform relative position change from the point of view of behind the front of the mesh.
  20518. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20519. * Supports definition of mesh facing forward or backward
  20520. * @param amountRight defines the distance on the right axis
  20521. * @param amountUp defines the distance on the up axis
  20522. * @param amountForward defines the distance on the forward axis
  20523. * @returns the current mesh
  20524. */
  20525. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20526. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20527. return this;
  20528. };
  20529. /**
  20530. * Calculate relative position change from the point of view of behind the front of the mesh.
  20531. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20532. * Supports definition of mesh facing forward or backward
  20533. * @param amountRight defines the distance on the right axis
  20534. * @param amountUp defines the distance on the up axis
  20535. * @param amountForward defines the distance on the forward axis
  20536. * @returns the new displacement vector
  20537. */
  20538. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20539. var rotMatrix = new BABYLON.Matrix();
  20540. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20541. rotQuaternion.toRotationMatrix(rotMatrix);
  20542. var translationDelta = BABYLON.Vector3.Zero();
  20543. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20544. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20545. return translationDelta;
  20546. };
  20547. // ================================== Point of View Rotation =================================
  20548. /**
  20549. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20550. * Supports definition of mesh facing forward or backward
  20551. * @param flipBack defines the flip
  20552. * @param twirlClockwise defines the twirl
  20553. * @param tiltRight defines the tilt
  20554. * @returns the current mesh
  20555. */
  20556. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20557. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20558. return this;
  20559. };
  20560. /**
  20561. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20562. * Supports definition of mesh facing forward or backward.
  20563. * @param flipBack defines the flip
  20564. * @param twirlClockwise defines the twirl
  20565. * @param tiltRight defines the tilt
  20566. * @returns the new rotation vector
  20567. */
  20568. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20569. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20570. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20571. };
  20572. /**
  20573. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20574. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20575. * @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
  20576. * @returns the new bounding vectors
  20577. */
  20578. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20579. if (includeDescendants === void 0) { includeDescendants = true; }
  20580. if (predicate === void 0) { predicate = null; }
  20581. // Ensures that all world matrix will be recomputed.
  20582. this.getScene().incrementRenderId();
  20583. this.computeWorldMatrix(true);
  20584. var min;
  20585. var max;
  20586. var boundingInfo = this.getBoundingInfo();
  20587. if (!this.subMeshes) {
  20588. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20589. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20590. }
  20591. else {
  20592. min = boundingInfo.boundingBox.minimumWorld;
  20593. max = boundingInfo.boundingBox.maximumWorld;
  20594. }
  20595. if (includeDescendants) {
  20596. var descendants = this.getDescendants(false);
  20597. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20598. var descendant = descendants_1[_i];
  20599. var childMesh = descendant;
  20600. childMesh.computeWorldMatrix(true);
  20601. // Filters meshes based on custom predicate function.
  20602. if (predicate && !predicate(childMesh)) {
  20603. continue;
  20604. }
  20605. //make sure we have the needed params to get mix and max
  20606. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20607. continue;
  20608. }
  20609. var childBoundingInfo = childMesh.getBoundingInfo();
  20610. var boundingBox = childBoundingInfo.boundingBox;
  20611. var minBox = boundingBox.minimumWorld;
  20612. var maxBox = boundingBox.maximumWorld;
  20613. BABYLON.Tools.CheckExtends(minBox, min, max);
  20614. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20615. }
  20616. }
  20617. return {
  20618. min: min,
  20619. max: max
  20620. };
  20621. };
  20622. /** @hidden */
  20623. AbstractMesh.prototype._updateBoundingInfo = function () {
  20624. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20625. this._boundingInfo.update(this.worldMatrixFromCache);
  20626. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20627. return this;
  20628. };
  20629. /** @hidden */
  20630. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20631. if (!this.subMeshes) {
  20632. return this;
  20633. }
  20634. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20635. var subMesh = this.subMeshes[subIndex];
  20636. if (!subMesh.IsGlobal) {
  20637. subMesh.updateBoundingInfo(matrix);
  20638. }
  20639. }
  20640. return this;
  20641. };
  20642. /** @hidden */
  20643. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20644. // Bounding info
  20645. this._updateBoundingInfo();
  20646. };
  20647. /**
  20648. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20649. * A mesh is in the frustum if its bounding box intersects the frustum
  20650. * @param frustumPlanes defines the frustum to test
  20651. * @returns true if the mesh is in the frustum planes
  20652. */
  20653. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20654. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20655. };
  20656. /**
  20657. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20658. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20659. * @param frustumPlanes defines the frustum to test
  20660. * @returns true if the mesh is completely in the frustum planes
  20661. */
  20662. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20663. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20664. };
  20665. /**
  20666. * True if the mesh intersects another mesh or a SolidParticle object
  20667. * @param mesh defines a target mesh or SolidParticle to test
  20668. * @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)
  20669. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20670. * @returns true if there is an intersection
  20671. */
  20672. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20673. if (precise === void 0) { precise = false; }
  20674. if (!this._boundingInfo || !mesh._boundingInfo) {
  20675. return false;
  20676. }
  20677. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20678. return true;
  20679. }
  20680. if (includeDescendants) {
  20681. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20682. var child = _a[_i];
  20683. if (child.intersectsMesh(mesh, precise, true)) {
  20684. return true;
  20685. }
  20686. }
  20687. }
  20688. return false;
  20689. };
  20690. /**
  20691. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20692. * @param point defines the point to test
  20693. * @returns true if there is an intersection
  20694. */
  20695. AbstractMesh.prototype.intersectsPoint = function (point) {
  20696. if (!this._boundingInfo) {
  20697. return false;
  20698. }
  20699. return this._boundingInfo.intersectsPoint(point);
  20700. };
  20701. /**
  20702. * Gets the position of the current mesh in camera space
  20703. * @param camera defines the camera to use
  20704. * @returns a position
  20705. */
  20706. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20707. if (camera === void 0) { camera = null; }
  20708. if (!camera) {
  20709. camera = this.getScene().activeCamera;
  20710. }
  20711. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20712. };
  20713. /**
  20714. * Returns the distance from the mesh to the active camera
  20715. * @param camera defines the camera to use
  20716. * @returns the distance
  20717. */
  20718. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20719. if (camera === void 0) { camera = null; }
  20720. if (!camera) {
  20721. camera = this.getScene().activeCamera;
  20722. }
  20723. return this.absolutePosition.subtract(camera.position).length();
  20724. };
  20725. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20726. // Collisions
  20727. /**
  20728. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20729. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20730. */
  20731. get: function () {
  20732. return this._checkCollisions;
  20733. },
  20734. set: function (collisionEnabled) {
  20735. this._checkCollisions = collisionEnabled;
  20736. if (this.getScene().workerCollisions) {
  20737. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20738. }
  20739. },
  20740. enumerable: true,
  20741. configurable: true
  20742. });
  20743. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20744. /**
  20745. * Gets Collider object used to compute collisions (not physics)
  20746. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20747. */
  20748. get: function () {
  20749. return this._collider;
  20750. },
  20751. enumerable: true,
  20752. configurable: true
  20753. });
  20754. /**
  20755. * Move the mesh using collision engine
  20756. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20757. * @param displacement defines the requested displacement vector
  20758. * @returns the current mesh
  20759. */
  20760. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20761. var globalPosition = this.getAbsolutePosition();
  20762. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20763. if (!this._collider) {
  20764. this._collider = new BABYLON.Collider();
  20765. }
  20766. this._collider._radius = this.ellipsoid;
  20767. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20768. return this;
  20769. };
  20770. // Collisions
  20771. /** @hidden */
  20772. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20773. this._generatePointsArray();
  20774. if (!this._positions) {
  20775. return this;
  20776. }
  20777. // Transformation
  20778. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20779. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20780. subMesh._lastColliderWorldVertices = [];
  20781. subMesh._trianglePlanes = [];
  20782. var start = subMesh.verticesStart;
  20783. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20784. for (var i = start; i < end; i++) {
  20785. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20786. }
  20787. }
  20788. // Collide
  20789. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20790. if (collider.collisionFound) {
  20791. collider.collidedMesh = this;
  20792. }
  20793. return this;
  20794. };
  20795. /** @hidden */
  20796. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20797. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20798. var len = subMeshes.length;
  20799. for (var index = 0; index < len; index++) {
  20800. var subMesh = subMeshes.data[index];
  20801. // Bounding test
  20802. if (len > 1 && !subMesh._checkCollision(collider))
  20803. continue;
  20804. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20805. }
  20806. return this;
  20807. };
  20808. /** @hidden */
  20809. AbstractMesh.prototype._checkCollision = function (collider) {
  20810. // Bounding box test
  20811. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20812. return this;
  20813. // Transformation matrix
  20814. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20815. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20816. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20817. return this;
  20818. };
  20819. // Picking
  20820. /** @hidden */
  20821. AbstractMesh.prototype._generatePointsArray = function () {
  20822. return false;
  20823. };
  20824. /**
  20825. * Checks if the passed Ray intersects with the mesh
  20826. * @param ray defines the ray to use
  20827. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20828. * @returns the picking info
  20829. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20830. */
  20831. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20832. var pickingInfo = new BABYLON.PickingInfo();
  20833. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20834. return pickingInfo;
  20835. }
  20836. if (!this._generatePointsArray()) {
  20837. return pickingInfo;
  20838. }
  20839. var intersectInfo = null;
  20840. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  20841. var len = subMeshes.length;
  20842. for (var index = 0; index < len; index++) {
  20843. var subMesh = subMeshes.data[index];
  20844. // Bounding test
  20845. if (len > 1 && !subMesh.canIntersects(ray))
  20846. continue;
  20847. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20848. if (currentIntersectInfo) {
  20849. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20850. intersectInfo = currentIntersectInfo;
  20851. intersectInfo.subMeshId = index;
  20852. if (fastCheck) {
  20853. break;
  20854. }
  20855. }
  20856. }
  20857. }
  20858. if (intersectInfo) {
  20859. // Get picked point
  20860. var world = this.getWorldMatrix();
  20861. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20862. var direction = ray.direction.clone();
  20863. direction = direction.scale(intersectInfo.distance);
  20864. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20865. var pickedPoint = worldOrigin.add(worldDirection);
  20866. // Return result
  20867. pickingInfo.hit = true;
  20868. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20869. pickingInfo.pickedPoint = pickedPoint;
  20870. pickingInfo.pickedMesh = this;
  20871. pickingInfo.bu = intersectInfo.bu || 0;
  20872. pickingInfo.bv = intersectInfo.bv || 0;
  20873. pickingInfo.faceId = intersectInfo.faceId;
  20874. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20875. return pickingInfo;
  20876. }
  20877. return pickingInfo;
  20878. };
  20879. /**
  20880. * Clones the current mesh
  20881. * @param name defines the mesh name
  20882. * @param newParent defines the new mesh parent
  20883. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20884. * @returns the new mesh
  20885. */
  20886. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20887. return null;
  20888. };
  20889. /**
  20890. * Disposes all the submeshes of the current meshnp
  20891. * @returns the current mesh
  20892. */
  20893. AbstractMesh.prototype.releaseSubMeshes = function () {
  20894. if (this.subMeshes) {
  20895. while (this.subMeshes.length) {
  20896. this.subMeshes[0].dispose();
  20897. }
  20898. }
  20899. else {
  20900. this.subMeshes = new Array();
  20901. }
  20902. return this;
  20903. };
  20904. /**
  20905. * Releases resources associated with this abstract mesh.
  20906. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20907. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20908. */
  20909. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20910. var _this = this;
  20911. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20912. var index;
  20913. // Smart Array Retainers.
  20914. this.getScene().freeActiveMeshes();
  20915. this.getScene().freeRenderingGroups();
  20916. // Action manager
  20917. if (this.actionManager !== undefined && this.actionManager !== null) {
  20918. this.actionManager.dispose();
  20919. this.actionManager = null;
  20920. }
  20921. // Skeleton
  20922. this._skeleton = null;
  20923. // Intersections in progress
  20924. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20925. var other = this._intersectionsInProgress[index];
  20926. var pos = other._intersectionsInProgress.indexOf(this);
  20927. other._intersectionsInProgress.splice(pos, 1);
  20928. }
  20929. this._intersectionsInProgress = [];
  20930. // Lights
  20931. var lights = this.getScene().lights;
  20932. lights.forEach(function (light) {
  20933. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20934. if (meshIndex !== -1) {
  20935. light.includedOnlyMeshes.splice(meshIndex, 1);
  20936. }
  20937. meshIndex = light.excludedMeshes.indexOf(_this);
  20938. if (meshIndex !== -1) {
  20939. light.excludedMeshes.splice(meshIndex, 1);
  20940. }
  20941. // Shadow generators
  20942. var generator = light.getShadowGenerator();
  20943. if (generator) {
  20944. var shadowMap = generator.getShadowMap();
  20945. if (shadowMap && shadowMap.renderList) {
  20946. meshIndex = shadowMap.renderList.indexOf(_this);
  20947. if (meshIndex !== -1) {
  20948. shadowMap.renderList.splice(meshIndex, 1);
  20949. }
  20950. }
  20951. }
  20952. });
  20953. // SubMeshes
  20954. if (this.getClassName() !== "InstancedMesh") {
  20955. this.releaseSubMeshes();
  20956. }
  20957. // Query
  20958. var engine = this.getScene().getEngine();
  20959. if (this._occlusionQuery) {
  20960. this._isOcclusionQueryInProgress = false;
  20961. engine.deleteQuery(this._occlusionQuery);
  20962. this._occlusionQuery = null;
  20963. }
  20964. // Engine
  20965. engine.wipeCaches();
  20966. // Remove from scene
  20967. this.getScene().removeMesh(this);
  20968. if (disposeMaterialAndTextures) {
  20969. if (this.material) {
  20970. this.material.dispose(false, true);
  20971. }
  20972. }
  20973. if (!doNotRecurse) {
  20974. // Particles
  20975. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20976. if (this.getScene().particleSystems[index].emitter === this) {
  20977. this.getScene().particleSystems[index].dispose();
  20978. index--;
  20979. }
  20980. }
  20981. }
  20982. // facet data
  20983. if (this._facetDataEnabled) {
  20984. this.disableFacetData();
  20985. }
  20986. this.onAfterWorldMatrixUpdateObservable.clear();
  20987. this.onCollideObservable.clear();
  20988. this.onCollisionPositionChangeObservable.clear();
  20989. this.onRebuildObservable.clear();
  20990. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20991. };
  20992. /**
  20993. * Adds the passed mesh as a child to the current mesh
  20994. * @param mesh defines the child mesh
  20995. * @returns the current mesh
  20996. */
  20997. AbstractMesh.prototype.addChild = function (mesh) {
  20998. mesh.setParent(this);
  20999. return this;
  21000. };
  21001. /**
  21002. * Removes the passed mesh from the current mesh children list
  21003. * @param mesh defines the child mesh
  21004. * @returns the current mesh
  21005. */
  21006. AbstractMesh.prototype.removeChild = function (mesh) {
  21007. mesh.setParent(null);
  21008. return this;
  21009. };
  21010. // Facet data
  21011. /** @hidden */
  21012. AbstractMesh.prototype._initFacetData = function () {
  21013. if (!this._facetNormals) {
  21014. this._facetNormals = new Array();
  21015. }
  21016. if (!this._facetPositions) {
  21017. this._facetPositions = new Array();
  21018. }
  21019. if (!this._facetPartitioning) {
  21020. this._facetPartitioning = new Array();
  21021. }
  21022. this._facetNb = (this.getIndices().length / 3) | 0;
  21023. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21024. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21025. for (var f = 0; f < this._facetNb; f++) {
  21026. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21027. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21028. }
  21029. this._facetDataEnabled = true;
  21030. return this;
  21031. };
  21032. /**
  21033. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21034. * This method can be called within the render loop.
  21035. * 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
  21036. * @returns the current mesh
  21037. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21038. */
  21039. AbstractMesh.prototype.updateFacetData = function () {
  21040. if (!this._facetDataEnabled) {
  21041. this._initFacetData();
  21042. }
  21043. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21044. var indices = this.getIndices();
  21045. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21046. var bInfo = this.getBoundingInfo();
  21047. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21048. // init arrays, matrix and sort function on first call
  21049. this._facetDepthSortEnabled = true;
  21050. if (indices instanceof Uint16Array) {
  21051. this._depthSortedIndices = new Uint16Array(indices);
  21052. }
  21053. else if (indices instanceof Uint32Array) {
  21054. this._depthSortedIndices = new Uint32Array(indices);
  21055. }
  21056. else {
  21057. var needs32bits = false;
  21058. for (var i = 0; i < indices.length; i++) {
  21059. if (indices[i] > 65535) {
  21060. needs32bits = true;
  21061. break;
  21062. }
  21063. }
  21064. if (needs32bits) {
  21065. this._depthSortedIndices = new Uint32Array(indices);
  21066. }
  21067. else {
  21068. this._depthSortedIndices = new Uint16Array(indices);
  21069. }
  21070. }
  21071. this._facetDepthSortFunction = function (f1, f2) {
  21072. return (f2.sqDistance - f1.sqDistance);
  21073. };
  21074. if (!this._facetDepthSortFrom) {
  21075. var camera = this.getScene().activeCamera;
  21076. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21077. }
  21078. this._depthSortedFacets = [];
  21079. for (var f = 0; f < this._facetNb; f++) {
  21080. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21081. this._depthSortedFacets.push(depthSortedFacet);
  21082. }
  21083. this._invertedMatrix = BABYLON.Matrix.Identity();
  21084. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21085. }
  21086. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21087. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21088. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21089. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21090. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21091. this._subDiv.max = this._partitioningSubdivisions;
  21092. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21093. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21094. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21095. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21096. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21097. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21098. // set the parameters for ComputeNormals()
  21099. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21100. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21101. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21102. this._facetParameters.bInfo = bInfo;
  21103. this._facetParameters.bbSize = this._bbSize;
  21104. this._facetParameters.subDiv = this._subDiv;
  21105. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21106. this._facetParameters.depthSort = this._facetDepthSort;
  21107. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21108. this.computeWorldMatrix(true);
  21109. this._worldMatrix.invertToRef(this._invertedMatrix);
  21110. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21111. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21112. }
  21113. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21114. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21115. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21116. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21117. var l = (this._depthSortedIndices.length / 3) | 0;
  21118. for (var f = 0; f < l; f++) {
  21119. var sind = this._depthSortedFacets[f].ind;
  21120. this._depthSortedIndices[f * 3] = indices[sind];
  21121. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21122. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21123. }
  21124. this.updateIndices(this._depthSortedIndices);
  21125. }
  21126. return this;
  21127. };
  21128. /**
  21129. * Returns the facetLocalNormals array.
  21130. * The normals are expressed in the mesh local spac
  21131. * @returns an array of Vector3
  21132. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21133. */
  21134. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21135. if (!this._facetNormals) {
  21136. this.updateFacetData();
  21137. }
  21138. return this._facetNormals;
  21139. };
  21140. /**
  21141. * Returns the facetLocalPositions array.
  21142. * The facet positions are expressed in the mesh local space
  21143. * @returns an array of Vector3
  21144. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21145. */
  21146. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21147. if (!this._facetPositions) {
  21148. this.updateFacetData();
  21149. }
  21150. return this._facetPositions;
  21151. };
  21152. /**
  21153. * Returns the facetLocalPartioning array
  21154. * @returns an array of array of numbers
  21155. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21156. */
  21157. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21158. if (!this._facetPartitioning) {
  21159. this.updateFacetData();
  21160. }
  21161. return this._facetPartitioning;
  21162. };
  21163. /**
  21164. * Returns the i-th facet position in the world system.
  21165. * This method allocates a new Vector3 per call
  21166. * @param i defines the facet index
  21167. * @returns a new Vector3
  21168. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21169. */
  21170. AbstractMesh.prototype.getFacetPosition = function (i) {
  21171. var pos = BABYLON.Vector3.Zero();
  21172. this.getFacetPositionToRef(i, pos);
  21173. return pos;
  21174. };
  21175. /**
  21176. * Sets the reference Vector3 with the i-th facet position in the world system
  21177. * @param i defines the facet index
  21178. * @param ref defines the target vector
  21179. * @returns the current mesh
  21180. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21181. */
  21182. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21183. var localPos = (this.getFacetLocalPositions())[i];
  21184. var world = this.getWorldMatrix();
  21185. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21186. return this;
  21187. };
  21188. /**
  21189. * Returns the i-th facet normal in the world system.
  21190. * This method allocates a new Vector3 per call
  21191. * @param i defines the facet index
  21192. * @returns a new Vector3
  21193. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21194. */
  21195. AbstractMesh.prototype.getFacetNormal = function (i) {
  21196. var norm = BABYLON.Vector3.Zero();
  21197. this.getFacetNormalToRef(i, norm);
  21198. return norm;
  21199. };
  21200. /**
  21201. * Sets the reference Vector3 with the i-th facet normal in the world system
  21202. * @param i defines the facet index
  21203. * @param ref defines the target vector
  21204. * @returns the current mesh
  21205. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21206. */
  21207. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21208. var localNorm = (this.getFacetLocalNormals())[i];
  21209. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21210. return this;
  21211. };
  21212. /**
  21213. * 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)
  21214. * @param x defines x coordinate
  21215. * @param y defines y coordinate
  21216. * @param z defines z coordinate
  21217. * @returns the array of facet indexes
  21218. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21219. */
  21220. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21221. var bInfo = this.getBoundingInfo();
  21222. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21223. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21224. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21225. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21226. return null;
  21227. }
  21228. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21229. };
  21230. /**
  21231. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21232. * @param projected sets as the (x,y,z) world projection on the facet
  21233. * @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
  21234. * @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
  21235. * @param x defines x coordinate
  21236. * @param y defines y coordinate
  21237. * @param z defines z coordinate
  21238. * @returns the face index if found (or null instead)
  21239. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21240. */
  21241. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21242. if (checkFace === void 0) { checkFace = false; }
  21243. if (facing === void 0) { facing = true; }
  21244. var world = this.getWorldMatrix();
  21245. var invMat = BABYLON.Tmp.Matrix[5];
  21246. world.invertToRef(invMat);
  21247. var invVect = BABYLON.Tmp.Vector3[8];
  21248. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21249. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21250. if (projected) {
  21251. // tranform the local computed projected vector to world coordinates
  21252. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21253. }
  21254. return closest;
  21255. };
  21256. /**
  21257. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21258. * @param projected sets as the (x,y,z) local projection on the facet
  21259. * @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
  21260. * @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
  21261. * @param x defines x coordinate
  21262. * @param y defines y coordinate
  21263. * @param z defines z coordinate
  21264. * @returns the face index if found (or null instead)
  21265. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21266. */
  21267. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21268. if (checkFace === void 0) { checkFace = false; }
  21269. if (facing === void 0) { facing = true; }
  21270. var closest = null;
  21271. var tmpx = 0.0;
  21272. var tmpy = 0.0;
  21273. var tmpz = 0.0;
  21274. var d = 0.0; // tmp dot facet normal * facet position
  21275. var t0 = 0.0;
  21276. var projx = 0.0;
  21277. var projy = 0.0;
  21278. var projz = 0.0;
  21279. // Get all the facets in the same partitioning block than (x, y, z)
  21280. var facetPositions = this.getFacetLocalPositions();
  21281. var facetNormals = this.getFacetLocalNormals();
  21282. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21283. if (!facetsInBlock) {
  21284. return null;
  21285. }
  21286. // Get the closest facet to (x, y, z)
  21287. var shortest = Number.MAX_VALUE; // init distance vars
  21288. var tmpDistance = shortest;
  21289. var fib; // current facet in the block
  21290. var norm; // current facet normal
  21291. var p0; // current facet barycenter position
  21292. // loop on all the facets in the current partitioning block
  21293. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21294. fib = facetsInBlock[idx];
  21295. norm = facetNormals[fib];
  21296. p0 = facetPositions[fib];
  21297. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21298. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21299. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21300. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21301. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21302. projx = x + norm.x * t0;
  21303. projy = y + norm.y * t0;
  21304. projz = z + norm.z * t0;
  21305. tmpx = projx - x;
  21306. tmpy = projy - y;
  21307. tmpz = projz - z;
  21308. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21309. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21310. shortest = tmpDistance;
  21311. closest = fib;
  21312. if (projected) {
  21313. projected.x = projx;
  21314. projected.y = projy;
  21315. projected.z = projz;
  21316. }
  21317. }
  21318. }
  21319. }
  21320. return closest;
  21321. };
  21322. /**
  21323. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21324. * @returns the parameters
  21325. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21326. */
  21327. AbstractMesh.prototype.getFacetDataParameters = function () {
  21328. return this._facetParameters;
  21329. };
  21330. /**
  21331. * Disables the feature FacetData and frees the related memory
  21332. * @returns the current mesh
  21333. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21334. */
  21335. AbstractMesh.prototype.disableFacetData = function () {
  21336. if (this._facetDataEnabled) {
  21337. this._facetDataEnabled = false;
  21338. this._facetPositions = new Array();
  21339. this._facetNormals = new Array();
  21340. this._facetPartitioning = new Array();
  21341. this._facetParameters = null;
  21342. this._depthSortedIndices = new Uint32Array(0);
  21343. }
  21344. return this;
  21345. };
  21346. /**
  21347. * Updates the AbstractMesh indices array
  21348. * @param indices defines the data source
  21349. * @returns the current mesh
  21350. */
  21351. AbstractMesh.prototype.updateIndices = function (indices) {
  21352. return this;
  21353. };
  21354. /**
  21355. * Creates new normals data for the mesh
  21356. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21357. * @returns the current mesh
  21358. */
  21359. AbstractMesh.prototype.createNormals = function (updatable) {
  21360. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21361. var indices = this.getIndices();
  21362. var normals;
  21363. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21364. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21365. }
  21366. else {
  21367. normals = [];
  21368. }
  21369. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21370. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21371. return this;
  21372. };
  21373. /**
  21374. * Align the mesh with a normal
  21375. * @param normal defines the normal to use
  21376. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21377. * @returns the current mesh
  21378. */
  21379. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21380. if (!upDirection) {
  21381. upDirection = BABYLON.Axis.Y;
  21382. }
  21383. var axisX = BABYLON.Tmp.Vector3[0];
  21384. var axisZ = BABYLON.Tmp.Vector3[1];
  21385. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21386. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21387. if (this.rotationQuaternion) {
  21388. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21389. }
  21390. else {
  21391. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21392. }
  21393. return this;
  21394. };
  21395. /** @hidden */
  21396. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21397. this._isOccluded = false;
  21398. };
  21399. /** No occlusion */
  21400. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21401. /** Occlusion set to optimisitic */
  21402. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21403. /** Occlusion set to strict */
  21404. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21405. /** Use an accurante occlusion algorithm */
  21406. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21407. /** Use a conservative occlusion algorithm */
  21408. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21409. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21410. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21411. /** Culling strategy with bounding sphere only and then frustum culling */
  21412. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21413. return AbstractMesh;
  21414. }(BABYLON.TransformNode));
  21415. BABYLON.AbstractMesh = AbstractMesh;
  21416. })(BABYLON || (BABYLON = {}));
  21417. //# sourceMappingURL=babylon.abstractMesh.js.map
  21418. var BABYLON;
  21419. (function (BABYLON) {
  21420. /**
  21421. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21422. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21423. * 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.
  21424. */
  21425. var Light = /** @class */ (function (_super) {
  21426. __extends(Light, _super);
  21427. /**
  21428. * Creates a Light object in the scene.
  21429. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21430. * @param name The firendly name of the light
  21431. * @param scene The scene the light belongs too
  21432. */
  21433. function Light(name, scene) {
  21434. var _this = _super.call(this, name, scene) || this;
  21435. /**
  21436. * Diffuse gives the basic color to an object.
  21437. */
  21438. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21439. /**
  21440. * Specular produces a highlight color on an object.
  21441. * Note: This is note affecting PBR materials.
  21442. */
  21443. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21444. /**
  21445. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21446. * falling off base on range or angle.
  21447. * This can be set to any values in Light.FALLOFF_x.
  21448. *
  21449. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21450. * other types of materials.
  21451. */
  21452. _this.falloffType = Light.FALLOFF_DEFAULT;
  21453. /**
  21454. * Strength of the light.
  21455. * Note: By default it is define in the framework own unit.
  21456. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21457. */
  21458. _this.intensity = 1.0;
  21459. _this._range = Number.MAX_VALUE;
  21460. _this._inverseSquaredRange = 0;
  21461. /**
  21462. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21463. * of light.
  21464. */
  21465. _this._photometricScale = 1.0;
  21466. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21467. _this._radius = 0.00001;
  21468. /**
  21469. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21470. * exceeding the number allowed of the materials.
  21471. */
  21472. _this.renderPriority = 0;
  21473. _this._shadowEnabled = true;
  21474. _this._excludeWithLayerMask = 0;
  21475. _this._includeOnlyWithLayerMask = 0;
  21476. _this._lightmapMode = 0;
  21477. /**
  21478. * @hidden Internal use only.
  21479. */
  21480. _this._excludedMeshesIds = new Array();
  21481. /**
  21482. * @hidden Internal use only.
  21483. */
  21484. _this._includedOnlyMeshesIds = new Array();
  21485. _this.getScene().addLight(_this);
  21486. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21487. _this._buildUniformLayout();
  21488. _this.includedOnlyMeshes = new Array();
  21489. _this.excludedMeshes = new Array();
  21490. _this._resyncMeshes();
  21491. return _this;
  21492. }
  21493. Object.defineProperty(Light.prototype, "range", {
  21494. /**
  21495. * Defines how far from the source the light is impacting in scene units.
  21496. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21497. */
  21498. get: function () {
  21499. return this._range;
  21500. },
  21501. /**
  21502. * Defines how far from the source the light is impacting in scene units.
  21503. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21504. */
  21505. set: function (value) {
  21506. this._range = value;
  21507. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21508. },
  21509. enumerable: true,
  21510. configurable: true
  21511. });
  21512. Object.defineProperty(Light.prototype, "intensityMode", {
  21513. /**
  21514. * Gets the photometric scale used to interpret the intensity.
  21515. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21516. */
  21517. get: function () {
  21518. return this._intensityMode;
  21519. },
  21520. /**
  21521. * Sets the photometric scale used to interpret the intensity.
  21522. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21523. */
  21524. set: function (value) {
  21525. this._intensityMode = value;
  21526. this._computePhotometricScale();
  21527. },
  21528. enumerable: true,
  21529. configurable: true
  21530. });
  21531. ;
  21532. ;
  21533. Object.defineProperty(Light.prototype, "radius", {
  21534. /**
  21535. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21536. */
  21537. get: function () {
  21538. return this._radius;
  21539. },
  21540. /**
  21541. * sets the light radius used by PBR Materials to simulate soft area lights.
  21542. */
  21543. set: function (value) {
  21544. this._radius = value;
  21545. this._computePhotometricScale();
  21546. },
  21547. enumerable: true,
  21548. configurable: true
  21549. });
  21550. ;
  21551. ;
  21552. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21553. /**
  21554. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21555. * the current shadow generator.
  21556. */
  21557. get: function () {
  21558. return this._shadowEnabled;
  21559. },
  21560. /**
  21561. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21562. * the current shadow generator.
  21563. */
  21564. set: function (value) {
  21565. if (this._shadowEnabled === value) {
  21566. return;
  21567. }
  21568. this._shadowEnabled = value;
  21569. this._markMeshesAsLightDirty();
  21570. },
  21571. enumerable: true,
  21572. configurable: true
  21573. });
  21574. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21575. /**
  21576. * Gets the only meshes impacted by this light.
  21577. */
  21578. get: function () {
  21579. return this._includedOnlyMeshes;
  21580. },
  21581. /**
  21582. * Sets the only meshes impacted by this light.
  21583. */
  21584. set: function (value) {
  21585. this._includedOnlyMeshes = value;
  21586. this._hookArrayForIncludedOnly(value);
  21587. },
  21588. enumerable: true,
  21589. configurable: true
  21590. });
  21591. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21592. /**
  21593. * Gets the meshes not impacted by this light.
  21594. */
  21595. get: function () {
  21596. return this._excludedMeshes;
  21597. },
  21598. /**
  21599. * Sets the meshes not impacted by this light.
  21600. */
  21601. set: function (value) {
  21602. this._excludedMeshes = value;
  21603. this._hookArrayForExcluded(value);
  21604. },
  21605. enumerable: true,
  21606. configurable: true
  21607. });
  21608. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21609. /**
  21610. * Gets the layer id use to find what meshes are not impacted by the light.
  21611. * Inactive if 0
  21612. */
  21613. get: function () {
  21614. return this._excludeWithLayerMask;
  21615. },
  21616. /**
  21617. * Sets the layer id use to find what meshes are not impacted by the light.
  21618. * Inactive if 0
  21619. */
  21620. set: function (value) {
  21621. this._excludeWithLayerMask = value;
  21622. this._resyncMeshes();
  21623. },
  21624. enumerable: true,
  21625. configurable: true
  21626. });
  21627. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21628. /**
  21629. * Gets the layer id use to find what meshes are impacted by the light.
  21630. * Inactive if 0
  21631. */
  21632. get: function () {
  21633. return this._includeOnlyWithLayerMask;
  21634. },
  21635. /**
  21636. * Sets the layer id use to find what meshes are impacted by the light.
  21637. * Inactive if 0
  21638. */
  21639. set: function (value) {
  21640. this._includeOnlyWithLayerMask = value;
  21641. this._resyncMeshes();
  21642. },
  21643. enumerable: true,
  21644. configurable: true
  21645. });
  21646. Object.defineProperty(Light.prototype, "lightmapMode", {
  21647. /**
  21648. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21649. */
  21650. get: function () {
  21651. return this._lightmapMode;
  21652. },
  21653. /**
  21654. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21655. */
  21656. set: function (value) {
  21657. if (this._lightmapMode === value) {
  21658. return;
  21659. }
  21660. this._lightmapMode = value;
  21661. this._markMeshesAsLightDirty();
  21662. },
  21663. enumerable: true,
  21664. configurable: true
  21665. });
  21666. /**
  21667. * Returns the string "Light".
  21668. * @returns the class name
  21669. */
  21670. Light.prototype.getClassName = function () {
  21671. return "Light";
  21672. };
  21673. /**
  21674. * Converts the light information to a readable string for debug purpose.
  21675. * @param fullDetails Supports for multiple levels of logging within scene loading
  21676. * @returns the human readable light info
  21677. */
  21678. Light.prototype.toString = function (fullDetails) {
  21679. var ret = "Name: " + this.name;
  21680. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21681. if (this.animations) {
  21682. for (var i = 0; i < this.animations.length; i++) {
  21683. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21684. }
  21685. }
  21686. if (fullDetails) {
  21687. }
  21688. return ret;
  21689. };
  21690. /** @hidden */
  21691. Light.prototype._syncParentEnabledState = function () {
  21692. _super.prototype._syncParentEnabledState.call(this);
  21693. this._resyncMeshes();
  21694. };
  21695. /**
  21696. * Set the enabled state of this node.
  21697. * @param value - the new enabled state
  21698. */
  21699. Light.prototype.setEnabled = function (value) {
  21700. _super.prototype.setEnabled.call(this, value);
  21701. this._resyncMeshes();
  21702. };
  21703. /**
  21704. * Returns the Light associated shadow generator if any.
  21705. * @return the associated shadow generator.
  21706. */
  21707. Light.prototype.getShadowGenerator = function () {
  21708. return this._shadowGenerator;
  21709. };
  21710. /**
  21711. * Returns a Vector3, the absolute light position in the World.
  21712. * @returns the world space position of the light
  21713. */
  21714. Light.prototype.getAbsolutePosition = function () {
  21715. return BABYLON.Vector3.Zero();
  21716. };
  21717. /**
  21718. * Specifies if the light will affect the passed mesh.
  21719. * @param mesh The mesh to test against the light
  21720. * @return true the mesh is affected otherwise, false.
  21721. */
  21722. Light.prototype.canAffectMesh = function (mesh) {
  21723. if (!mesh) {
  21724. return true;
  21725. }
  21726. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21727. return false;
  21728. }
  21729. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21730. return false;
  21731. }
  21732. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21733. return false;
  21734. }
  21735. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21736. return false;
  21737. }
  21738. return true;
  21739. };
  21740. /**
  21741. * Sort function to order lights for rendering.
  21742. * @param a First Light object to compare to second.
  21743. * @param b Second Light object to compare first.
  21744. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21745. */
  21746. Light.CompareLightsPriority = function (a, b) {
  21747. //shadow-casting lights have priority over non-shadow-casting lights
  21748. //the renderPrioirty is a secondary sort criterion
  21749. if (a.shadowEnabled !== b.shadowEnabled) {
  21750. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21751. }
  21752. return b.renderPriority - a.renderPriority;
  21753. };
  21754. /**
  21755. * Releases resources associated with this node.
  21756. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21757. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21758. */
  21759. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21760. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21761. if (this._shadowGenerator) {
  21762. this._shadowGenerator.dispose();
  21763. this._shadowGenerator = null;
  21764. }
  21765. // Animations
  21766. this.getScene().stopAnimation(this);
  21767. // Remove from meshes
  21768. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21769. var mesh = _a[_i];
  21770. mesh._removeLightSource(this);
  21771. }
  21772. this._uniformBuffer.dispose();
  21773. // Remove from scene
  21774. this.getScene().removeLight(this);
  21775. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21776. };
  21777. /**
  21778. * Returns the light type ID (integer).
  21779. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21780. */
  21781. Light.prototype.getTypeID = function () {
  21782. return 0;
  21783. };
  21784. /**
  21785. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21786. * @returns the scaled intensity in intensity mode unit
  21787. */
  21788. Light.prototype.getScaledIntensity = function () {
  21789. return this._photometricScale * this.intensity;
  21790. };
  21791. /**
  21792. * Returns a new Light object, named "name", from the current one.
  21793. * @param name The name of the cloned light
  21794. * @returns the new created light
  21795. */
  21796. Light.prototype.clone = function (name) {
  21797. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21798. if (!constructor) {
  21799. return null;
  21800. }
  21801. return BABYLON.SerializationHelper.Clone(constructor, this);
  21802. };
  21803. /**
  21804. * Serializes the current light into a Serialization object.
  21805. * @returns the serialized object.
  21806. */
  21807. Light.prototype.serialize = function () {
  21808. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21809. // Type
  21810. serializationObject.type = this.getTypeID();
  21811. // Parent
  21812. if (this.parent) {
  21813. serializationObject.parentId = this.parent.id;
  21814. }
  21815. // Inclusion / exclusions
  21816. if (this.excludedMeshes.length > 0) {
  21817. serializationObject.excludedMeshesIds = [];
  21818. this.excludedMeshes.forEach(function (mesh) {
  21819. serializationObject.excludedMeshesIds.push(mesh.id);
  21820. });
  21821. }
  21822. if (this.includedOnlyMeshes.length > 0) {
  21823. serializationObject.includedOnlyMeshesIds = [];
  21824. this.includedOnlyMeshes.forEach(function (mesh) {
  21825. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21826. });
  21827. }
  21828. // Animations
  21829. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21830. serializationObject.ranges = this.serializeAnimationRanges();
  21831. return serializationObject;
  21832. };
  21833. /**
  21834. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21835. * This new light is named "name" and added to the passed scene.
  21836. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21837. * @param name The friendly name of the light
  21838. * @param scene The scene the new light will belong to
  21839. * @returns the constructor function
  21840. */
  21841. Light.GetConstructorFromName = function (type, name, scene) {
  21842. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21843. if (constructorFunc) {
  21844. return constructorFunc;
  21845. }
  21846. // Default to no light for none present once.
  21847. return null;
  21848. };
  21849. /**
  21850. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21851. * @param parsedLight The JSON representation of the light
  21852. * @param scene The scene to create the parsed light in
  21853. * @returns the created light after parsing
  21854. */
  21855. Light.Parse = function (parsedLight, scene) {
  21856. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21857. if (!constructor) {
  21858. return null;
  21859. }
  21860. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21861. // Inclusion / exclusions
  21862. if (parsedLight.excludedMeshesIds) {
  21863. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21864. }
  21865. if (parsedLight.includedOnlyMeshesIds) {
  21866. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21867. }
  21868. // Parent
  21869. if (parsedLight.parentId) {
  21870. light._waitingParentId = parsedLight.parentId;
  21871. }
  21872. // Animations
  21873. if (parsedLight.animations) {
  21874. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21875. var parsedAnimation = parsedLight.animations[animationIndex];
  21876. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21877. }
  21878. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21879. }
  21880. if (parsedLight.autoAnimate) {
  21881. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21882. }
  21883. return light;
  21884. };
  21885. Light.prototype._hookArrayForExcluded = function (array) {
  21886. var _this = this;
  21887. var oldPush = array.push;
  21888. array.push = function () {
  21889. var items = [];
  21890. for (var _i = 0; _i < arguments.length; _i++) {
  21891. items[_i] = arguments[_i];
  21892. }
  21893. var result = oldPush.apply(array, items);
  21894. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21895. var item = items_1[_a];
  21896. item._resyncLighSource(_this);
  21897. }
  21898. return result;
  21899. };
  21900. var oldSplice = array.splice;
  21901. array.splice = function (index, deleteCount) {
  21902. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21903. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21904. var item = deleted_1[_i];
  21905. item._resyncLighSource(_this);
  21906. }
  21907. return deleted;
  21908. };
  21909. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21910. var item = array_1[_i];
  21911. item._resyncLighSource(this);
  21912. }
  21913. };
  21914. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21915. var _this = this;
  21916. var oldPush = array.push;
  21917. array.push = function () {
  21918. var items = [];
  21919. for (var _i = 0; _i < arguments.length; _i++) {
  21920. items[_i] = arguments[_i];
  21921. }
  21922. var result = oldPush.apply(array, items);
  21923. _this._resyncMeshes();
  21924. return result;
  21925. };
  21926. var oldSplice = array.splice;
  21927. array.splice = function (index, deleteCount) {
  21928. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21929. _this._resyncMeshes();
  21930. return deleted;
  21931. };
  21932. this._resyncMeshes();
  21933. };
  21934. Light.prototype._resyncMeshes = function () {
  21935. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21936. var mesh = _a[_i];
  21937. mesh._resyncLighSource(this);
  21938. }
  21939. };
  21940. /**
  21941. * Forces the meshes to update their light related information in their rendering used effects
  21942. * @hidden Internal Use Only
  21943. */
  21944. Light.prototype._markMeshesAsLightDirty = function () {
  21945. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21946. var mesh = _a[_i];
  21947. if (mesh._lightSources.indexOf(this) !== -1) {
  21948. mesh._markSubMeshesAsLightDirty();
  21949. }
  21950. }
  21951. };
  21952. /**
  21953. * Recomputes the cached photometric scale if needed.
  21954. */
  21955. Light.prototype._computePhotometricScale = function () {
  21956. this._photometricScale = this._getPhotometricScale();
  21957. this.getScene().resetCachedMaterial();
  21958. };
  21959. /**
  21960. * Returns the Photometric Scale according to the light type and intensity mode.
  21961. */
  21962. Light.prototype._getPhotometricScale = function () {
  21963. var photometricScale = 0.0;
  21964. var lightTypeID = this.getTypeID();
  21965. //get photometric mode
  21966. var photometricMode = this.intensityMode;
  21967. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21968. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21969. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21970. }
  21971. else {
  21972. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21973. }
  21974. }
  21975. //compute photometric scale
  21976. switch (lightTypeID) {
  21977. case Light.LIGHTTYPEID_POINTLIGHT:
  21978. case Light.LIGHTTYPEID_SPOTLIGHT:
  21979. switch (photometricMode) {
  21980. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21981. photometricScale = 1.0 / (4.0 * Math.PI);
  21982. break;
  21983. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21984. photometricScale = 1.0;
  21985. break;
  21986. case Light.INTENSITYMODE_LUMINANCE:
  21987. photometricScale = this.radius * this.radius;
  21988. break;
  21989. }
  21990. break;
  21991. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21992. switch (photometricMode) {
  21993. case Light.INTENSITYMODE_ILLUMINANCE:
  21994. photometricScale = 1.0;
  21995. break;
  21996. case Light.INTENSITYMODE_LUMINANCE:
  21997. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21998. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21999. var apexAngleRadians = this.radius;
  22000. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22001. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22002. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22003. photometricScale = solidAngle;
  22004. break;
  22005. }
  22006. break;
  22007. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22008. // No fall off in hemisperic light.
  22009. photometricScale = 1.0;
  22010. break;
  22011. }
  22012. return photometricScale;
  22013. };
  22014. /**
  22015. * Reorder the light in the scene according to their defined priority.
  22016. * @hidden Internal Use Only
  22017. */
  22018. Light.prototype._reorderLightsInScene = function () {
  22019. var scene = this.getScene();
  22020. if (this._renderPriority != 0) {
  22021. scene.requireLightSorting = true;
  22022. }
  22023. this.getScene().sortLightsByPriority();
  22024. };
  22025. /**
  22026. * Falloff Default: light is falling off following the material specification:
  22027. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22028. */
  22029. Light.FALLOFF_DEFAULT = 0;
  22030. /**
  22031. * Falloff Physical: light is falling off following the inverse squared distance law.
  22032. */
  22033. Light.FALLOFF_PHYSICAL = 1;
  22034. /**
  22035. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22036. * to enhance interoperability with other engines.
  22037. */
  22038. Light.FALLOFF_GLTF = 2;
  22039. /**
  22040. * Falloff Standard: light is falling off like in the standard material
  22041. * to enhance interoperability with other materials.
  22042. */
  22043. Light.FALLOFF_STANDARD = 3;
  22044. //lightmapMode Consts
  22045. /**
  22046. * If every light affecting the material is in this lightmapMode,
  22047. * material.lightmapTexture adds or multiplies
  22048. * (depends on material.useLightmapAsShadowmap)
  22049. * after every other light calculations.
  22050. */
  22051. Light.LIGHTMAP_DEFAULT = 0;
  22052. /**
  22053. * material.lightmapTexture as only diffuse lighting from this light
  22054. * adds only specular lighting from this light
  22055. * adds dynamic shadows
  22056. */
  22057. Light.LIGHTMAP_SPECULAR = 1;
  22058. /**
  22059. * material.lightmapTexture as only lighting
  22060. * no light calculation from this light
  22061. * only adds dynamic shadows from this light
  22062. */
  22063. Light.LIGHTMAP_SHADOWSONLY = 2;
  22064. // Intensity Mode Consts
  22065. /**
  22066. * Each light type uses the default quantity according to its type:
  22067. * point/spot lights use luminous intensity
  22068. * directional lights use illuminance
  22069. */
  22070. Light.INTENSITYMODE_AUTOMATIC = 0;
  22071. /**
  22072. * lumen (lm)
  22073. */
  22074. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22075. /**
  22076. * candela (lm/sr)
  22077. */
  22078. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22079. /**
  22080. * lux (lm/m^2)
  22081. */
  22082. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22083. /**
  22084. * nit (cd/m^2)
  22085. */
  22086. Light.INTENSITYMODE_LUMINANCE = 4;
  22087. // Light types ids const.
  22088. /**
  22089. * Light type const id of the point light.
  22090. */
  22091. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22092. /**
  22093. * Light type const id of the directional light.
  22094. */
  22095. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22096. /**
  22097. * Light type const id of the spot light.
  22098. */
  22099. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22100. /**
  22101. * Light type const id of the hemispheric light.
  22102. */
  22103. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22104. __decorate([
  22105. BABYLON.serializeAsColor3()
  22106. ], Light.prototype, "diffuse", void 0);
  22107. __decorate([
  22108. BABYLON.serializeAsColor3()
  22109. ], Light.prototype, "specular", void 0);
  22110. __decorate([
  22111. BABYLON.serialize()
  22112. ], Light.prototype, "falloffType", void 0);
  22113. __decorate([
  22114. BABYLON.serialize()
  22115. ], Light.prototype, "intensity", void 0);
  22116. __decorate([
  22117. BABYLON.serialize()
  22118. ], Light.prototype, "range", null);
  22119. __decorate([
  22120. BABYLON.serialize()
  22121. ], Light.prototype, "intensityMode", null);
  22122. __decorate([
  22123. BABYLON.serialize()
  22124. ], Light.prototype, "radius", null);
  22125. __decorate([
  22126. BABYLON.serialize()
  22127. ], Light.prototype, "_renderPriority", void 0);
  22128. __decorate([
  22129. BABYLON.expandToProperty("_reorderLightsInScene")
  22130. ], Light.prototype, "renderPriority", void 0);
  22131. __decorate([
  22132. BABYLON.serialize("shadowEnabled")
  22133. ], Light.prototype, "_shadowEnabled", void 0);
  22134. __decorate([
  22135. BABYLON.serialize("excludeWithLayerMask")
  22136. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22137. __decorate([
  22138. BABYLON.serialize("includeOnlyWithLayerMask")
  22139. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22140. __decorate([
  22141. BABYLON.serialize("lightmapMode")
  22142. ], Light.prototype, "_lightmapMode", void 0);
  22143. return Light;
  22144. }(BABYLON.Node));
  22145. BABYLON.Light = Light;
  22146. })(BABYLON || (BABYLON = {}));
  22147. //# sourceMappingURL=babylon.light.js.map
  22148. var BABYLON;
  22149. (function (BABYLON) {
  22150. var Camera = /** @class */ (function (_super) {
  22151. __extends(Camera, _super);
  22152. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22153. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22154. var _this = _super.call(this, name, scene) || this;
  22155. /**
  22156. * The vector the camera should consider as up.
  22157. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22158. */
  22159. _this.upVector = BABYLON.Vector3.Up();
  22160. _this.orthoLeft = null;
  22161. _this.orthoRight = null;
  22162. _this.orthoBottom = null;
  22163. _this.orthoTop = null;
  22164. /**
  22165. * FOV is set in Radians. (default is 0.8)
  22166. */
  22167. _this.fov = 0.8;
  22168. _this.minZ = 1;
  22169. _this.maxZ = 10000.0;
  22170. _this.inertia = 0.9;
  22171. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22172. _this.isIntermediate = false;
  22173. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22174. /**
  22175. * Restricts the camera to viewing objects with the same layerMask.
  22176. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22177. */
  22178. _this.layerMask = 0x0FFFFFFF;
  22179. /**
  22180. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22181. */
  22182. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22183. // Camera rig members
  22184. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22185. /** @hidden */
  22186. _this._rigCameras = new Array();
  22187. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22188. /** @hidden */
  22189. _this._skipRendering = false;
  22190. _this.customRenderTargets = new Array();
  22191. // Observables
  22192. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22193. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22194. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22195. _this.onRestoreStateObservable = new BABYLON.Observable();
  22196. // Cache
  22197. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22198. _this._projectionMatrix = new BABYLON.Matrix();
  22199. _this._doNotComputeProjectionMatrix = false;
  22200. _this._postProcesses = new Array();
  22201. _this._transformMatrix = BABYLON.Matrix.Zero();
  22202. _this._activeMeshes = new BABYLON.SmartArray(256);
  22203. _this._globalPosition = BABYLON.Vector3.Zero();
  22204. _this._refreshFrustumPlanes = true;
  22205. _this.getScene().addCamera(_this);
  22206. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22207. _this.getScene().activeCamera = _this;
  22208. }
  22209. _this.position = position;
  22210. return _this;
  22211. }
  22212. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22213. get: function () {
  22214. return Camera._PERSPECTIVE_CAMERA;
  22215. },
  22216. enumerable: true,
  22217. configurable: true
  22218. });
  22219. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22220. get: function () {
  22221. return Camera._ORTHOGRAPHIC_CAMERA;
  22222. },
  22223. enumerable: true,
  22224. configurable: true
  22225. });
  22226. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22227. /**
  22228. * This is the default FOV mode for perspective cameras.
  22229. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22230. *
  22231. */
  22232. get: function () {
  22233. return Camera._FOVMODE_VERTICAL_FIXED;
  22234. },
  22235. enumerable: true,
  22236. configurable: true
  22237. });
  22238. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22239. /**
  22240. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22241. *
  22242. */
  22243. get: function () {
  22244. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22245. },
  22246. enumerable: true,
  22247. configurable: true
  22248. });
  22249. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22250. get: function () {
  22251. return Camera._RIG_MODE_NONE;
  22252. },
  22253. enumerable: true,
  22254. configurable: true
  22255. });
  22256. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22257. get: function () {
  22258. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22259. },
  22260. enumerable: true,
  22261. configurable: true
  22262. });
  22263. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22264. get: function () {
  22265. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22266. },
  22267. enumerable: true,
  22268. configurable: true
  22269. });
  22270. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22271. get: function () {
  22272. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22273. },
  22274. enumerable: true,
  22275. configurable: true
  22276. });
  22277. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22278. get: function () {
  22279. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22280. },
  22281. enumerable: true,
  22282. configurable: true
  22283. });
  22284. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22285. get: function () {
  22286. return Camera._RIG_MODE_VR;
  22287. },
  22288. enumerable: true,
  22289. configurable: true
  22290. });
  22291. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22292. get: function () {
  22293. return Camera._RIG_MODE_WEBVR;
  22294. },
  22295. enumerable: true,
  22296. configurable: true
  22297. });
  22298. /**
  22299. * Store current camera state (fov, position, etc..)
  22300. */
  22301. Camera.prototype.storeState = function () {
  22302. this._stateStored = true;
  22303. this._storedFov = this.fov;
  22304. return this;
  22305. };
  22306. /**
  22307. * Restores the camera state values if it has been stored. You must call storeState() first
  22308. */
  22309. Camera.prototype._restoreStateValues = function () {
  22310. if (!this._stateStored) {
  22311. return false;
  22312. }
  22313. this.fov = this._storedFov;
  22314. return true;
  22315. };
  22316. /**
  22317. * Restored camera state. You must call storeState() first
  22318. */
  22319. Camera.prototype.restoreState = function () {
  22320. if (this._restoreStateValues()) {
  22321. this.onRestoreStateObservable.notifyObservers(this);
  22322. return true;
  22323. }
  22324. return false;
  22325. };
  22326. Camera.prototype.getClassName = function () {
  22327. return "Camera";
  22328. };
  22329. /**
  22330. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22331. */
  22332. Camera.prototype.toString = function (fullDetails) {
  22333. var ret = "Name: " + this.name;
  22334. ret += ", type: " + this.getClassName();
  22335. if (this.animations) {
  22336. for (var i = 0; i < this.animations.length; i++) {
  22337. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22338. }
  22339. }
  22340. if (fullDetails) {
  22341. }
  22342. return ret;
  22343. };
  22344. Object.defineProperty(Camera.prototype, "globalPosition", {
  22345. get: function () {
  22346. return this._globalPosition;
  22347. },
  22348. enumerable: true,
  22349. configurable: true
  22350. });
  22351. Camera.prototype.getActiveMeshes = function () {
  22352. return this._activeMeshes;
  22353. };
  22354. Camera.prototype.isActiveMesh = function (mesh) {
  22355. return (this._activeMeshes.indexOf(mesh) !== -1);
  22356. };
  22357. /**
  22358. * Is this camera ready to be used/rendered
  22359. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22360. * @return true if the camera is ready
  22361. */
  22362. Camera.prototype.isReady = function (completeCheck) {
  22363. if (completeCheck === void 0) { completeCheck = false; }
  22364. if (completeCheck) {
  22365. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22366. var pp = _a[_i];
  22367. if (pp && !pp.isReady()) {
  22368. return false;
  22369. }
  22370. }
  22371. }
  22372. return _super.prototype.isReady.call(this, completeCheck);
  22373. };
  22374. //Cache
  22375. /** @hidden */
  22376. Camera.prototype._initCache = function () {
  22377. _super.prototype._initCache.call(this);
  22378. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22379. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22380. this._cache.mode = undefined;
  22381. this._cache.minZ = undefined;
  22382. this._cache.maxZ = undefined;
  22383. this._cache.fov = undefined;
  22384. this._cache.fovMode = undefined;
  22385. this._cache.aspectRatio = undefined;
  22386. this._cache.orthoLeft = undefined;
  22387. this._cache.orthoRight = undefined;
  22388. this._cache.orthoBottom = undefined;
  22389. this._cache.orthoTop = undefined;
  22390. this._cache.renderWidth = undefined;
  22391. this._cache.renderHeight = undefined;
  22392. };
  22393. /** @hidden */
  22394. Camera.prototype._updateCache = function (ignoreParentClass) {
  22395. if (!ignoreParentClass) {
  22396. _super.prototype._updateCache.call(this);
  22397. }
  22398. this._cache.position.copyFrom(this.position);
  22399. this._cache.upVector.copyFrom(this.upVector);
  22400. };
  22401. // Synchronized
  22402. /** @hidden */
  22403. Camera.prototype._isSynchronized = function () {
  22404. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22405. };
  22406. /** @hidden */
  22407. Camera.prototype._isSynchronizedViewMatrix = function () {
  22408. if (!_super.prototype._isSynchronized.call(this))
  22409. return false;
  22410. return this._cache.position.equals(this.position)
  22411. && this._cache.upVector.equals(this.upVector)
  22412. && this.isSynchronizedWithParent();
  22413. };
  22414. /** @hidden */
  22415. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22416. var check = this._cache.mode === this.mode
  22417. && this._cache.minZ === this.minZ
  22418. && this._cache.maxZ === this.maxZ;
  22419. if (!check) {
  22420. return false;
  22421. }
  22422. var engine = this.getEngine();
  22423. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22424. check = this._cache.fov === this.fov
  22425. && this._cache.fovMode === this.fovMode
  22426. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22427. }
  22428. else {
  22429. check = this._cache.orthoLeft === this.orthoLeft
  22430. && this._cache.orthoRight === this.orthoRight
  22431. && this._cache.orthoBottom === this.orthoBottom
  22432. && this._cache.orthoTop === this.orthoTop
  22433. && this._cache.renderWidth === engine.getRenderWidth()
  22434. && this._cache.renderHeight === engine.getRenderHeight();
  22435. }
  22436. return check;
  22437. };
  22438. // Controls
  22439. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22440. };
  22441. Camera.prototype.detachControl = function (element) {
  22442. };
  22443. Camera.prototype.update = function () {
  22444. this._checkInputs();
  22445. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22446. this._updateRigCameras();
  22447. }
  22448. };
  22449. /** @hidden */
  22450. Camera.prototype._checkInputs = function () {
  22451. this.onAfterCheckInputsObservable.notifyObservers(this);
  22452. };
  22453. Object.defineProperty(Camera.prototype, "rigCameras", {
  22454. get: function () {
  22455. return this._rigCameras;
  22456. },
  22457. enumerable: true,
  22458. configurable: true
  22459. });
  22460. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22461. get: function () {
  22462. return this._rigPostProcess;
  22463. },
  22464. enumerable: true,
  22465. configurable: true
  22466. });
  22467. /**
  22468. * Internal, gets the first post proces.
  22469. * @returns the first post process to be run on this camera.
  22470. */
  22471. Camera.prototype._getFirstPostProcess = function () {
  22472. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22473. if (this._postProcesses[ppIndex] !== null) {
  22474. return this._postProcesses[ppIndex];
  22475. }
  22476. }
  22477. return null;
  22478. };
  22479. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22480. // invalidate framebuffer
  22481. var firstPostProcess = this._getFirstPostProcess();
  22482. if (firstPostProcess) {
  22483. firstPostProcess.markTextureDirty();
  22484. }
  22485. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22486. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22487. var cam = this._rigCameras[i];
  22488. var rigPostProcess = cam._rigPostProcess;
  22489. // for VR rig, there does not have to be a post process
  22490. if (rigPostProcess) {
  22491. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22492. if (isPass) {
  22493. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22494. cam.isIntermediate = this._postProcesses.length === 0;
  22495. }
  22496. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22497. rigPostProcess.markTextureDirty();
  22498. }
  22499. else {
  22500. cam._postProcesses = this._postProcesses.slice(0);
  22501. }
  22502. }
  22503. };
  22504. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22505. if (insertAt === void 0) { insertAt = null; }
  22506. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22507. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22508. return 0;
  22509. }
  22510. if (insertAt == null || insertAt < 0) {
  22511. this._postProcesses.push(postProcess);
  22512. }
  22513. else if (this._postProcesses[insertAt] === null) {
  22514. this._postProcesses[insertAt] = postProcess;
  22515. }
  22516. else {
  22517. this._postProcesses.splice(insertAt, 0, postProcess);
  22518. }
  22519. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22520. return this._postProcesses.indexOf(postProcess);
  22521. };
  22522. Camera.prototype.detachPostProcess = function (postProcess) {
  22523. var idx = this._postProcesses.indexOf(postProcess);
  22524. if (idx !== -1) {
  22525. this._postProcesses[idx] = null;
  22526. }
  22527. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22528. };
  22529. Camera.prototype.getWorldMatrix = function () {
  22530. if (this._isSynchronizedViewMatrix()) {
  22531. return this._worldMatrix;
  22532. }
  22533. // Getting the the view matrix will also compute the world matrix.
  22534. this.getViewMatrix();
  22535. return this._worldMatrix;
  22536. };
  22537. /** @hidden */
  22538. Camera.prototype._getViewMatrix = function () {
  22539. return BABYLON.Matrix.Identity();
  22540. };
  22541. Camera.prototype.getViewMatrix = function (force) {
  22542. if (!force && this._isSynchronizedViewMatrix()) {
  22543. return this._computedViewMatrix;
  22544. }
  22545. this.updateCache();
  22546. this._computedViewMatrix = this._getViewMatrix();
  22547. this._currentRenderId = this.getScene().getRenderId();
  22548. this._childRenderId = this._currentRenderId;
  22549. this._refreshFrustumPlanes = true;
  22550. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22551. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22552. }
  22553. this.onViewMatrixChangedObservable.notifyObservers(this);
  22554. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22555. return this._computedViewMatrix;
  22556. };
  22557. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22558. this._doNotComputeProjectionMatrix = true;
  22559. if (projection !== undefined) {
  22560. this._projectionMatrix = projection;
  22561. }
  22562. };
  22563. ;
  22564. Camera.prototype.unfreezeProjectionMatrix = function () {
  22565. this._doNotComputeProjectionMatrix = false;
  22566. };
  22567. ;
  22568. Camera.prototype.getProjectionMatrix = function (force) {
  22569. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22570. return this._projectionMatrix;
  22571. }
  22572. // Cache
  22573. this._cache.mode = this.mode;
  22574. this._cache.minZ = this.minZ;
  22575. this._cache.maxZ = this.maxZ;
  22576. // Matrix
  22577. this._refreshFrustumPlanes = true;
  22578. var engine = this.getEngine();
  22579. var scene = this.getScene();
  22580. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22581. this._cache.fov = this.fov;
  22582. this._cache.fovMode = this.fovMode;
  22583. this._cache.aspectRatio = engine.getAspectRatio(this);
  22584. if (this.minZ <= 0) {
  22585. this.minZ = 0.1;
  22586. }
  22587. if (scene.useRightHandedSystem) {
  22588. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22589. }
  22590. else {
  22591. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22592. }
  22593. }
  22594. else {
  22595. var halfWidth = engine.getRenderWidth() / 2.0;
  22596. var halfHeight = engine.getRenderHeight() / 2.0;
  22597. if (scene.useRightHandedSystem) {
  22598. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22599. }
  22600. else {
  22601. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22602. }
  22603. this._cache.orthoLeft = this.orthoLeft;
  22604. this._cache.orthoRight = this.orthoRight;
  22605. this._cache.orthoBottom = this.orthoBottom;
  22606. this._cache.orthoTop = this.orthoTop;
  22607. this._cache.renderWidth = engine.getRenderWidth();
  22608. this._cache.renderHeight = engine.getRenderHeight();
  22609. }
  22610. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22611. return this._projectionMatrix;
  22612. };
  22613. /**
  22614. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22615. * @returns a Matrix
  22616. */
  22617. Camera.prototype.getTransformationMatrix = function () {
  22618. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22619. return this._transformMatrix;
  22620. };
  22621. Camera.prototype.updateFrustumPlanes = function () {
  22622. if (!this._refreshFrustumPlanes) {
  22623. return;
  22624. }
  22625. this.getTransformationMatrix();
  22626. if (!this._frustumPlanes) {
  22627. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22628. }
  22629. else {
  22630. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22631. }
  22632. this._refreshFrustumPlanes = false;
  22633. };
  22634. Camera.prototype.isInFrustum = function (target) {
  22635. this.updateFrustumPlanes();
  22636. return target.isInFrustum(this._frustumPlanes);
  22637. };
  22638. Camera.prototype.isCompletelyInFrustum = function (target) {
  22639. this.updateFrustumPlanes();
  22640. return target.isCompletelyInFrustum(this._frustumPlanes);
  22641. };
  22642. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22643. if (length === void 0) { length = 100; }
  22644. if (!transform) {
  22645. transform = this.getWorldMatrix();
  22646. }
  22647. if (!origin) {
  22648. origin = this.position;
  22649. }
  22650. var forward = new BABYLON.Vector3(0, 0, 1);
  22651. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22652. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22653. return new BABYLON.Ray(origin, direction, length);
  22654. };
  22655. /**
  22656. * Releases resources associated with this node.
  22657. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22658. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22659. */
  22660. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22661. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22662. // Observables
  22663. this.onViewMatrixChangedObservable.clear();
  22664. this.onProjectionMatrixChangedObservable.clear();
  22665. this.onAfterCheckInputsObservable.clear();
  22666. this.onRestoreStateObservable.clear();
  22667. // Inputs
  22668. if (this.inputs) {
  22669. this.inputs.clear();
  22670. }
  22671. // Animations
  22672. this.getScene().stopAnimation(this);
  22673. // Remove from scene
  22674. this.getScene().removeCamera(this);
  22675. while (this._rigCameras.length > 0) {
  22676. var camera = this._rigCameras.pop();
  22677. if (camera) {
  22678. camera.dispose();
  22679. }
  22680. }
  22681. // Postprocesses
  22682. if (this._rigPostProcess) {
  22683. this._rigPostProcess.dispose(this);
  22684. this._rigPostProcess = null;
  22685. this._postProcesses = [];
  22686. }
  22687. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22688. this._rigPostProcess = null;
  22689. this._postProcesses = [];
  22690. }
  22691. else {
  22692. var i = this._postProcesses.length;
  22693. while (--i >= 0) {
  22694. var postProcess = this._postProcesses[i];
  22695. if (postProcess) {
  22696. postProcess.dispose(this);
  22697. }
  22698. }
  22699. }
  22700. // Render targets
  22701. var i = this.customRenderTargets.length;
  22702. while (--i >= 0) {
  22703. this.customRenderTargets[i].dispose();
  22704. }
  22705. this.customRenderTargets = [];
  22706. // Active Meshes
  22707. this._activeMeshes.dispose();
  22708. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22709. };
  22710. Object.defineProperty(Camera.prototype, "leftCamera", {
  22711. // ---- Camera rigs section ----
  22712. get: function () {
  22713. if (this._rigCameras.length < 1) {
  22714. return null;
  22715. }
  22716. return this._rigCameras[0];
  22717. },
  22718. enumerable: true,
  22719. configurable: true
  22720. });
  22721. Object.defineProperty(Camera.prototype, "rightCamera", {
  22722. get: function () {
  22723. if (this._rigCameras.length < 2) {
  22724. return null;
  22725. }
  22726. return this._rigCameras[1];
  22727. },
  22728. enumerable: true,
  22729. configurable: true
  22730. });
  22731. Camera.prototype.getLeftTarget = function () {
  22732. if (this._rigCameras.length < 1) {
  22733. return null;
  22734. }
  22735. return this._rigCameras[0].getTarget();
  22736. };
  22737. Camera.prototype.getRightTarget = function () {
  22738. if (this._rigCameras.length < 2) {
  22739. return null;
  22740. }
  22741. return this._rigCameras[1].getTarget();
  22742. };
  22743. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22744. if (this.cameraRigMode === mode) {
  22745. return;
  22746. }
  22747. while (this._rigCameras.length > 0) {
  22748. var camera = this._rigCameras.pop();
  22749. if (camera) {
  22750. camera.dispose();
  22751. }
  22752. }
  22753. this.cameraRigMode = mode;
  22754. this._cameraRigParams = {};
  22755. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22756. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22757. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22758. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22759. // create the rig cameras, unless none
  22760. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22761. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22762. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22763. if (leftCamera && rightCamera) {
  22764. this._rigCameras.push(leftCamera);
  22765. this._rigCameras.push(rightCamera);
  22766. }
  22767. }
  22768. switch (this.cameraRigMode) {
  22769. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22770. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22771. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22772. break;
  22773. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22774. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22775. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22776. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22777. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22778. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22779. break;
  22780. case Camera.RIG_MODE_VR:
  22781. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22782. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22783. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22784. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22785. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22786. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22787. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22788. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22789. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22790. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22791. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22792. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22793. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22794. if (metrics.compensateDistortion) {
  22795. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22796. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22797. }
  22798. break;
  22799. case Camera.RIG_MODE_WEBVR:
  22800. if (rigParams.vrDisplay) {
  22801. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22802. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22803. //Left eye
  22804. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22805. this._rigCameras[0].setCameraRigParameter("left", true);
  22806. //leaving this for future reference
  22807. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22808. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22809. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22810. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22811. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22812. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22813. this._rigCameras[0].parent = this;
  22814. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22815. //Right eye
  22816. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22817. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22818. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22819. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22820. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22821. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22822. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22823. this._rigCameras[1].parent = this;
  22824. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22825. if (Camera.UseAlternateWebVRRendering) {
  22826. this._rigCameras[1]._skipRendering = true;
  22827. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22828. }
  22829. }
  22830. break;
  22831. }
  22832. this._cascadePostProcessesToRigCams();
  22833. this.update();
  22834. };
  22835. Camera.prototype._getVRProjectionMatrix = function () {
  22836. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22837. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22838. return this._projectionMatrix;
  22839. };
  22840. Camera.prototype._updateCameraRotationMatrix = function () {
  22841. //Here for WebVR
  22842. };
  22843. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22844. //Here for WebVR
  22845. };
  22846. /**
  22847. * This function MUST be overwritten by the different WebVR cameras available.
  22848. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22849. */
  22850. Camera.prototype._getWebVRProjectionMatrix = function () {
  22851. return BABYLON.Matrix.Identity();
  22852. };
  22853. /**
  22854. * This function MUST be overwritten by the different WebVR cameras available.
  22855. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22856. */
  22857. Camera.prototype._getWebVRViewMatrix = function () {
  22858. return BABYLON.Matrix.Identity();
  22859. };
  22860. Camera.prototype.setCameraRigParameter = function (name, value) {
  22861. if (!this._cameraRigParams) {
  22862. this._cameraRigParams = {};
  22863. }
  22864. this._cameraRigParams[name] = value;
  22865. //provisionnally:
  22866. if (name === "interaxialDistance") {
  22867. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22868. }
  22869. };
  22870. /**
  22871. * needs to be overridden by children so sub has required properties to be copied
  22872. */
  22873. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22874. return null;
  22875. };
  22876. /**
  22877. * May need to be overridden by children
  22878. * @hidden
  22879. */
  22880. Camera.prototype._updateRigCameras = function () {
  22881. for (var i = 0; i < this._rigCameras.length; i++) {
  22882. this._rigCameras[i].minZ = this.minZ;
  22883. this._rigCameras[i].maxZ = this.maxZ;
  22884. this._rigCameras[i].fov = this.fov;
  22885. }
  22886. // only update viewport when ANAGLYPH
  22887. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22888. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22889. }
  22890. };
  22891. /** @hidden */
  22892. Camera.prototype._setupInputs = function () {
  22893. };
  22894. Camera.prototype.serialize = function () {
  22895. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22896. // Type
  22897. serializationObject.type = this.getClassName();
  22898. // Parent
  22899. if (this.parent) {
  22900. serializationObject.parentId = this.parent.id;
  22901. }
  22902. if (this.inputs) {
  22903. this.inputs.serialize(serializationObject);
  22904. }
  22905. // Animations
  22906. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22907. serializationObject.ranges = this.serializeAnimationRanges();
  22908. return serializationObject;
  22909. };
  22910. Camera.prototype.clone = function (name) {
  22911. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22912. };
  22913. Camera.prototype.getDirection = function (localAxis) {
  22914. var result = BABYLON.Vector3.Zero();
  22915. this.getDirectionToRef(localAxis, result);
  22916. return result;
  22917. };
  22918. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22919. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22920. };
  22921. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22922. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22923. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22924. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22925. interaxial_distance: interaxial_distance,
  22926. isStereoscopicSideBySide: isStereoscopicSideBySide
  22927. });
  22928. if (constructorFunc) {
  22929. return constructorFunc;
  22930. }
  22931. // Default to universal camera
  22932. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22933. };
  22934. Camera.prototype.computeWorldMatrix = function () {
  22935. return this.getWorldMatrix();
  22936. };
  22937. Camera.Parse = function (parsedCamera, scene) {
  22938. var type = parsedCamera.type;
  22939. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22940. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22941. // Parent
  22942. if (parsedCamera.parentId) {
  22943. camera._waitingParentId = parsedCamera.parentId;
  22944. }
  22945. //If camera has an input manager, let it parse inputs settings
  22946. if (camera.inputs) {
  22947. camera.inputs.parse(parsedCamera);
  22948. camera._setupInputs();
  22949. }
  22950. if (camera.setPosition) { // need to force position
  22951. camera.position.copyFromFloats(0, 0, 0);
  22952. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22953. }
  22954. // Target
  22955. if (parsedCamera.target) {
  22956. if (camera.setTarget) {
  22957. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22958. }
  22959. }
  22960. // Apply 3d rig, when found
  22961. if (parsedCamera.cameraRigMode) {
  22962. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22963. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22964. }
  22965. // Animations
  22966. if (parsedCamera.animations) {
  22967. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22968. var parsedAnimation = parsedCamera.animations[animationIndex];
  22969. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22970. }
  22971. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22972. }
  22973. if (parsedCamera.autoAnimate) {
  22974. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22975. }
  22976. return camera;
  22977. };
  22978. // Statics
  22979. Camera._PERSPECTIVE_CAMERA = 0;
  22980. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22981. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22982. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22983. Camera._RIG_MODE_NONE = 0;
  22984. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22985. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22986. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22987. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22988. Camera._RIG_MODE_VR = 20;
  22989. Camera._RIG_MODE_WEBVR = 21;
  22990. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22991. Camera.UseAlternateWebVRRendering = false;
  22992. __decorate([
  22993. BABYLON.serializeAsVector3()
  22994. ], Camera.prototype, "position", void 0);
  22995. __decorate([
  22996. BABYLON.serializeAsVector3()
  22997. ], Camera.prototype, "upVector", void 0);
  22998. __decorate([
  22999. BABYLON.serialize()
  23000. ], Camera.prototype, "orthoLeft", void 0);
  23001. __decorate([
  23002. BABYLON.serialize()
  23003. ], Camera.prototype, "orthoRight", void 0);
  23004. __decorate([
  23005. BABYLON.serialize()
  23006. ], Camera.prototype, "orthoBottom", void 0);
  23007. __decorate([
  23008. BABYLON.serialize()
  23009. ], Camera.prototype, "orthoTop", void 0);
  23010. __decorate([
  23011. BABYLON.serialize()
  23012. ], Camera.prototype, "fov", void 0);
  23013. __decorate([
  23014. BABYLON.serialize()
  23015. ], Camera.prototype, "minZ", void 0);
  23016. __decorate([
  23017. BABYLON.serialize()
  23018. ], Camera.prototype, "maxZ", void 0);
  23019. __decorate([
  23020. BABYLON.serialize()
  23021. ], Camera.prototype, "inertia", void 0);
  23022. __decorate([
  23023. BABYLON.serialize()
  23024. ], Camera.prototype, "mode", void 0);
  23025. __decorate([
  23026. BABYLON.serialize()
  23027. ], Camera.prototype, "layerMask", void 0);
  23028. __decorate([
  23029. BABYLON.serialize()
  23030. ], Camera.prototype, "fovMode", void 0);
  23031. __decorate([
  23032. BABYLON.serialize()
  23033. ], Camera.prototype, "cameraRigMode", void 0);
  23034. __decorate([
  23035. BABYLON.serialize()
  23036. ], Camera.prototype, "interaxialDistance", void 0);
  23037. __decorate([
  23038. BABYLON.serialize()
  23039. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23040. return Camera;
  23041. }(BABYLON.Node));
  23042. BABYLON.Camera = Camera;
  23043. })(BABYLON || (BABYLON = {}));
  23044. //# sourceMappingURL=babylon.camera.js.map
  23045. var BABYLON;
  23046. (function (BABYLON) {
  23047. var RenderingManager = /** @class */ (function () {
  23048. function RenderingManager(scene) {
  23049. /**
  23050. * @hidden
  23051. */
  23052. this._useSceneAutoClearSetup = false;
  23053. this._renderingGroups = new Array();
  23054. this._autoClearDepthStencil = {};
  23055. this._customOpaqueSortCompareFn = {};
  23056. this._customAlphaTestSortCompareFn = {};
  23057. this._customTransparentSortCompareFn = {};
  23058. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23059. this._scene = scene;
  23060. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23061. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23062. }
  23063. }
  23064. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23065. if (depth === void 0) { depth = true; }
  23066. if (stencil === void 0) { stencil = true; }
  23067. if (this._depthStencilBufferAlreadyCleaned) {
  23068. return;
  23069. }
  23070. this._scene.getEngine().clear(null, false, depth, stencil);
  23071. this._depthStencilBufferAlreadyCleaned = true;
  23072. };
  23073. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23074. // Update the observable context (not null as it only goes away on dispose)
  23075. var info = this._renderingGroupInfo;
  23076. info.scene = this._scene;
  23077. info.camera = this._scene.activeCamera;
  23078. // Dispatch sprites
  23079. if (this._scene.spriteManagers && renderSprites) {
  23080. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23081. var manager = this._scene.spriteManagers[index];
  23082. this.dispatchSprites(manager);
  23083. }
  23084. }
  23085. // Render
  23086. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23087. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23088. var renderingGroup = this._renderingGroups[index];
  23089. if (!renderingGroup)
  23090. continue;
  23091. var renderingGroupMask = Math.pow(2, index);
  23092. info.renderingGroupId = index;
  23093. // Before Observable
  23094. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23095. // Clear depth/stencil if needed
  23096. if (RenderingManager.AUTOCLEAR) {
  23097. var autoClear = this._useSceneAutoClearSetup ?
  23098. this._scene.getAutoClearDepthStencilSetup(index) :
  23099. this._autoClearDepthStencil[index];
  23100. if (autoClear && autoClear.autoClear) {
  23101. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23102. }
  23103. }
  23104. // Render
  23105. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23106. var step = _a[_i];
  23107. step.action(index);
  23108. }
  23109. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23110. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23111. var step = _c[_b];
  23112. step.action(index);
  23113. }
  23114. // After Observable
  23115. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23116. }
  23117. };
  23118. RenderingManager.prototype.reset = function () {
  23119. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23120. var renderingGroup = this._renderingGroups[index];
  23121. if (renderingGroup) {
  23122. renderingGroup.prepare();
  23123. }
  23124. }
  23125. };
  23126. RenderingManager.prototype.dispose = function () {
  23127. this.freeRenderingGroups();
  23128. this._renderingGroups.length = 0;
  23129. this._renderingGroupInfo = null;
  23130. };
  23131. /**
  23132. * Clear the info related to rendering groups preventing retention points during dispose.
  23133. */
  23134. RenderingManager.prototype.freeRenderingGroups = function () {
  23135. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23136. var renderingGroup = this._renderingGroups[index];
  23137. if (renderingGroup) {
  23138. renderingGroup.dispose();
  23139. }
  23140. }
  23141. };
  23142. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23143. if (this._renderingGroups[renderingGroupId] === undefined) {
  23144. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23145. }
  23146. };
  23147. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23148. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23149. this._prepareRenderingGroup(renderingGroupId);
  23150. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23151. };
  23152. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23153. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23154. this._prepareRenderingGroup(renderingGroupId);
  23155. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23156. };
  23157. /**
  23158. * @param subMesh The submesh to dispatch
  23159. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23160. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23161. */
  23162. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23163. if (mesh === undefined) {
  23164. mesh = subMesh.getMesh();
  23165. }
  23166. var renderingGroupId = mesh.renderingGroupId || 0;
  23167. this._prepareRenderingGroup(renderingGroupId);
  23168. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23169. };
  23170. /**
  23171. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23172. * This allowed control for front to back rendering or reversly depending of the special needs.
  23173. *
  23174. * @param renderingGroupId The rendering group id corresponding to its index
  23175. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23176. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23177. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23178. */
  23179. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23180. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23181. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23182. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23183. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23184. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23185. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23186. if (this._renderingGroups[renderingGroupId]) {
  23187. var group = this._renderingGroups[renderingGroupId];
  23188. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23189. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23190. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23191. }
  23192. };
  23193. /**
  23194. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23195. *
  23196. * @param renderingGroupId The rendering group id corresponding to its index
  23197. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23198. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23199. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23200. */
  23201. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23202. if (depth === void 0) { depth = true; }
  23203. if (stencil === void 0) { stencil = true; }
  23204. this._autoClearDepthStencil[renderingGroupId] = {
  23205. autoClear: autoClearDepthStencil,
  23206. depth: depth,
  23207. stencil: stencil
  23208. };
  23209. };
  23210. /**
  23211. * Gets the current auto clear configuration for one rendering group of the rendering
  23212. * manager.
  23213. * @param index the rendering group index to get the information for
  23214. * @returns The auto clear setup for the requested rendering group
  23215. */
  23216. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23217. return this._autoClearDepthStencil[index];
  23218. };
  23219. /**
  23220. * The max id used for rendering groups (not included)
  23221. */
  23222. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23223. /**
  23224. * The min id used for rendering groups (included)
  23225. */
  23226. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23227. /**
  23228. * Used to globally prevent autoclearing scenes.
  23229. */
  23230. RenderingManager.AUTOCLEAR = true;
  23231. return RenderingManager;
  23232. }());
  23233. BABYLON.RenderingManager = RenderingManager;
  23234. })(BABYLON || (BABYLON = {}));
  23235. //# sourceMappingURL=babylon.renderingManager.js.map
  23236. var BABYLON;
  23237. (function (BABYLON) {
  23238. var RenderingGroup = /** @class */ (function () {
  23239. /**
  23240. * Creates a new rendering group.
  23241. * @param index The rendering group index
  23242. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23243. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23244. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23245. */
  23246. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23247. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23248. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23249. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23250. this.index = index;
  23251. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23252. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23253. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23254. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23255. this._particleSystems = new BABYLON.SmartArray(256);
  23256. this._spriteManagers = new BABYLON.SmartArray(256);
  23257. this._edgesRenderers = new BABYLON.SmartArray(16);
  23258. this._scene = scene;
  23259. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23260. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23261. this.transparentSortCompareFn = transparentSortCompareFn;
  23262. }
  23263. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23264. /**
  23265. * Set the opaque sort comparison function.
  23266. * If null the sub meshes will be render in the order they were created
  23267. */
  23268. set: function (value) {
  23269. this._opaqueSortCompareFn = value;
  23270. if (value) {
  23271. this._renderOpaque = this.renderOpaqueSorted;
  23272. }
  23273. else {
  23274. this._renderOpaque = RenderingGroup.renderUnsorted;
  23275. }
  23276. },
  23277. enumerable: true,
  23278. configurable: true
  23279. });
  23280. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23281. /**
  23282. * Set the alpha test sort comparison function.
  23283. * If null the sub meshes will be render in the order they were created
  23284. */
  23285. set: function (value) {
  23286. this._alphaTestSortCompareFn = value;
  23287. if (value) {
  23288. this._renderAlphaTest = this.renderAlphaTestSorted;
  23289. }
  23290. else {
  23291. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23292. }
  23293. },
  23294. enumerable: true,
  23295. configurable: true
  23296. });
  23297. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23298. /**
  23299. * Set the transparent sort comparison function.
  23300. * If null the sub meshes will be render in the order they were created
  23301. */
  23302. set: function (value) {
  23303. if (value) {
  23304. this._transparentSortCompareFn = value;
  23305. }
  23306. else {
  23307. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23308. }
  23309. this._renderTransparent = this.renderTransparentSorted;
  23310. },
  23311. enumerable: true,
  23312. configurable: true
  23313. });
  23314. /**
  23315. * Render all the sub meshes contained in the group.
  23316. * @param customRenderFunction Used to override the default render behaviour of the group.
  23317. * @returns true if rendered some submeshes.
  23318. */
  23319. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23320. if (customRenderFunction) {
  23321. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23322. return;
  23323. }
  23324. var engine = this._scene.getEngine();
  23325. // Depth only
  23326. if (this._depthOnlySubMeshes.length !== 0) {
  23327. engine.setColorWrite(false);
  23328. this._renderAlphaTest(this._depthOnlySubMeshes);
  23329. engine.setColorWrite(true);
  23330. }
  23331. // Opaque
  23332. if (this._opaqueSubMeshes.length !== 0) {
  23333. this._renderOpaque(this._opaqueSubMeshes);
  23334. }
  23335. // Alpha test
  23336. if (this._alphaTestSubMeshes.length !== 0) {
  23337. this._renderAlphaTest(this._alphaTestSubMeshes);
  23338. }
  23339. var stencilState = engine.getStencilBuffer();
  23340. engine.setStencilBuffer(false);
  23341. // Sprites
  23342. if (renderSprites) {
  23343. this._renderSprites();
  23344. }
  23345. // Particles
  23346. if (renderParticles) {
  23347. this._renderParticles(activeMeshes);
  23348. }
  23349. if (this.onBeforeTransparentRendering) {
  23350. this.onBeforeTransparentRendering();
  23351. }
  23352. // Transparent
  23353. if (this._transparentSubMeshes.length !== 0) {
  23354. this._renderTransparent(this._transparentSubMeshes);
  23355. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23356. }
  23357. // Set back stencil to false in case it changes before the edge renderer.
  23358. engine.setStencilBuffer(false);
  23359. // Edges
  23360. if (this._edgesRenderers.length) {
  23361. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23362. this._edgesRenderers.data[edgesRendererIndex].render();
  23363. }
  23364. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23365. }
  23366. // Restore Stencil state.
  23367. engine.setStencilBuffer(stencilState);
  23368. };
  23369. /**
  23370. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23371. * @param subMeshes The submeshes to render
  23372. */
  23373. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23374. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23375. };
  23376. /**
  23377. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23378. * @param subMeshes The submeshes to render
  23379. */
  23380. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23381. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23382. };
  23383. /**
  23384. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23385. * @param subMeshes The submeshes to render
  23386. */
  23387. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23388. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23389. };
  23390. /**
  23391. * Renders the submeshes in a specified order.
  23392. * @param subMeshes The submeshes to sort before render
  23393. * @param sortCompareFn The comparison function use to sort
  23394. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23395. * @param transparent Specifies to activate blending if true
  23396. */
  23397. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23398. var subIndex = 0;
  23399. var subMesh;
  23400. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23401. for (; subIndex < subMeshes.length; subIndex++) {
  23402. subMesh = subMeshes.data[subIndex];
  23403. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23404. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23405. }
  23406. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23407. if (sortCompareFn) {
  23408. sortedArray.sort(sortCompareFn);
  23409. }
  23410. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23411. subMesh = sortedArray[subIndex];
  23412. if (transparent) {
  23413. var material = subMesh.getMaterial();
  23414. if (material && material.needDepthPrePass) {
  23415. var engine = material.getScene().getEngine();
  23416. engine.setColorWrite(false);
  23417. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23418. subMesh.render(false);
  23419. engine.setColorWrite(true);
  23420. }
  23421. }
  23422. subMesh.render(transparent);
  23423. }
  23424. };
  23425. /**
  23426. * Renders the submeshes in the order they were dispatched (no sort applied).
  23427. * @param subMeshes The submeshes to render
  23428. */
  23429. RenderingGroup.renderUnsorted = function (subMeshes) {
  23430. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23431. var submesh = subMeshes.data[subIndex];
  23432. submesh.render(false);
  23433. }
  23434. };
  23435. /**
  23436. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23437. * are rendered back to front if in the same alpha index.
  23438. *
  23439. * @param a The first submesh
  23440. * @param b The second submesh
  23441. * @returns The result of the comparison
  23442. */
  23443. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23444. // Alpha index first
  23445. if (a._alphaIndex > b._alphaIndex) {
  23446. return 1;
  23447. }
  23448. if (a._alphaIndex < b._alphaIndex) {
  23449. return -1;
  23450. }
  23451. // Then distance to camera
  23452. return RenderingGroup.backToFrontSortCompare(a, b);
  23453. };
  23454. /**
  23455. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23456. * are rendered back to front.
  23457. *
  23458. * @param a The first submesh
  23459. * @param b The second submesh
  23460. * @returns The result of the comparison
  23461. */
  23462. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23463. // Then distance to camera
  23464. if (a._distanceToCamera < b._distanceToCamera) {
  23465. return 1;
  23466. }
  23467. if (a._distanceToCamera > b._distanceToCamera) {
  23468. return -1;
  23469. }
  23470. return 0;
  23471. };
  23472. /**
  23473. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23474. * are rendered front to back (prevent overdraw).
  23475. *
  23476. * @param a The first submesh
  23477. * @param b The second submesh
  23478. * @returns The result of the comparison
  23479. */
  23480. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23481. // Then distance to camera
  23482. if (a._distanceToCamera < b._distanceToCamera) {
  23483. return -1;
  23484. }
  23485. if (a._distanceToCamera > b._distanceToCamera) {
  23486. return 1;
  23487. }
  23488. return 0;
  23489. };
  23490. /**
  23491. * Resets the different lists of submeshes to prepare a new frame.
  23492. */
  23493. RenderingGroup.prototype.prepare = function () {
  23494. this._opaqueSubMeshes.reset();
  23495. this._transparentSubMeshes.reset();
  23496. this._alphaTestSubMeshes.reset();
  23497. this._depthOnlySubMeshes.reset();
  23498. this._particleSystems.reset();
  23499. this._spriteManagers.reset();
  23500. this._edgesRenderers.reset();
  23501. };
  23502. RenderingGroup.prototype.dispose = function () {
  23503. this._opaqueSubMeshes.dispose();
  23504. this._transparentSubMeshes.dispose();
  23505. this._alphaTestSubMeshes.dispose();
  23506. this._depthOnlySubMeshes.dispose();
  23507. this._particleSystems.dispose();
  23508. this._spriteManagers.dispose();
  23509. this._edgesRenderers.dispose();
  23510. };
  23511. /**
  23512. * Inserts the submesh in its correct queue depending on its material.
  23513. * @param subMesh The submesh to dispatch
  23514. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23515. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23516. */
  23517. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23518. // Get mesh and materials if not provided
  23519. if (mesh === undefined) {
  23520. mesh = subMesh.getMesh();
  23521. }
  23522. if (material === undefined) {
  23523. material = subMesh.getMaterial();
  23524. }
  23525. if (material === null || material === undefined) {
  23526. return;
  23527. }
  23528. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23529. this._transparentSubMeshes.push(subMesh);
  23530. }
  23531. else if (material.needAlphaTesting()) { // Alpha test
  23532. if (material.needDepthPrePass) {
  23533. this._depthOnlySubMeshes.push(subMesh);
  23534. }
  23535. this._alphaTestSubMeshes.push(subMesh);
  23536. }
  23537. else {
  23538. if (material.needDepthPrePass) {
  23539. this._depthOnlySubMeshes.push(subMesh);
  23540. }
  23541. this._opaqueSubMeshes.push(subMesh); // Opaque
  23542. }
  23543. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23544. this._edgesRenderers.push(mesh._edgesRenderer);
  23545. }
  23546. };
  23547. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23548. this._spriteManagers.push(spriteManager);
  23549. };
  23550. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23551. this._particleSystems.push(particleSystem);
  23552. };
  23553. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23554. if (this._particleSystems.length === 0) {
  23555. return;
  23556. }
  23557. // Particles
  23558. var activeCamera = this._scene.activeCamera;
  23559. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23560. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23561. var particleSystem = this._particleSystems.data[particleIndex];
  23562. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23563. continue;
  23564. }
  23565. var emitter = particleSystem.emitter;
  23566. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23567. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23568. }
  23569. }
  23570. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23571. };
  23572. RenderingGroup.prototype._renderSprites = function () {
  23573. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23574. return;
  23575. }
  23576. // Sprites
  23577. var activeCamera = this._scene.activeCamera;
  23578. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23579. for (var id = 0; id < this._spriteManagers.length; id++) {
  23580. var spriteManager = this._spriteManagers.data[id];
  23581. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23582. spriteManager.render();
  23583. }
  23584. }
  23585. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23586. };
  23587. return RenderingGroup;
  23588. }());
  23589. BABYLON.RenderingGroup = RenderingGroup;
  23590. })(BABYLON || (BABYLON = {}));
  23591. //# sourceMappingURL=babylon.renderingGroup.js.map
  23592. var BABYLON;
  23593. (function (BABYLON) {
  23594. /**
  23595. * Groups all the scene component constants in one place to ease maintenance.
  23596. * @hidden
  23597. */
  23598. var SceneComponentConstants = /** @class */ (function () {
  23599. function SceneComponentConstants() {
  23600. }
  23601. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23602. SceneComponentConstants.NAME_LAYER = "Layer";
  23603. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23604. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23605. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23606. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23607. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23608. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23609. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23610. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23611. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23612. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23613. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23614. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23615. SceneComponentConstants.NAME_OCTREE = "Octree";
  23616. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  23617. SceneComponentConstants.NAME_AUDIO = "Audio";
  23618. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23619. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23620. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23621. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23622. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23623. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23624. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23625. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23626. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23627. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23628. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  23629. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23630. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23631. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23632. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23633. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23634. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  23635. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  23636. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  23637. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23638. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23639. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23640. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23641. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  23642. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23643. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23644. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23645. return SceneComponentConstants;
  23646. }());
  23647. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23648. /**
  23649. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23650. * @hidden
  23651. */
  23652. var Stage = /** @class */ (function (_super) {
  23653. __extends(Stage, _super);
  23654. /**
  23655. * Hide ctor from the rest of the world.
  23656. * @param items The items to add.
  23657. */
  23658. function Stage(items) {
  23659. return _super.apply(this, items) || this;
  23660. }
  23661. /**
  23662. * Creates a new Stage.
  23663. * @returns A new instance of a Stage
  23664. */
  23665. Stage.Create = function () {
  23666. return Object.create(Stage.prototype);
  23667. };
  23668. /**
  23669. * Registers a step in an ordered way in the targeted stage.
  23670. * @param index Defines the position to register the step in
  23671. * @param component Defines the component attached to the step
  23672. * @param action Defines the action to launch during the step
  23673. */
  23674. Stage.prototype.registerStep = function (index, component, action) {
  23675. var i = 0;
  23676. var maxIndex = Number.MAX_VALUE;
  23677. for (; i < this.length && i < maxIndex; i++) {
  23678. var step = this[i];
  23679. maxIndex = step.index;
  23680. }
  23681. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23682. };
  23683. /**
  23684. * Clears all the steps from the stage.
  23685. */
  23686. Stage.prototype.clear = function () {
  23687. this.length = 0;
  23688. };
  23689. return Stage;
  23690. }(Array));
  23691. BABYLON.Stage = Stage;
  23692. })(BABYLON || (BABYLON = {}));
  23693. //# sourceMappingURL=babylon.sceneComponent.js.map
  23694. var BABYLON;
  23695. (function (BABYLON) {
  23696. /**
  23697. * Base class of the scene acting as a container for the different elements composing a scene.
  23698. * This class is dynamically extended by the different components of the scene increasing
  23699. * flexibility and reducing coupling
  23700. */
  23701. var AbstractScene = /** @class */ (function () {
  23702. function AbstractScene() {
  23703. /**
  23704. * Gets the list of root nodes (ie. nodes with no parent)
  23705. */
  23706. this.rootNodes = new Array();
  23707. /** All of the cameras added to this scene
  23708. * @see http://doc.babylonjs.com/babylon101/cameras
  23709. */
  23710. this.cameras = new Array();
  23711. /**
  23712. * All of the lights added to this scene
  23713. * @see http://doc.babylonjs.com/babylon101/lights
  23714. */
  23715. this.lights = new Array();
  23716. /**
  23717. * All of the (abstract) meshes added to this scene
  23718. */
  23719. this.meshes = new Array();
  23720. /**
  23721. * The list of skeletons added to the scene
  23722. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23723. */
  23724. this.skeletons = new Array();
  23725. /**
  23726. * All of the particle systems added to this scene
  23727. * @see http://doc.babylonjs.com/babylon101/particles
  23728. */
  23729. this.particleSystems = new Array();
  23730. /**
  23731. * Gets a list of Animations associated with the scene
  23732. */
  23733. this.animations = [];
  23734. /**
  23735. * All of the animation groups added to this scene
  23736. * @see http://doc.babylonjs.com/how_to/group
  23737. */
  23738. this.animationGroups = new Array();
  23739. /**
  23740. * All of the multi-materials added to this scene
  23741. * @see http://doc.babylonjs.com/how_to/multi_materials
  23742. */
  23743. this.multiMaterials = new Array();
  23744. /**
  23745. * All of the materials added to this scene
  23746. * @see http://doc.babylonjs.com/babylon101/materials
  23747. */
  23748. this.materials = new Array();
  23749. /**
  23750. * The list of morph target managers added to the scene
  23751. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23752. */
  23753. this.morphTargetManagers = new Array();
  23754. /**
  23755. * The list of geometries used in the scene.
  23756. */
  23757. this.geometries = new Array();
  23758. /**
  23759. * All of the tranform nodes added to this scene
  23760. * @see http://doc.babylonjs.com/how_to/transformnode
  23761. */
  23762. this.transformNodes = new Array();
  23763. /**
  23764. * ActionManagers available on the scene.
  23765. */
  23766. this.actionManagers = new Array();
  23767. /**
  23768. * Textures to keep.
  23769. */
  23770. this.textures = new Array();
  23771. }
  23772. /**
  23773. * Adds a parser in the list of available ones
  23774. * @param name Defines the name of the parser
  23775. * @param parser Defines the parser to add
  23776. */
  23777. AbstractScene.AddParser = function (name, parser) {
  23778. this._BabylonFileParsers[name] = parser;
  23779. };
  23780. /**
  23781. * Gets a general parser from the list of avaialble ones
  23782. * @param name Defines the name of the parser
  23783. * @returns the requested parser or null
  23784. */
  23785. AbstractScene.GetParser = function (name) {
  23786. if (this._BabylonFileParsers[name]) {
  23787. return this._BabylonFileParsers[name];
  23788. }
  23789. return null;
  23790. };
  23791. /**
  23792. * Adds n individual parser in the list of available ones
  23793. * @param name Defines the name of the parser
  23794. * @param parser Defines the parser to add
  23795. */
  23796. AbstractScene.AddIndividualParser = function (name, parser) {
  23797. this._IndividualBabylonFileParsers[name] = parser;
  23798. };
  23799. /**
  23800. * Gets an individual parser from the list of avaialble ones
  23801. * @param name Defines the name of the parser
  23802. * @returns the requested parser or null
  23803. */
  23804. AbstractScene.GetIndividualParser = function (name) {
  23805. if (this._IndividualBabylonFileParsers[name]) {
  23806. return this._IndividualBabylonFileParsers[name];
  23807. }
  23808. return null;
  23809. };
  23810. /**
  23811. * Parser json data and populate both a scene and its associated container object
  23812. * @param jsonData Defines the data to parse
  23813. * @param scene Defines the scene to parse the data for
  23814. * @param container Defines the container attached to the parsing sequence
  23815. * @param rootUrl Defines the root url of the data
  23816. */
  23817. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23818. for (var parserName in this._BabylonFileParsers) {
  23819. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23820. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23821. }
  23822. }
  23823. };
  23824. /**
  23825. * Stores the list of available parsers in the application.
  23826. */
  23827. AbstractScene._BabylonFileParsers = {};
  23828. /**
  23829. * Stores the list of available individual parsers in the application.
  23830. */
  23831. AbstractScene._IndividualBabylonFileParsers = {};
  23832. return AbstractScene;
  23833. }());
  23834. BABYLON.AbstractScene = AbstractScene;
  23835. })(BABYLON || (BABYLON = {}));
  23836. //# sourceMappingURL=babylon.abstractScene.js.map
  23837. var BABYLON;
  23838. (function (BABYLON) {
  23839. /** @hidden */
  23840. var ClickInfo = /** @class */ (function () {
  23841. function ClickInfo() {
  23842. this._singleClick = false;
  23843. this._doubleClick = false;
  23844. this._hasSwiped = false;
  23845. this._ignore = false;
  23846. }
  23847. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23848. get: function () {
  23849. return this._singleClick;
  23850. },
  23851. set: function (b) {
  23852. this._singleClick = b;
  23853. },
  23854. enumerable: true,
  23855. configurable: true
  23856. });
  23857. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23858. get: function () {
  23859. return this._doubleClick;
  23860. },
  23861. set: function (b) {
  23862. this._doubleClick = b;
  23863. },
  23864. enumerable: true,
  23865. configurable: true
  23866. });
  23867. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23868. get: function () {
  23869. return this._hasSwiped;
  23870. },
  23871. set: function (b) {
  23872. this._hasSwiped = b;
  23873. },
  23874. enumerable: true,
  23875. configurable: true
  23876. });
  23877. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23878. get: function () {
  23879. return this._ignore;
  23880. },
  23881. set: function (b) {
  23882. this._ignore = b;
  23883. },
  23884. enumerable: true,
  23885. configurable: true
  23886. });
  23887. return ClickInfo;
  23888. }());
  23889. /**
  23890. * This class is used by the onRenderingGroupObservable
  23891. */
  23892. var RenderingGroupInfo = /** @class */ (function () {
  23893. function RenderingGroupInfo() {
  23894. }
  23895. return RenderingGroupInfo;
  23896. }());
  23897. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23898. /**
  23899. * Represents a scene to be rendered by the engine.
  23900. * @see http://doc.babylonjs.com/features/scene
  23901. */
  23902. var Scene = /** @class */ (function (_super) {
  23903. __extends(Scene, _super);
  23904. /**
  23905. * Creates a new Scene
  23906. * @param engine defines the engine to use to render this scene
  23907. */
  23908. function Scene(engine) {
  23909. var _this = _super.call(this) || this;
  23910. // Members
  23911. /**
  23912. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23913. */
  23914. _this.autoClear = true;
  23915. /**
  23916. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23917. */
  23918. _this.autoClearDepthAndStencil = true;
  23919. /**
  23920. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23921. */
  23922. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23923. /**
  23924. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23925. */
  23926. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23927. _this._forceWireframe = false;
  23928. _this._forcePointsCloud = false;
  23929. /**
  23930. * Gets or sets a boolean indicating if animations are enabled
  23931. */
  23932. _this.animationsEnabled = true;
  23933. _this._animationPropertiesOverride = null;
  23934. /**
  23935. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23936. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23937. */
  23938. _this.useConstantAnimationDeltaTime = false;
  23939. /**
  23940. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23941. * Please note that it requires to run a ray cast through the scene on every frame
  23942. */
  23943. _this.constantlyUpdateMeshUnderPointer = false;
  23944. /**
  23945. * Defines the HTML cursor to use when hovering over interactive elements
  23946. */
  23947. _this.hoverCursor = "pointer";
  23948. /**
  23949. * Defines the HTML default cursor to use (empty by default)
  23950. */
  23951. _this.defaultCursor = "";
  23952. /**
  23953. * This is used to call preventDefault() on pointer down
  23954. * in order to block unwanted artifacts like system double clicks
  23955. */
  23956. _this.preventDefaultOnPointerDown = true;
  23957. // Metadata
  23958. /**
  23959. * Gets or sets user defined metadata
  23960. */
  23961. _this.metadata = null;
  23962. /**
  23963. * Use this array to add regular expressions used to disable offline support for specific urls
  23964. */
  23965. _this.disableOfflineSupportExceptionRules = new Array();
  23966. /**
  23967. * An event triggered when the scene is disposed.
  23968. */
  23969. _this.onDisposeObservable = new BABYLON.Observable();
  23970. _this._onDisposeObserver = null;
  23971. /**
  23972. * An event triggered before rendering the scene (right after animations and physics)
  23973. */
  23974. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23975. _this._onBeforeRenderObserver = null;
  23976. /**
  23977. * An event triggered after rendering the scene
  23978. */
  23979. _this.onAfterRenderObservable = new BABYLON.Observable();
  23980. _this._onAfterRenderObserver = null;
  23981. /**
  23982. * An event triggered before animating the scene
  23983. */
  23984. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23985. /**
  23986. * An event triggered after animations processing
  23987. */
  23988. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23989. /**
  23990. * An event triggered before draw calls are ready to be sent
  23991. */
  23992. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23993. /**
  23994. * An event triggered after draw calls have been sent
  23995. */
  23996. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23997. /**
  23998. * An event triggered when the scene is ready
  23999. */
  24000. _this.onReadyObservable = new BABYLON.Observable();
  24001. /**
  24002. * An event triggered before rendering a camera
  24003. */
  24004. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24005. _this._onBeforeCameraRenderObserver = null;
  24006. /**
  24007. * An event triggered after rendering a camera
  24008. */
  24009. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24010. _this._onAfterCameraRenderObserver = null;
  24011. /**
  24012. * An event triggered when active meshes evaluation is about to start
  24013. */
  24014. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24015. /**
  24016. * An event triggered when active meshes evaluation is done
  24017. */
  24018. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24019. /**
  24020. * An event triggered when particles rendering is about to start
  24021. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24022. */
  24023. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24024. /**
  24025. * An event triggered when particles rendering is done
  24026. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24027. */
  24028. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24029. /**
  24030. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24031. */
  24032. _this.onDataLoadedObservable = new BABYLON.Observable();
  24033. /**
  24034. * An event triggered when a camera is created
  24035. */
  24036. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24037. /**
  24038. * An event triggered when a camera is removed
  24039. */
  24040. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24041. /**
  24042. * An event triggered when a light is created
  24043. */
  24044. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24045. /**
  24046. * An event triggered when a light is removed
  24047. */
  24048. _this.onLightRemovedObservable = new BABYLON.Observable();
  24049. /**
  24050. * An event triggered when a geometry is created
  24051. */
  24052. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24053. /**
  24054. * An event triggered when a geometry is removed
  24055. */
  24056. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24057. /**
  24058. * An event triggered when a transform node is created
  24059. */
  24060. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24061. /**
  24062. * An event triggered when a transform node is removed
  24063. */
  24064. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24065. /**
  24066. * An event triggered when a mesh is created
  24067. */
  24068. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24069. /**
  24070. * An event triggered when a mesh is removed
  24071. */
  24072. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24073. /**
  24074. * An event triggered when render targets are about to be rendered
  24075. * Can happen multiple times per frame.
  24076. */
  24077. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24078. /**
  24079. * An event triggered when render targets were rendered.
  24080. * Can happen multiple times per frame.
  24081. */
  24082. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24083. /**
  24084. * An event triggered before calculating deterministic simulation step
  24085. */
  24086. _this.onBeforeStepObservable = new BABYLON.Observable();
  24087. /**
  24088. * An event triggered after calculating deterministic simulation step
  24089. */
  24090. _this.onAfterStepObservable = new BABYLON.Observable();
  24091. /**
  24092. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24093. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24094. * 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)
  24095. */
  24096. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24097. /**
  24098. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24099. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24100. * 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)
  24101. */
  24102. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24103. /**
  24104. * This Observable will when a mesh has been imported into the scene.
  24105. */
  24106. _this.onMeshImportedObservable = new BABYLON.Observable();
  24107. // Animations
  24108. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24109. /**
  24110. * 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).
  24111. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24112. */
  24113. _this.onPrePointerObservable = new BABYLON.Observable();
  24114. /**
  24115. * Observable event triggered each time an input event is received from the rendering canvas
  24116. */
  24117. _this.onPointerObservable = new BABYLON.Observable();
  24118. _this._meshPickProceed = false;
  24119. _this._currentPickResult = null;
  24120. _this._previousPickResult = null;
  24121. _this._totalPointersPressed = 0;
  24122. _this._doubleClickOccured = false;
  24123. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24124. _this.cameraToUseForPointers = null;
  24125. _this._pointerX = 0;
  24126. _this._pointerY = 0;
  24127. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24128. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24129. _this._startingPointerTime = 0;
  24130. _this._previousStartingPointerTime = 0;
  24131. _this._pointerCaptures = {};
  24132. // Deterministic lockstep
  24133. _this._timeAccumulator = 0;
  24134. _this._currentStepId = 0;
  24135. _this._currentInternalStep = 0;
  24136. // Keyboard
  24137. /**
  24138. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24139. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24140. */
  24141. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24142. /**
  24143. * Observable event triggered each time an keyboard event is received from the hosting window
  24144. */
  24145. _this.onKeyboardObservable = new BABYLON.Observable();
  24146. // Coordinates system
  24147. _this._useRightHandedSystem = false;
  24148. // Fog
  24149. _this._fogEnabled = true;
  24150. _this._fogMode = Scene.FOGMODE_NONE;
  24151. /**
  24152. * Gets or sets the fog color to use
  24153. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24154. */
  24155. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24156. /**
  24157. * Gets or sets the fog density to use
  24158. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24159. */
  24160. _this.fogDensity = 0.1;
  24161. /**
  24162. * Gets or sets the fog start distance to use
  24163. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24164. */
  24165. _this.fogStart = 0;
  24166. /**
  24167. * Gets or sets the fog end distance to use
  24168. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24169. */
  24170. _this.fogEnd = 1000.0;
  24171. // Lights
  24172. _this._shadowsEnabled = true;
  24173. _this._lightsEnabled = true;
  24174. /** All of the active cameras added to this scene. */
  24175. _this.activeCameras = new Array();
  24176. // Textures
  24177. _this._texturesEnabled = true;
  24178. // Particles
  24179. /**
  24180. * Gets or sets a boolean indicating if particles are enabled on this scene
  24181. */
  24182. _this.particlesEnabled = true;
  24183. // Sprites
  24184. /**
  24185. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24186. */
  24187. _this.spritesEnabled = true;
  24188. // Skeletons
  24189. _this._skeletonsEnabled = true;
  24190. // Lens flares
  24191. /**
  24192. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24193. */
  24194. _this.lensFlaresEnabled = true;
  24195. // Collisions
  24196. /**
  24197. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24198. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24199. */
  24200. _this.collisionsEnabled = true;
  24201. /**
  24202. * Defines the gravity applied to this scene (used only for collisions)
  24203. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24204. */
  24205. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24206. // Postprocesses
  24207. /**
  24208. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24209. */
  24210. _this.postProcessesEnabled = true;
  24211. /**
  24212. * The list of postprocesses added to the scene
  24213. */
  24214. _this.postProcesses = new Array();
  24215. // Customs render targets
  24216. /**
  24217. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24218. */
  24219. _this.renderTargetsEnabled = true;
  24220. /**
  24221. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24222. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24223. */
  24224. _this.dumpNextRenderTargets = false;
  24225. /**
  24226. * The list of user defined render targets added to the scene
  24227. */
  24228. _this.customRenderTargets = new Array();
  24229. /**
  24230. * Gets the list of meshes imported to the scene through SceneLoader
  24231. */
  24232. _this.importedMeshesFiles = new Array();
  24233. // Probes
  24234. /**
  24235. * Gets or sets a boolean indicating if probes are enabled on this scene
  24236. */
  24237. _this.probesEnabled = true;
  24238. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24239. // Procedural textures
  24240. /**
  24241. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24242. */
  24243. _this.proceduralTexturesEnabled = true;
  24244. // Performance counters
  24245. _this._totalVertices = new BABYLON.PerfCounter();
  24246. /** @hidden */
  24247. _this._activeIndices = new BABYLON.PerfCounter();
  24248. /** @hidden */
  24249. _this._activeParticles = new BABYLON.PerfCounter();
  24250. /** @hidden */
  24251. _this._activeBones = new BABYLON.PerfCounter();
  24252. _this._animationTime = 0;
  24253. /**
  24254. * Gets or sets a general scale for animation speed
  24255. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24256. */
  24257. _this.animationTimeScale = 1;
  24258. _this._renderId = 0;
  24259. _this._frameId = 0;
  24260. _this._executeWhenReadyTimeoutId = -1;
  24261. _this._intermediateRendering = false;
  24262. _this._viewUpdateFlag = -1;
  24263. _this._projectionUpdateFlag = -1;
  24264. _this._alternateViewUpdateFlag = -1;
  24265. _this._alternateProjectionUpdateFlag = -1;
  24266. /** @hidden */
  24267. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24268. _this._activeRequests = new Array();
  24269. _this._pendingData = new Array();
  24270. _this._isDisposed = false;
  24271. /**
  24272. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24273. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24274. */
  24275. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24276. _this._activeMeshes = new BABYLON.SmartArray(256);
  24277. _this._processedMaterials = new BABYLON.SmartArray(256);
  24278. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24279. /** @hidden */
  24280. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24281. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24282. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24283. /** @hidden */
  24284. _this._activeAnimatables = new Array();
  24285. _this._transformMatrix = BABYLON.Matrix.Zero();
  24286. _this._useAlternateCameraConfiguration = false;
  24287. _this._alternateRendering = false;
  24288. /**
  24289. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24290. * This is useful if there are more lights that the maximum simulteanous authorized
  24291. */
  24292. _this.requireLightSorting = false;
  24293. /**
  24294. * @hidden
  24295. * Backing store of defined scene components.
  24296. */
  24297. _this._components = [];
  24298. /**
  24299. * @hidden
  24300. * Backing store of defined scene components.
  24301. */
  24302. _this._serializableComponents = [];
  24303. /**
  24304. * List of components to register on the next registration step.
  24305. */
  24306. _this._transientComponents = [];
  24307. /**
  24308. * @hidden
  24309. * Defines the actions happening before camera updates.
  24310. */
  24311. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24312. /**
  24313. * @hidden
  24314. * Defines the actions happening before clear the canvas.
  24315. */
  24316. _this._beforeClearStage = BABYLON.Stage.Create();
  24317. /**
  24318. * @hidden
  24319. * Defines the actions when collecting render targets for the frame.
  24320. */
  24321. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24322. /**
  24323. * @hidden
  24324. * Defines the actions happening for one camera in the frame.
  24325. */
  24326. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24327. /**
  24328. * @hidden
  24329. * Defines the actions happening during the per mesh ready checks.
  24330. */
  24331. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24332. /**
  24333. * @hidden
  24334. * Defines the actions happening before evaluate active mesh checks.
  24335. */
  24336. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24337. /**
  24338. * @hidden
  24339. * Defines the actions happening during the evaluate sub mesh checks.
  24340. */
  24341. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24342. /**
  24343. * @hidden
  24344. * Defines the actions happening during the active mesh stage.
  24345. */
  24346. _this._activeMeshStage = BABYLON.Stage.Create();
  24347. /**
  24348. * @hidden
  24349. * Defines the actions happening during the per camera render target step.
  24350. */
  24351. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24352. /**
  24353. * @hidden
  24354. * Defines the actions happening just before the active camera is drawing.
  24355. */
  24356. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24357. /**
  24358. * @hidden
  24359. * Defines the actions happening just before a rendering group is drawing.
  24360. */
  24361. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24362. /**
  24363. * @hidden
  24364. * Defines the actions happening just before a mesh is drawing.
  24365. */
  24366. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24367. /**
  24368. * @hidden
  24369. * Defines the actions happening just after a mesh has been drawn.
  24370. */
  24371. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24372. /**
  24373. * @hidden
  24374. * Defines the actions happening just after a rendering group has been drawn.
  24375. */
  24376. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24377. /**
  24378. * @hidden
  24379. * Defines the actions happening just after the active camera has been drawn.
  24380. */
  24381. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24382. /**
  24383. * @hidden
  24384. * Defines the actions happening just after rendering all cameras and computing intersections.
  24385. */
  24386. _this._afterRenderStage = BABYLON.Stage.Create();
  24387. /**
  24388. * @hidden
  24389. * Defines the actions happening when a pointer move event happens.
  24390. */
  24391. _this._pointerMoveStage = BABYLON.Stage.Create();
  24392. /**
  24393. * @hidden
  24394. * Defines the actions happening when a pointer down event happens.
  24395. */
  24396. _this._pointerDownStage = BABYLON.Stage.Create();
  24397. /**
  24398. * @hidden
  24399. * Defines the actions happening when a pointer up event happens.
  24400. */
  24401. _this._pointerUpStage = BABYLON.Stage.Create();
  24402. _this._defaultMeshCandidates = {
  24403. data: [],
  24404. length: 0
  24405. };
  24406. _this._defaultSubMeshCandidates = {
  24407. data: [],
  24408. length: 0
  24409. };
  24410. _this._activeMeshesFrozen = false;
  24411. /** @hidden */
  24412. _this._allowPostProcessClearColor = true;
  24413. /**
  24414. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  24415. */
  24416. _this.getDeterministicFrameTime = function () {
  24417. return 1000.0 / 60.0; // frame time in ms
  24418. };
  24419. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24420. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24421. _this.blockMaterialDirtyMechanism = false;
  24422. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24423. _this._engine.scenes.push(_this);
  24424. _this._uid = null;
  24425. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24426. if (BABYLON.PostProcessManager) {
  24427. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24428. }
  24429. if (BABYLON.Tools.IsWindowObjectExist()) {
  24430. _this.attachControl();
  24431. }
  24432. //collision coordinator initialization. For now legacy per default.
  24433. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24434. // Uniform Buffer
  24435. _this._createUbo();
  24436. // Default Image processing definition
  24437. if (BABYLON.ImageProcessingConfiguration) {
  24438. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24439. }
  24440. _this.setDefaultCandidateProviders();
  24441. return _this;
  24442. }
  24443. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24444. /**
  24445. * Texture used in all pbr material as the reflection texture.
  24446. * As in the majority of the scene they are the same (exception for multi room and so on),
  24447. * this is easier to reference from here than from all the materials.
  24448. */
  24449. get: function () {
  24450. return this._environmentTexture;
  24451. },
  24452. /**
  24453. * Texture used in all pbr material as the reflection texture.
  24454. * As in the majority of the scene they are the same (exception for multi room and so on),
  24455. * this is easier to set here than in all the materials.
  24456. */
  24457. set: function (value) {
  24458. if (this._environmentTexture === value) {
  24459. return;
  24460. }
  24461. this._environmentTexture = value;
  24462. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24463. },
  24464. enumerable: true,
  24465. configurable: true
  24466. });
  24467. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24468. /**
  24469. * Default image processing configuration used either in the rendering
  24470. * Forward main pass or through the imageProcessingPostProcess if present.
  24471. * As in the majority of the scene they are the same (exception for multi camera),
  24472. * this is easier to reference from here than from all the materials and post process.
  24473. *
  24474. * No setter as we it is a shared configuration, you can set the values instead.
  24475. */
  24476. get: function () {
  24477. return this._imageProcessingConfiguration;
  24478. },
  24479. enumerable: true,
  24480. configurable: true
  24481. });
  24482. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24483. get: function () {
  24484. return this._forceWireframe;
  24485. },
  24486. /**
  24487. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24488. */
  24489. set: function (value) {
  24490. if (this._forceWireframe === value) {
  24491. return;
  24492. }
  24493. this._forceWireframe = value;
  24494. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24495. },
  24496. enumerable: true,
  24497. configurable: true
  24498. });
  24499. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24500. get: function () {
  24501. return this._forcePointsCloud;
  24502. },
  24503. /**
  24504. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24505. */
  24506. set: function (value) {
  24507. if (this._forcePointsCloud === value) {
  24508. return;
  24509. }
  24510. this._forcePointsCloud = value;
  24511. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24512. },
  24513. enumerable: true,
  24514. configurable: true
  24515. });
  24516. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24517. /**
  24518. * Gets or sets the animation properties override
  24519. */
  24520. get: function () {
  24521. return this._animationPropertiesOverride;
  24522. },
  24523. set: function (value) {
  24524. this._animationPropertiesOverride = value;
  24525. },
  24526. enumerable: true,
  24527. configurable: true
  24528. });
  24529. Object.defineProperty(Scene.prototype, "onDispose", {
  24530. /** Sets a function to be executed when this scene is disposed. */
  24531. set: function (callback) {
  24532. if (this._onDisposeObserver) {
  24533. this.onDisposeObservable.remove(this._onDisposeObserver);
  24534. }
  24535. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24536. },
  24537. enumerable: true,
  24538. configurable: true
  24539. });
  24540. Object.defineProperty(Scene.prototype, "beforeRender", {
  24541. /** Sets a function to be executed before rendering this scene */
  24542. set: function (callback) {
  24543. if (this._onBeforeRenderObserver) {
  24544. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24545. }
  24546. if (callback) {
  24547. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24548. }
  24549. },
  24550. enumerable: true,
  24551. configurable: true
  24552. });
  24553. Object.defineProperty(Scene.prototype, "afterRender", {
  24554. /** Sets a function to be executed after rendering this scene */
  24555. set: function (callback) {
  24556. if (this._onAfterRenderObserver) {
  24557. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24558. }
  24559. if (callback) {
  24560. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24561. }
  24562. },
  24563. enumerable: true,
  24564. configurable: true
  24565. });
  24566. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24567. /** Sets a function to be executed before rendering a camera*/
  24568. set: function (callback) {
  24569. if (this._onBeforeCameraRenderObserver) {
  24570. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24571. }
  24572. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24573. },
  24574. enumerable: true,
  24575. configurable: true
  24576. });
  24577. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24578. /** Sets a function to be executed after rendering a camera*/
  24579. set: function (callback) {
  24580. if (this._onAfterCameraRenderObserver) {
  24581. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24582. }
  24583. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24584. },
  24585. enumerable: true,
  24586. configurable: true
  24587. });
  24588. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24589. /**
  24590. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24591. */
  24592. get: function () {
  24593. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24594. },
  24595. enumerable: true,
  24596. configurable: true
  24597. });
  24598. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24599. get: function () {
  24600. return this._useRightHandedSystem;
  24601. },
  24602. /**
  24603. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24604. */
  24605. set: function (value) {
  24606. if (this._useRightHandedSystem === value) {
  24607. return;
  24608. }
  24609. this._useRightHandedSystem = value;
  24610. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. /**
  24616. * Sets the step Id used by deterministic lock step
  24617. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24618. * @param newStepId defines the step Id
  24619. */
  24620. Scene.prototype.setStepId = function (newStepId) {
  24621. this._currentStepId = newStepId;
  24622. };
  24623. ;
  24624. /**
  24625. * Gets the step Id used by deterministic lock step
  24626. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24627. * @returns the step Id
  24628. */
  24629. Scene.prototype.getStepId = function () {
  24630. return this._currentStepId;
  24631. };
  24632. ;
  24633. /**
  24634. * Gets the internal step used by deterministic lock step
  24635. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24636. * @returns the internal step
  24637. */
  24638. Scene.prototype.getInternalStep = function () {
  24639. return this._currentInternalStep;
  24640. };
  24641. ;
  24642. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24643. get: function () {
  24644. return this._fogEnabled;
  24645. },
  24646. /**
  24647. * Gets or sets a boolean indicating if fog is enabled on this scene
  24648. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24649. */
  24650. set: function (value) {
  24651. if (this._fogEnabled === value) {
  24652. return;
  24653. }
  24654. this._fogEnabled = value;
  24655. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24656. },
  24657. enumerable: true,
  24658. configurable: true
  24659. });
  24660. Object.defineProperty(Scene.prototype, "fogMode", {
  24661. get: function () {
  24662. return this._fogMode;
  24663. },
  24664. /**
  24665. * Gets or sets the fog mode to use
  24666. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24667. */
  24668. set: function (value) {
  24669. if (this._fogMode === value) {
  24670. return;
  24671. }
  24672. this._fogMode = value;
  24673. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24674. },
  24675. enumerable: true,
  24676. configurable: true
  24677. });
  24678. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24679. get: function () {
  24680. return this._shadowsEnabled;
  24681. },
  24682. /**
  24683. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24684. */
  24685. set: function (value) {
  24686. if (this._shadowsEnabled === value) {
  24687. return;
  24688. }
  24689. this._shadowsEnabled = value;
  24690. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24691. },
  24692. enumerable: true,
  24693. configurable: true
  24694. });
  24695. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24696. get: function () {
  24697. return this._lightsEnabled;
  24698. },
  24699. /**
  24700. * Gets or sets a boolean indicating if lights are enabled on this scene
  24701. */
  24702. set: function (value) {
  24703. if (this._lightsEnabled === value) {
  24704. return;
  24705. }
  24706. this._lightsEnabled = value;
  24707. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24708. },
  24709. enumerable: true,
  24710. configurable: true
  24711. });
  24712. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24713. /** The default material used on meshes when no material is affected */
  24714. get: function () {
  24715. if (!this._defaultMaterial) {
  24716. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24717. }
  24718. return this._defaultMaterial;
  24719. },
  24720. /** The default material used on meshes when no material is affected */
  24721. set: function (value) {
  24722. this._defaultMaterial = value;
  24723. },
  24724. enumerable: true,
  24725. configurable: true
  24726. });
  24727. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24728. get: function () {
  24729. return this._texturesEnabled;
  24730. },
  24731. /**
  24732. * Gets or sets a boolean indicating if textures are enabled on this scene
  24733. */
  24734. set: function (value) {
  24735. if (this._texturesEnabled === value) {
  24736. return;
  24737. }
  24738. this._texturesEnabled = value;
  24739. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24740. },
  24741. enumerable: true,
  24742. configurable: true
  24743. });
  24744. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24745. get: function () {
  24746. return this._skeletonsEnabled;
  24747. },
  24748. /**
  24749. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24750. */
  24751. set: function (value) {
  24752. if (this._skeletonsEnabled === value) {
  24753. return;
  24754. }
  24755. this._skeletonsEnabled = value;
  24756. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24757. },
  24758. enumerable: true,
  24759. configurable: true
  24760. });
  24761. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24762. /** @hidden */
  24763. get: function () {
  24764. return this._alternateRendering;
  24765. },
  24766. enumerable: true,
  24767. configurable: true
  24768. });
  24769. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24770. /**
  24771. * Gets the list of frustum planes (built from the active camera)
  24772. */
  24773. get: function () {
  24774. return this._frustumPlanes;
  24775. },
  24776. enumerable: true,
  24777. configurable: true
  24778. });
  24779. /**
  24780. * Registers the transient components if needed.
  24781. */
  24782. Scene.prototype._registerTransientComponents = function () {
  24783. // Register components that have been associated lately to the scene.
  24784. if (this._transientComponents.length > 0) {
  24785. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24786. var component = _a[_i];
  24787. component.register();
  24788. }
  24789. this._transientComponents = [];
  24790. }
  24791. };
  24792. /**
  24793. * @hidden
  24794. * Add a component to the scene.
  24795. * Note that the ccomponent could be registered on th next frame if this is called after
  24796. * the register component stage.
  24797. * @param component Defines the component to add to the scene
  24798. */
  24799. Scene.prototype._addComponent = function (component) {
  24800. this._components.push(component);
  24801. this._transientComponents.push(component);
  24802. var serializableComponent = component;
  24803. if (serializableComponent.addFromContainer) {
  24804. this._serializableComponents.push(serializableComponent);
  24805. }
  24806. };
  24807. /**
  24808. * @hidden
  24809. * Gets a component from the scene.
  24810. * @param name defines the name of the component to retrieve
  24811. * @returns the component or null if not present
  24812. */
  24813. Scene.prototype._getComponent = function (name) {
  24814. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24815. var component = _a[_i];
  24816. if (component.name === name) {
  24817. return component;
  24818. }
  24819. }
  24820. return null;
  24821. };
  24822. /**
  24823. * @hidden
  24824. */
  24825. Scene.prototype._getDefaultMeshCandidates = function () {
  24826. this._defaultMeshCandidates.data = this.meshes;
  24827. this._defaultMeshCandidates.length = this.meshes.length;
  24828. return this._defaultMeshCandidates;
  24829. };
  24830. /**
  24831. * @hidden
  24832. */
  24833. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  24834. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  24835. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  24836. return this._defaultSubMeshCandidates;
  24837. };
  24838. /**
  24839. * Sets the default candidate providers for the scene.
  24840. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  24841. * and getCollidingSubMeshCandidates to their default function
  24842. */
  24843. Scene.prototype.setDefaultCandidateProviders = function () {
  24844. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  24845. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24846. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24847. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24848. };
  24849. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24850. /**
  24851. * Gets a boolean indicating if collisions are processed on a web worker
  24852. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24853. */
  24854. get: function () {
  24855. return this._workerCollisions;
  24856. },
  24857. set: function (enabled) {
  24858. if (!BABYLON.CollisionCoordinatorLegacy) {
  24859. return;
  24860. }
  24861. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24862. this._workerCollisions = enabled;
  24863. if (this.collisionCoordinator) {
  24864. this.collisionCoordinator.destroy();
  24865. }
  24866. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24867. this.collisionCoordinator.init(this);
  24868. },
  24869. enumerable: true,
  24870. configurable: true
  24871. });
  24872. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24873. /**
  24874. * Gets the mesh that is currently under the pointer
  24875. */
  24876. get: function () {
  24877. return this._pointerOverMesh;
  24878. },
  24879. enumerable: true,
  24880. configurable: true
  24881. });
  24882. Object.defineProperty(Scene.prototype, "pointerX", {
  24883. /**
  24884. * Gets the current on-screen X position of the pointer
  24885. */
  24886. get: function () {
  24887. return this._pointerX;
  24888. },
  24889. enumerable: true,
  24890. configurable: true
  24891. });
  24892. Object.defineProperty(Scene.prototype, "pointerY", {
  24893. /**
  24894. * Gets the current on-screen Y position of the pointer
  24895. */
  24896. get: function () {
  24897. return this._pointerY;
  24898. },
  24899. enumerable: true,
  24900. configurable: true
  24901. });
  24902. /**
  24903. * Gets the cached material (ie. the latest rendered one)
  24904. * @returns the cached material
  24905. */
  24906. Scene.prototype.getCachedMaterial = function () {
  24907. return this._cachedMaterial;
  24908. };
  24909. /**
  24910. * Gets the cached effect (ie. the latest rendered one)
  24911. * @returns the cached effect
  24912. */
  24913. Scene.prototype.getCachedEffect = function () {
  24914. return this._cachedEffect;
  24915. };
  24916. /**
  24917. * Gets the cached visibility state (ie. the latest rendered one)
  24918. * @returns the cached visibility state
  24919. */
  24920. Scene.prototype.getCachedVisibility = function () {
  24921. return this._cachedVisibility;
  24922. };
  24923. /**
  24924. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24925. * @param material defines the current material
  24926. * @param effect defines the current effect
  24927. * @param visibility defines the current visibility state
  24928. * @returns true if one parameter is not cached
  24929. */
  24930. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24931. if (visibility === void 0) { visibility = 1; }
  24932. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24933. };
  24934. /**
  24935. * Gets the engine associated with the scene
  24936. * @returns an Engine
  24937. */
  24938. Scene.prototype.getEngine = function () {
  24939. return this._engine;
  24940. };
  24941. /**
  24942. * Gets the total number of vertices rendered per frame
  24943. * @returns the total number of vertices rendered per frame
  24944. */
  24945. Scene.prototype.getTotalVertices = function () {
  24946. return this._totalVertices.current;
  24947. };
  24948. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24949. /**
  24950. * Gets the performance counter for total vertices
  24951. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24952. */
  24953. get: function () {
  24954. return this._totalVertices;
  24955. },
  24956. enumerable: true,
  24957. configurable: true
  24958. });
  24959. /**
  24960. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24961. * @returns the total number of active indices rendered per frame
  24962. */
  24963. Scene.prototype.getActiveIndices = function () {
  24964. return this._activeIndices.current;
  24965. };
  24966. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24967. /**
  24968. * Gets the performance counter for active indices
  24969. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24970. */
  24971. get: function () {
  24972. return this._activeIndices;
  24973. },
  24974. enumerable: true,
  24975. configurable: true
  24976. });
  24977. /**
  24978. * Gets the total number of active particles rendered per frame
  24979. * @returns the total number of active particles rendered per frame
  24980. */
  24981. Scene.prototype.getActiveParticles = function () {
  24982. return this._activeParticles.current;
  24983. };
  24984. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24985. /**
  24986. * Gets the performance counter for active particles
  24987. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24988. */
  24989. get: function () {
  24990. return this._activeParticles;
  24991. },
  24992. enumerable: true,
  24993. configurable: true
  24994. });
  24995. /**
  24996. * Gets the total number of active bones rendered per frame
  24997. * @returns the total number of active bones rendered per frame
  24998. */
  24999. Scene.prototype.getActiveBones = function () {
  25000. return this._activeBones.current;
  25001. };
  25002. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25003. /**
  25004. * Gets the performance counter for active bones
  25005. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25006. */
  25007. get: function () {
  25008. return this._activeBones;
  25009. },
  25010. enumerable: true,
  25011. configurable: true
  25012. });
  25013. /** @hidden */
  25014. Scene.prototype.getInterFramePerfCounter = function () {
  25015. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25016. return 0;
  25017. };
  25018. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25019. /** @hidden */
  25020. get: function () {
  25021. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25022. return null;
  25023. },
  25024. enumerable: true,
  25025. configurable: true
  25026. });
  25027. /** @hidden */
  25028. Scene.prototype.getLastFrameDuration = function () {
  25029. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25030. return 0;
  25031. };
  25032. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25033. /** @hidden */
  25034. get: function () {
  25035. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25036. return null;
  25037. },
  25038. enumerable: true,
  25039. configurable: true
  25040. });
  25041. /** @hidden */
  25042. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25043. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25044. return 0;
  25045. };
  25046. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25047. /** @hidden */
  25048. get: function () {
  25049. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25050. return null;
  25051. },
  25052. enumerable: true,
  25053. configurable: true
  25054. });
  25055. /**
  25056. * Gets the array of active meshes
  25057. * @returns an array of AbstractMesh
  25058. */
  25059. Scene.prototype.getActiveMeshes = function () {
  25060. return this._activeMeshes;
  25061. };
  25062. /** @hidden */
  25063. Scene.prototype.getRenderTargetsDuration = function () {
  25064. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25065. return 0;
  25066. };
  25067. /** @hidden */
  25068. Scene.prototype.getRenderDuration = function () {
  25069. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25070. return 0;
  25071. };
  25072. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25073. /** @hidden */
  25074. get: function () {
  25075. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25076. return null;
  25077. },
  25078. enumerable: true,
  25079. configurable: true
  25080. });
  25081. /** @hidden */
  25082. Scene.prototype.getParticlesDuration = function () {
  25083. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25084. return 0;
  25085. };
  25086. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25087. /** @hidden */
  25088. get: function () {
  25089. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25090. return null;
  25091. },
  25092. enumerable: true,
  25093. configurable: true
  25094. });
  25095. /** @hidden */
  25096. Scene.prototype.getSpritesDuration = function () {
  25097. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25098. return 0;
  25099. };
  25100. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25101. /** @hidden */
  25102. get: function () {
  25103. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25104. return null;
  25105. },
  25106. enumerable: true,
  25107. configurable: true
  25108. });
  25109. /**
  25110. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25111. * @returns a number
  25112. */
  25113. Scene.prototype.getAnimationRatio = function () {
  25114. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25115. };
  25116. /**
  25117. * Gets an unique Id for the current render phase
  25118. * @returns a number
  25119. */
  25120. Scene.prototype.getRenderId = function () {
  25121. return this._renderId;
  25122. };
  25123. /**
  25124. * Gets an unique Id for the current frame
  25125. * @returns a number
  25126. */
  25127. Scene.prototype.getFrameId = function () {
  25128. return this._frameId;
  25129. };
  25130. /** Call this function if you want to manually increment the render Id*/
  25131. Scene.prototype.incrementRenderId = function () {
  25132. this._renderId++;
  25133. };
  25134. Scene.prototype._updatePointerPosition = function (evt) {
  25135. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25136. if (!canvasRect) {
  25137. return;
  25138. }
  25139. this._pointerX = evt.clientX - canvasRect.left;
  25140. this._pointerY = evt.clientY - canvasRect.top;
  25141. this._unTranslatedPointerX = this._pointerX;
  25142. this._unTranslatedPointerY = this._pointerY;
  25143. };
  25144. Scene.prototype._createUbo = function () {
  25145. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25146. this._sceneUbo.addUniform("viewProjection", 16);
  25147. this._sceneUbo.addUniform("view", 16);
  25148. };
  25149. Scene.prototype._createAlternateUbo = function () {
  25150. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25151. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25152. this._alternateSceneUbo.addUniform("view", 16);
  25153. };
  25154. // Pointers handling
  25155. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25156. if (pointerInfo.pickInfo) {
  25157. if (!pointerInfo.pickInfo.ray) {
  25158. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25159. }
  25160. }
  25161. };
  25162. /**
  25163. * Use this method to simulate a pointer move on a mesh
  25164. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25165. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25166. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25167. * @returns the current scene
  25168. */
  25169. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25170. var evt = new PointerEvent("pointermove", pointerEventInit);
  25171. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25172. return this;
  25173. }
  25174. return this._processPointerMove(pickResult, evt);
  25175. };
  25176. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25177. var canvas = this._engine.getRenderingCanvas();
  25178. if (!canvas) {
  25179. return this;
  25180. }
  25181. // Restore pointer
  25182. canvas.style.cursor = this.defaultCursor;
  25183. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25184. if (isMeshPicked) {
  25185. this.setPointerOverMesh(pickResult.pickedMesh);
  25186. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25187. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25188. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25189. }
  25190. else {
  25191. canvas.style.cursor = this.hoverCursor;
  25192. }
  25193. }
  25194. }
  25195. else {
  25196. this.setPointerOverMesh(null);
  25197. }
  25198. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25199. var step = _a[_i];
  25200. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25201. }
  25202. if (pickResult) {
  25203. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25204. if (this.onPointerMove) {
  25205. this.onPointerMove(evt, pickResult, type);
  25206. }
  25207. if (this.onPointerObservable.hasObservers()) {
  25208. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25209. this._setRayOnPointerInfo(pi);
  25210. this.onPointerObservable.notifyObservers(pi, type);
  25211. }
  25212. }
  25213. return this;
  25214. };
  25215. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25216. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25217. if (pickResult) {
  25218. pi.ray = pickResult.ray;
  25219. }
  25220. this.onPrePointerObservable.notifyObservers(pi, type);
  25221. if (pi.skipOnPointerObservable) {
  25222. return true;
  25223. }
  25224. else {
  25225. return false;
  25226. }
  25227. };
  25228. /**
  25229. * Use this method to simulate a pointer down on a mesh
  25230. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25231. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25232. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25233. * @returns the current scene
  25234. */
  25235. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25236. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25237. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25238. return this;
  25239. }
  25240. return this._processPointerDown(pickResult, evt);
  25241. };
  25242. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25243. var _this = this;
  25244. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25245. this._pickedDownMesh = pickResult.pickedMesh;
  25246. var actionManager = pickResult.pickedMesh.actionManager;
  25247. if (actionManager) {
  25248. if (actionManager.hasPickTriggers) {
  25249. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25250. switch (evt.button) {
  25251. case 0:
  25252. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25253. break;
  25254. case 1:
  25255. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25256. break;
  25257. case 2:
  25258. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25259. break;
  25260. }
  25261. }
  25262. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25263. window.setTimeout(function () {
  25264. 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);
  25265. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25266. if (_this._totalPointersPressed !== 0 &&
  25267. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25268. !_this._isPointerSwiping()) {
  25269. _this._startingPointerTime = 0;
  25270. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25271. }
  25272. }
  25273. }, Scene.LongPressDelay);
  25274. }
  25275. }
  25276. }
  25277. else {
  25278. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25279. var step = _a[_i];
  25280. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25281. }
  25282. }
  25283. if (pickResult) {
  25284. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25285. if (this.onPointerDown) {
  25286. this.onPointerDown(evt, pickResult, type);
  25287. }
  25288. if (this.onPointerObservable.hasObservers()) {
  25289. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25290. this._setRayOnPointerInfo(pi);
  25291. this.onPointerObservable.notifyObservers(pi, type);
  25292. }
  25293. }
  25294. return this;
  25295. };
  25296. /**
  25297. * Use this method to simulate a pointer up on a mesh
  25298. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25299. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25300. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25301. * @returns the current scene
  25302. */
  25303. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25304. var evt = new PointerEvent("pointerup", pointerEventInit);
  25305. var clickInfo = new ClickInfo();
  25306. clickInfo.singleClick = true;
  25307. clickInfo.ignore = true;
  25308. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25309. return this;
  25310. }
  25311. return this._processPointerUp(pickResult, evt, clickInfo);
  25312. };
  25313. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25314. if (pickResult && pickResult && pickResult.pickedMesh) {
  25315. this._pickedUpMesh = pickResult.pickedMesh;
  25316. if (this._pickedDownMesh === this._pickedUpMesh) {
  25317. if (this.onPointerPick) {
  25318. this.onPointerPick(evt, pickResult);
  25319. }
  25320. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25321. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25322. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25323. this._setRayOnPointerInfo(pi);
  25324. this.onPointerObservable.notifyObservers(pi, type_1);
  25325. }
  25326. }
  25327. if (pickResult.pickedMesh.actionManager) {
  25328. if (clickInfo.ignore) {
  25329. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25330. }
  25331. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25332. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25333. }
  25334. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25335. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25336. }
  25337. }
  25338. }
  25339. else {
  25340. if (!clickInfo.ignore) {
  25341. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25342. var step = _a[_i];
  25343. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25344. }
  25345. }
  25346. }
  25347. if (this._pickedDownMesh &&
  25348. this._pickedDownMesh.actionManager &&
  25349. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25350. this._pickedDownMesh !== this._pickedUpMesh) {
  25351. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25352. }
  25353. var type = BABYLON.PointerEventTypes.POINTERUP;
  25354. if (this.onPointerObservable.hasObservers()) {
  25355. if (!clickInfo.ignore) {
  25356. if (!clickInfo.hasSwiped) {
  25357. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25358. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25359. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25360. this._setRayOnPointerInfo(pi);
  25361. this.onPointerObservable.notifyObservers(pi, type_2);
  25362. }
  25363. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25364. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25365. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25366. this._setRayOnPointerInfo(pi);
  25367. this.onPointerObservable.notifyObservers(pi, type_3);
  25368. }
  25369. }
  25370. }
  25371. else {
  25372. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25373. this._setRayOnPointerInfo(pi);
  25374. this.onPointerObservable.notifyObservers(pi, type);
  25375. }
  25376. }
  25377. if (this.onPointerUp) {
  25378. this.onPointerUp(evt, pickResult, type);
  25379. }
  25380. return this;
  25381. };
  25382. /**
  25383. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25384. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25385. * @returns true if the pointer was captured
  25386. */
  25387. Scene.prototype.isPointerCaptured = function (pointerId) {
  25388. if (pointerId === void 0) { pointerId = 0; }
  25389. return this._pointerCaptures[pointerId];
  25390. };
  25391. /** @hidden */
  25392. Scene.prototype._isPointerSwiping = function () {
  25393. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25394. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25395. };
  25396. /**
  25397. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25398. * @param attachUp defines if you want to attach events to pointerup
  25399. * @param attachDown defines if you want to attach events to pointerdown
  25400. * @param attachMove defines if you want to attach events to pointermove
  25401. */
  25402. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25403. var _this = this;
  25404. if (attachUp === void 0) { attachUp = true; }
  25405. if (attachDown === void 0) { attachDown = true; }
  25406. if (attachMove === void 0) { attachMove = true; }
  25407. this._initActionManager = function (act, clickInfo) {
  25408. if (!_this._meshPickProceed) {
  25409. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25410. _this._currentPickResult = pickResult;
  25411. if (pickResult) {
  25412. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25413. }
  25414. _this._meshPickProceed = true;
  25415. }
  25416. return act;
  25417. };
  25418. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25419. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25420. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25421. btn !== _this._previousButtonPressed) {
  25422. _this._doubleClickOccured = false;
  25423. clickInfo.singleClick = true;
  25424. clickInfo.ignore = false;
  25425. cb(clickInfo, _this._currentPickResult);
  25426. }
  25427. };
  25428. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25429. var clickInfo = new ClickInfo();
  25430. _this._currentPickResult = null;
  25431. var act = null;
  25432. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25433. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25434. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25435. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25436. act = _this._initActionManager(act, clickInfo);
  25437. if (act)
  25438. checkPicking = act.hasPickTriggers;
  25439. }
  25440. if (checkPicking) {
  25441. var btn = evt.button;
  25442. clickInfo.hasSwiped = _this._isPointerSwiping();
  25443. if (!clickInfo.hasSwiped) {
  25444. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25445. if (!checkSingleClickImmediately) {
  25446. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25447. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25448. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25449. act = _this._initActionManager(act, clickInfo);
  25450. if (act)
  25451. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25452. }
  25453. }
  25454. if (checkSingleClickImmediately) {
  25455. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25456. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25457. btn !== _this._previousButtonPressed) {
  25458. clickInfo.singleClick = true;
  25459. cb(clickInfo, _this._currentPickResult);
  25460. }
  25461. }
  25462. // at least one double click is required to be check and exclusive double click is enabled
  25463. else {
  25464. // wait that no double click has been raised during the double click delay
  25465. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25466. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25467. }
  25468. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25469. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25470. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25471. act = _this._initActionManager(act, clickInfo);
  25472. if (act)
  25473. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25474. }
  25475. if (checkDoubleClick) {
  25476. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25477. if (btn === _this._previousButtonPressed &&
  25478. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25479. !_this._doubleClickOccured) {
  25480. // pointer has not moved for 2 clicks, it's a double click
  25481. if (!clickInfo.hasSwiped &&
  25482. !_this._isPointerSwiping()) {
  25483. _this._previousStartingPointerTime = 0;
  25484. _this._doubleClickOccured = true;
  25485. clickInfo.doubleClick = true;
  25486. clickInfo.ignore = false;
  25487. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25488. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25489. }
  25490. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25491. cb(clickInfo, _this._currentPickResult);
  25492. }
  25493. // if the two successive clicks are too far, it's just two simple clicks
  25494. else {
  25495. _this._doubleClickOccured = false;
  25496. _this._previousStartingPointerTime = _this._startingPointerTime;
  25497. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25498. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25499. _this._previousButtonPressed = btn;
  25500. if (Scene.ExclusiveDoubleClickMode) {
  25501. if (_this._previousDelayedSimpleClickTimeout) {
  25502. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25503. }
  25504. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25505. cb(clickInfo, _this._previousPickResult);
  25506. }
  25507. else {
  25508. cb(clickInfo, _this._currentPickResult);
  25509. }
  25510. }
  25511. }
  25512. // just the first click of the double has been raised
  25513. else {
  25514. _this._doubleClickOccured = false;
  25515. _this._previousStartingPointerTime = _this._startingPointerTime;
  25516. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25517. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25518. _this._previousButtonPressed = btn;
  25519. }
  25520. }
  25521. }
  25522. }
  25523. clickInfo.ignore = true;
  25524. cb(clickInfo, _this._currentPickResult);
  25525. };
  25526. this._onPointerMove = function (evt) {
  25527. _this._updatePointerPosition(evt);
  25528. // PreObservable support
  25529. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25530. return;
  25531. }
  25532. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25533. return;
  25534. }
  25535. if (!_this.pointerMovePredicate) {
  25536. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25537. }
  25538. // Meshes
  25539. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25540. _this._processPointerMove(pickResult, evt);
  25541. };
  25542. this._onPointerDown = function (evt) {
  25543. _this._totalPointersPressed++;
  25544. _this._pickedDownMesh = null;
  25545. _this._meshPickProceed = false;
  25546. _this._updatePointerPosition(evt);
  25547. if (_this.preventDefaultOnPointerDown && canvas) {
  25548. evt.preventDefault();
  25549. canvas.focus();
  25550. }
  25551. // PreObservable support
  25552. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25553. return;
  25554. }
  25555. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25556. return;
  25557. }
  25558. _this._pointerCaptures[evt.pointerId] = true;
  25559. _this._startingPointerPosition.x = _this._pointerX;
  25560. _this._startingPointerPosition.y = _this._pointerY;
  25561. _this._startingPointerTime = Date.now();
  25562. if (!_this.pointerDownPredicate) {
  25563. _this.pointerDownPredicate = function (mesh) {
  25564. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25565. };
  25566. }
  25567. // Meshes
  25568. _this._pickedDownMesh = null;
  25569. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25570. _this._processPointerDown(pickResult, evt);
  25571. };
  25572. this._onPointerUp = function (evt) {
  25573. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25574. return; // So we need to test it the pointer down was pressed before.
  25575. }
  25576. _this._totalPointersPressed--;
  25577. _this._pickedUpMesh = null;
  25578. _this._meshPickProceed = false;
  25579. _this._updatePointerPosition(evt);
  25580. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25581. // PreObservable support
  25582. if (_this.onPrePointerObservable.hasObservers()) {
  25583. if (!clickInfo.ignore) {
  25584. if (!clickInfo.hasSwiped) {
  25585. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25586. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25587. return;
  25588. }
  25589. }
  25590. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25591. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25592. return;
  25593. }
  25594. }
  25595. }
  25596. }
  25597. else {
  25598. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25599. return;
  25600. }
  25601. }
  25602. }
  25603. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25604. return;
  25605. }
  25606. _this._pointerCaptures[evt.pointerId] = false;
  25607. if (!_this.pointerUpPredicate) {
  25608. _this.pointerUpPredicate = function (mesh) {
  25609. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25610. };
  25611. }
  25612. // Meshes
  25613. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25614. _this._initActionManager(null, clickInfo);
  25615. }
  25616. if (!pickResult) {
  25617. pickResult = _this._currentPickResult;
  25618. }
  25619. _this._processPointerUp(pickResult, evt, clickInfo);
  25620. _this._previousPickResult = _this._currentPickResult;
  25621. });
  25622. };
  25623. this._onKeyDown = function (evt) {
  25624. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25625. if (_this.onPreKeyboardObservable.hasObservers()) {
  25626. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25627. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25628. if (pi.skipOnPointerObservable) {
  25629. return;
  25630. }
  25631. }
  25632. if (_this.onKeyboardObservable.hasObservers()) {
  25633. var pi = new BABYLON.KeyboardInfo(type, evt);
  25634. _this.onKeyboardObservable.notifyObservers(pi, type);
  25635. }
  25636. if (_this.actionManager) {
  25637. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25638. }
  25639. };
  25640. this._onKeyUp = function (evt) {
  25641. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25642. if (_this.onPreKeyboardObservable.hasObservers()) {
  25643. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25644. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25645. if (pi.skipOnPointerObservable) {
  25646. return;
  25647. }
  25648. }
  25649. if (_this.onKeyboardObservable.hasObservers()) {
  25650. var pi = new BABYLON.KeyboardInfo(type, evt);
  25651. _this.onKeyboardObservable.notifyObservers(pi, type);
  25652. }
  25653. if (_this.actionManager) {
  25654. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25655. }
  25656. };
  25657. var engine = this.getEngine();
  25658. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25659. if (!canvas) {
  25660. return;
  25661. }
  25662. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25663. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25664. });
  25665. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25666. if (!canvas) {
  25667. return;
  25668. }
  25669. canvas.removeEventListener("keydown", _this._onKeyDown);
  25670. canvas.removeEventListener("keyup", _this._onKeyUp);
  25671. });
  25672. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25673. var canvas = this._engine.getRenderingCanvas();
  25674. if (!canvas) {
  25675. return;
  25676. }
  25677. if (attachMove) {
  25678. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25679. // Wheel
  25680. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25681. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25682. }
  25683. if (attachDown) {
  25684. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25685. }
  25686. if (attachUp) {
  25687. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25688. }
  25689. canvas.tabIndex = 1;
  25690. };
  25691. /** Detaches all event handlers*/
  25692. Scene.prototype.detachControl = function () {
  25693. var engine = this.getEngine();
  25694. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25695. var canvas = engine.getRenderingCanvas();
  25696. if (!canvas) {
  25697. return;
  25698. }
  25699. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25700. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25701. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25702. if (this._onCanvasBlurObserver) {
  25703. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25704. }
  25705. if (this._onCanvasFocusObserver) {
  25706. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25707. }
  25708. // Wheel
  25709. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25710. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25711. // Keyboard
  25712. canvas.removeEventListener("keydown", this._onKeyDown);
  25713. canvas.removeEventListener("keyup", this._onKeyUp);
  25714. // Observables
  25715. this.onKeyboardObservable.clear();
  25716. this.onPreKeyboardObservable.clear();
  25717. this.onPointerObservable.clear();
  25718. this.onPrePointerObservable.clear();
  25719. };
  25720. /**
  25721. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25722. * Delay loaded resources are not taking in account
  25723. * @return true if all required resources are ready
  25724. */
  25725. Scene.prototype.isReady = function () {
  25726. if (this._isDisposed) {
  25727. return false;
  25728. }
  25729. if (this._pendingData.length > 0) {
  25730. return false;
  25731. }
  25732. var index;
  25733. var engine = this.getEngine();
  25734. // Geometries
  25735. for (index = 0; index < this.geometries.length; index++) {
  25736. var geometry = this.geometries[index];
  25737. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25738. return false;
  25739. }
  25740. }
  25741. // Meshes
  25742. for (index = 0; index < this.meshes.length; index++) {
  25743. var mesh = this.meshes[index];
  25744. if (!mesh.isEnabled()) {
  25745. continue;
  25746. }
  25747. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25748. continue;
  25749. }
  25750. if (!mesh.isReady(true)) {
  25751. return false;
  25752. }
  25753. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25754. // Is Ready For Mesh
  25755. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25756. var step = _a[_i];
  25757. if (!step.action(mesh, hardwareInstancedRendering)) {
  25758. return false;
  25759. }
  25760. }
  25761. }
  25762. // Post-processes
  25763. if (this.activeCameras && this.activeCameras.length > 0) {
  25764. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25765. var camera = _c[_b];
  25766. if (!camera.isReady(true)) {
  25767. return false;
  25768. }
  25769. }
  25770. }
  25771. else if (this.activeCamera) {
  25772. if (!this.activeCamera.isReady(true)) {
  25773. return false;
  25774. }
  25775. }
  25776. // Particles
  25777. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25778. var particleSystem = _e[_d];
  25779. if (!particleSystem.isReady()) {
  25780. return false;
  25781. }
  25782. }
  25783. return true;
  25784. };
  25785. /** Resets all cached information relative to material (including effect and visibility) */
  25786. Scene.prototype.resetCachedMaterial = function () {
  25787. this._cachedMaterial = null;
  25788. this._cachedEffect = null;
  25789. this._cachedVisibility = null;
  25790. };
  25791. /**
  25792. * Registers a function to be called before every frame render
  25793. * @param func defines the function to register
  25794. */
  25795. Scene.prototype.registerBeforeRender = function (func) {
  25796. this.onBeforeRenderObservable.add(func);
  25797. };
  25798. /**
  25799. * Unregisters a function called before every frame render
  25800. * @param func defines the function to unregister
  25801. */
  25802. Scene.prototype.unregisterBeforeRender = function (func) {
  25803. this.onBeforeRenderObservable.removeCallback(func);
  25804. };
  25805. /**
  25806. * Registers a function to be called after every frame render
  25807. * @param func defines the function to register
  25808. */
  25809. Scene.prototype.registerAfterRender = function (func) {
  25810. this.onAfterRenderObservable.add(func);
  25811. };
  25812. /**
  25813. * Unregisters a function called after every frame render
  25814. * @param func defines the function to unregister
  25815. */
  25816. Scene.prototype.unregisterAfterRender = function (func) {
  25817. this.onAfterRenderObservable.removeCallback(func);
  25818. };
  25819. Scene.prototype._executeOnceBeforeRender = function (func) {
  25820. var _this = this;
  25821. var execFunc = function () {
  25822. func();
  25823. setTimeout(function () {
  25824. _this.unregisterBeforeRender(execFunc);
  25825. });
  25826. };
  25827. this.registerBeforeRender(execFunc);
  25828. };
  25829. /**
  25830. * The provided function will run before render once and will be disposed afterwards.
  25831. * A timeout delay can be provided so that the function will be executed in N ms.
  25832. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25833. * @param func The function to be executed.
  25834. * @param timeout optional delay in ms
  25835. */
  25836. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25837. var _this = this;
  25838. if (timeout !== undefined) {
  25839. setTimeout(function () {
  25840. _this._executeOnceBeforeRender(func);
  25841. }, timeout);
  25842. }
  25843. else {
  25844. this._executeOnceBeforeRender(func);
  25845. }
  25846. };
  25847. /** @hidden */
  25848. Scene.prototype._addPendingData = function (data) {
  25849. this._pendingData.push(data);
  25850. };
  25851. /** @hidden */
  25852. Scene.prototype._removePendingData = function (data) {
  25853. var wasLoading = this.isLoading;
  25854. var index = this._pendingData.indexOf(data);
  25855. if (index !== -1) {
  25856. this._pendingData.splice(index, 1);
  25857. }
  25858. if (wasLoading && !this.isLoading) {
  25859. this.onDataLoadedObservable.notifyObservers(this);
  25860. }
  25861. };
  25862. /**
  25863. * Returns the number of items waiting to be loaded
  25864. * @returns the number of items waiting to be loaded
  25865. */
  25866. Scene.prototype.getWaitingItemsCount = function () {
  25867. return this._pendingData.length;
  25868. };
  25869. Object.defineProperty(Scene.prototype, "isLoading", {
  25870. /**
  25871. * Returns a boolean indicating if the scene is still loading data
  25872. */
  25873. get: function () {
  25874. return this._pendingData.length > 0;
  25875. },
  25876. enumerable: true,
  25877. configurable: true
  25878. });
  25879. /**
  25880. * Registers a function to be executed when the scene is ready
  25881. * @param {Function} func - the function to be executed
  25882. */
  25883. Scene.prototype.executeWhenReady = function (func) {
  25884. var _this = this;
  25885. this.onReadyObservable.add(func);
  25886. if (this._executeWhenReadyTimeoutId !== -1) {
  25887. return;
  25888. }
  25889. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25890. _this._checkIsReady();
  25891. }, 150);
  25892. };
  25893. /**
  25894. * Returns a promise that resolves when the scene is ready
  25895. * @returns A promise that resolves when the scene is ready
  25896. */
  25897. Scene.prototype.whenReadyAsync = function () {
  25898. var _this = this;
  25899. return new Promise(function (resolve) {
  25900. _this.executeWhenReady(function () {
  25901. resolve();
  25902. });
  25903. });
  25904. };
  25905. /** @hidden */
  25906. Scene.prototype._checkIsReady = function () {
  25907. var _this = this;
  25908. this._registerTransientComponents();
  25909. if (this.isReady()) {
  25910. this.onReadyObservable.notifyObservers(this);
  25911. this.onReadyObservable.clear();
  25912. this._executeWhenReadyTimeoutId = -1;
  25913. return;
  25914. }
  25915. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25916. _this._checkIsReady();
  25917. }, 150);
  25918. };
  25919. // Animations
  25920. /**
  25921. * Will start the animation sequence of a given target
  25922. * @param target defines the target
  25923. * @param from defines from which frame should animation start
  25924. * @param to defines until which frame should animation run.
  25925. * @param weight defines the weight to apply to the animation (1.0 by default)
  25926. * @param loop defines if the animation loops
  25927. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25928. * @param onAnimationEnd defines the function to be executed when the animation ends
  25929. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25930. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25931. * @returns the animatable object created for this animation
  25932. */
  25933. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25934. if (weight === void 0) { weight = 1.0; }
  25935. if (speedRatio === void 0) { speedRatio = 1.0; }
  25936. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25937. returnedAnimatable.weight = weight;
  25938. return returnedAnimatable;
  25939. };
  25940. /**
  25941. * Will start the animation sequence of a given target
  25942. * @param target defines the target
  25943. * @param from defines from which frame should animation start
  25944. * @param to defines until which frame should animation run.
  25945. * @param loop defines if the animation loops
  25946. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25947. * @param onAnimationEnd defines the function to be executed when the animation ends
  25948. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25949. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25950. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25951. * @returns the animatable object created for this animation
  25952. */
  25953. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25954. if (speedRatio === void 0) { speedRatio = 1.0; }
  25955. if (stopCurrent === void 0) { stopCurrent = true; }
  25956. if (from > to && speedRatio > 0) {
  25957. speedRatio *= -1;
  25958. }
  25959. if (stopCurrent) {
  25960. this.stopAnimation(target, undefined, targetMask);
  25961. }
  25962. if (!animatable) {
  25963. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25964. }
  25965. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25966. // Local animations
  25967. if (target.animations && shouldRunTargetAnimations) {
  25968. animatable.appendAnimations(target, target.animations);
  25969. }
  25970. // Children animations
  25971. if (target.getAnimatables) {
  25972. var animatables = target.getAnimatables();
  25973. for (var index = 0; index < animatables.length; index++) {
  25974. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25975. }
  25976. }
  25977. animatable.reset();
  25978. return animatable;
  25979. };
  25980. /**
  25981. * Begin a new animation on a given node
  25982. * @param target defines the target where the animation will take place
  25983. * @param animations defines the list of animations to start
  25984. * @param from defines the initial value
  25985. * @param to defines the final value
  25986. * @param loop defines if you want animation to loop (off by default)
  25987. * @param speedRatio defines the speed ratio to apply to all animations
  25988. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25989. * @returns the list of created animatables
  25990. */
  25991. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25992. if (speedRatio === undefined) {
  25993. speedRatio = 1.0;
  25994. }
  25995. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25996. return animatable;
  25997. };
  25998. /**
  25999. * Begin a new animation on a given node and its hierarchy
  26000. * @param target defines the root node where the animation will take place
  26001. * @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.
  26002. * @param animations defines the list of animations to start
  26003. * @param from defines the initial value
  26004. * @param to defines the final value
  26005. * @param loop defines if you want animation to loop (off by default)
  26006. * @param speedRatio defines the speed ratio to apply to all animations
  26007. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26008. * @returns the list of animatables created for all nodes
  26009. */
  26010. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26011. var children = target.getDescendants(directDescendantsOnly);
  26012. var result = [];
  26013. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26014. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26015. var child = children_1[_i];
  26016. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26017. }
  26018. return result;
  26019. };
  26020. /**
  26021. * Gets the animatable associated with a specific target
  26022. * @param target defines the target of the animatable
  26023. * @returns the required animatable if found
  26024. */
  26025. Scene.prototype.getAnimatableByTarget = function (target) {
  26026. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26027. if (this._activeAnimatables[index].target === target) {
  26028. return this._activeAnimatables[index];
  26029. }
  26030. }
  26031. return null;
  26032. };
  26033. /**
  26034. * Gets all animatables associated with a given target
  26035. * @param target defines the target to look animatables for
  26036. * @returns an array of Animatables
  26037. */
  26038. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26039. var result = [];
  26040. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26041. if (this._activeAnimatables[index].target === target) {
  26042. result.push(this._activeAnimatables[index]);
  26043. }
  26044. }
  26045. return result;
  26046. };
  26047. Object.defineProperty(Scene.prototype, "animatables", {
  26048. /**
  26049. * Gets all animatable attached to the scene
  26050. */
  26051. get: function () {
  26052. return this._activeAnimatables;
  26053. },
  26054. enumerable: true,
  26055. configurable: true
  26056. });
  26057. /**
  26058. * Will stop the animation of the given target
  26059. * @param target - the target
  26060. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26061. * @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)
  26062. */
  26063. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26064. var animatables = this.getAllAnimatablesByTarget(target);
  26065. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26066. var animatable = animatables_1[_i];
  26067. animatable.stop(animationName, targetMask);
  26068. }
  26069. };
  26070. /**
  26071. * Stops and removes all animations that have been applied to the scene
  26072. */
  26073. Scene.prototype.stopAllAnimations = function () {
  26074. if (this._activeAnimatables) {
  26075. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26076. this._activeAnimatables[i].stop();
  26077. }
  26078. this._activeAnimatables = [];
  26079. }
  26080. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26081. var group = _a[_i];
  26082. group.stop();
  26083. }
  26084. };
  26085. Scene.prototype._animate = function () {
  26086. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26087. return;
  26088. }
  26089. // Getting time
  26090. var now = BABYLON.Tools.Now;
  26091. if (!this._animationTimeLast) {
  26092. if (this._pendingData.length > 0) {
  26093. return;
  26094. }
  26095. this._animationTimeLast = now;
  26096. }
  26097. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26098. this._animationTime += deltaTime;
  26099. this._animationTimeLast = now;
  26100. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26101. this._activeAnimatables[index]._animate(this._animationTime);
  26102. }
  26103. // Late animation bindings
  26104. this._processLateAnimationBindings();
  26105. };
  26106. /** @hidden */
  26107. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26108. var target = runtimeAnimation.target;
  26109. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26110. if (!target._lateAnimationHolders) {
  26111. target._lateAnimationHolders = {};
  26112. }
  26113. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26114. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26115. totalWeight: 0,
  26116. animations: [],
  26117. originalValue: originalValue
  26118. };
  26119. }
  26120. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26121. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26122. };
  26123. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26124. var normalizer = 1.0;
  26125. var finalPosition = BABYLON.Tmp.Vector3[0];
  26126. var finalScaling = BABYLON.Tmp.Vector3[1];
  26127. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26128. var startIndex = 0;
  26129. var originalAnimation = holder.animations[0];
  26130. var originalValue = holder.originalValue;
  26131. var scale = 1;
  26132. if (holder.totalWeight < 1.0) {
  26133. // We need to mix the original value in
  26134. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26135. scale = 1.0 - holder.totalWeight;
  26136. }
  26137. else {
  26138. startIndex = 1;
  26139. // We need to normalize the weights
  26140. normalizer = holder.totalWeight;
  26141. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26142. scale = originalAnimation.weight / normalizer;
  26143. if (scale == 1) {
  26144. return originalAnimation.currentValue;
  26145. }
  26146. }
  26147. finalScaling.scaleInPlace(scale);
  26148. finalPosition.scaleInPlace(scale);
  26149. finalQuaternion.scaleInPlace(scale);
  26150. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26151. var runtimeAnimation = holder.animations[animIndex];
  26152. var scale = runtimeAnimation.weight / normalizer;
  26153. var currentPosition = BABYLON.Tmp.Vector3[2];
  26154. var currentScaling = BABYLON.Tmp.Vector3[3];
  26155. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26156. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26157. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26158. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26159. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26160. }
  26161. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26162. return originalAnimation._workValue;
  26163. };
  26164. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26165. var originalAnimation = holder.animations[0];
  26166. var originalValue = holder.originalValue;
  26167. if (holder.animations.length === 1) {
  26168. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26169. return refQuaternion;
  26170. }
  26171. var normalizer = 1.0;
  26172. var quaternions;
  26173. var weights;
  26174. if (holder.totalWeight < 1.0) {
  26175. var scale = 1.0 - holder.totalWeight;
  26176. quaternions = [];
  26177. weights = [];
  26178. quaternions.push(originalValue);
  26179. weights.push(scale);
  26180. }
  26181. else {
  26182. if (holder.animations.length === 2) { // Slerp as soon as we can
  26183. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26184. return refQuaternion;
  26185. }
  26186. quaternions = [];
  26187. weights = [];
  26188. normalizer = holder.totalWeight;
  26189. }
  26190. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26191. var runtimeAnimation = holder.animations[animIndex];
  26192. quaternions.push(runtimeAnimation.currentValue);
  26193. weights.push(runtimeAnimation.weight / normalizer);
  26194. }
  26195. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26196. var cumulativeAmount = 0;
  26197. var cumulativeQuaternion = null;
  26198. for (var index = 0; index < quaternions.length;) {
  26199. if (!cumulativeQuaternion) {
  26200. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26201. cumulativeQuaternion = refQuaternion;
  26202. cumulativeAmount = weights[index] + weights[index + 1];
  26203. index += 2;
  26204. continue;
  26205. }
  26206. cumulativeAmount += weights[index];
  26207. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26208. index++;
  26209. }
  26210. return cumulativeQuaternion;
  26211. };
  26212. Scene.prototype._processLateAnimationBindings = function () {
  26213. if (!this._registeredForLateAnimationBindings.length) {
  26214. return;
  26215. }
  26216. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26217. var target = this._registeredForLateAnimationBindings.data[index];
  26218. for (var path in target._lateAnimationHolders) {
  26219. var holder = target._lateAnimationHolders[path];
  26220. var originalAnimation = holder.animations[0];
  26221. var originalValue = holder.originalValue;
  26222. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26223. var finalValue = target[path];
  26224. if (matrixDecomposeMode) {
  26225. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26226. }
  26227. else {
  26228. var quaternionMode = originalValue.w !== undefined;
  26229. if (quaternionMode) {
  26230. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26231. }
  26232. else {
  26233. var startIndex = 0;
  26234. var normalizer = 1.0;
  26235. if (holder.totalWeight < 1.0) {
  26236. // We need to mix the original value in
  26237. if (originalValue.scale) {
  26238. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26239. }
  26240. else {
  26241. finalValue = originalValue * (1.0 - holder.totalWeight);
  26242. }
  26243. }
  26244. else {
  26245. // We need to normalize the weights
  26246. normalizer = holder.totalWeight;
  26247. var scale_1 = originalAnimation.weight / normalizer;
  26248. if (scale_1 !== 1) {
  26249. if (originalAnimation.currentValue.scale) {
  26250. finalValue = originalAnimation.currentValue.scale(scale_1);
  26251. }
  26252. else {
  26253. finalValue = originalAnimation.currentValue * scale_1;
  26254. }
  26255. }
  26256. else {
  26257. finalValue = originalAnimation.currentValue;
  26258. }
  26259. startIndex = 1;
  26260. }
  26261. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26262. var runtimeAnimation = holder.animations[animIndex];
  26263. var scale = runtimeAnimation.weight / normalizer;
  26264. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26265. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26266. }
  26267. else {
  26268. finalValue += runtimeAnimation.currentValue * scale;
  26269. }
  26270. }
  26271. }
  26272. }
  26273. target[path] = finalValue;
  26274. }
  26275. target._lateAnimationHolders = {};
  26276. }
  26277. this._registeredForLateAnimationBindings.reset();
  26278. };
  26279. // Matrix
  26280. /** @hidden */
  26281. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26282. this._useAlternateCameraConfiguration = active;
  26283. };
  26284. /**
  26285. * Gets the current view matrix
  26286. * @returns a Matrix
  26287. */
  26288. Scene.prototype.getViewMatrix = function () {
  26289. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26290. };
  26291. /**
  26292. * Gets the current projection matrix
  26293. * @returns a Matrix
  26294. */
  26295. Scene.prototype.getProjectionMatrix = function () {
  26296. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26297. };
  26298. /**
  26299. * Gets the current transform matrix
  26300. * @returns a Matrix made of View * Projection
  26301. */
  26302. Scene.prototype.getTransformMatrix = function () {
  26303. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26304. };
  26305. /**
  26306. * Sets the current transform matrix
  26307. * @param view defines the View matrix to use
  26308. * @param projection defines the Projection matrix to use
  26309. */
  26310. Scene.prototype.setTransformMatrix = function (view, projection) {
  26311. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26312. return;
  26313. }
  26314. this._viewUpdateFlag = view.updateFlag;
  26315. this._projectionUpdateFlag = projection.updateFlag;
  26316. this._viewMatrix = view;
  26317. this._projectionMatrix = projection;
  26318. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26319. // Update frustum
  26320. if (!this._frustumPlanes) {
  26321. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26322. }
  26323. else {
  26324. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26325. }
  26326. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26327. var otherCamera = this.activeCamera._alternateCamera;
  26328. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26329. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26330. }
  26331. if (this._sceneUbo.useUbo) {
  26332. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26333. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26334. this._sceneUbo.update();
  26335. }
  26336. };
  26337. /** @hidden */
  26338. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26339. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26340. return;
  26341. }
  26342. this._alternateViewUpdateFlag = view.updateFlag;
  26343. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26344. this._alternateViewMatrix = view;
  26345. this._alternateProjectionMatrix = projection;
  26346. if (!this._alternateTransformMatrix) {
  26347. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26348. }
  26349. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26350. if (!this._alternateSceneUbo) {
  26351. this._createAlternateUbo();
  26352. }
  26353. if (this._alternateSceneUbo.useUbo) {
  26354. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26355. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26356. this._alternateSceneUbo.update();
  26357. }
  26358. };
  26359. /**
  26360. * Gets the uniform buffer used to store scene data
  26361. * @returns a UniformBuffer
  26362. */
  26363. Scene.prototype.getSceneUniformBuffer = function () {
  26364. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26365. };
  26366. /**
  26367. * Gets an unique (relatively to the current scene) Id
  26368. * @returns an unique number for the scene
  26369. */
  26370. Scene.prototype.getUniqueId = function () {
  26371. var result = Scene._uniqueIdCounter;
  26372. Scene._uniqueIdCounter++;
  26373. return result;
  26374. };
  26375. /**
  26376. * Add a mesh to the list of scene's meshes
  26377. * @param newMesh defines the mesh to add
  26378. * @param recursive if all child meshes should also be added to the scene
  26379. */
  26380. Scene.prototype.addMesh = function (newMesh, recursive) {
  26381. var _this = this;
  26382. if (recursive === void 0) { recursive = false; }
  26383. this.meshes.push(newMesh);
  26384. //notify the collision coordinator
  26385. if (this.collisionCoordinator) {
  26386. this.collisionCoordinator.onMeshAdded(newMesh);
  26387. }
  26388. newMesh._resyncLightSources();
  26389. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26390. if (recursive) {
  26391. newMesh.getChildMeshes().forEach(function (m) {
  26392. _this.addMesh(m);
  26393. });
  26394. }
  26395. };
  26396. /**
  26397. * Remove a mesh for the list of scene's meshes
  26398. * @param toRemove defines the mesh to remove
  26399. * @param recursive if all child meshes should also be removed from the scene
  26400. * @returns the index where the mesh was in the mesh list
  26401. */
  26402. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26403. var _this = this;
  26404. if (recursive === void 0) { recursive = false; }
  26405. var index = this.meshes.indexOf(toRemove);
  26406. if (index !== -1) {
  26407. // Remove from the scene if mesh found
  26408. this.meshes.splice(index, 1);
  26409. }
  26410. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26411. if (recursive) {
  26412. toRemove.getChildMeshes().forEach(function (m) {
  26413. _this.removeMesh(m);
  26414. });
  26415. }
  26416. return index;
  26417. };
  26418. /**
  26419. * Add a transform node to the list of scene's transform nodes
  26420. * @param newTransformNode defines the transform node to add
  26421. */
  26422. Scene.prototype.addTransformNode = function (newTransformNode) {
  26423. this.transformNodes.push(newTransformNode);
  26424. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26425. };
  26426. /**
  26427. * Remove a transform node for the list of scene's transform nodes
  26428. * @param toRemove defines the transform node to remove
  26429. * @returns the index where the transform node was in the transform node list
  26430. */
  26431. Scene.prototype.removeTransformNode = function (toRemove) {
  26432. var index = this.transformNodes.indexOf(toRemove);
  26433. if (index !== -1) {
  26434. // Remove from the scene if found
  26435. this.transformNodes.splice(index, 1);
  26436. }
  26437. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26438. return index;
  26439. };
  26440. /**
  26441. * Remove a skeleton for the list of scene's skeletons
  26442. * @param toRemove defines the skeleton to remove
  26443. * @returns the index where the skeleton was in the skeleton list
  26444. */
  26445. Scene.prototype.removeSkeleton = function (toRemove) {
  26446. var index = this.skeletons.indexOf(toRemove);
  26447. if (index !== -1) {
  26448. // Remove from the scene if found
  26449. this.skeletons.splice(index, 1);
  26450. }
  26451. return index;
  26452. };
  26453. /**
  26454. * Remove a morph target for the list of scene's morph targets
  26455. * @param toRemove defines the morph target to remove
  26456. * @returns the index where the morph target was in the morph target list
  26457. */
  26458. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26459. var index = this.morphTargetManagers.indexOf(toRemove);
  26460. if (index !== -1) {
  26461. // Remove from the scene if found
  26462. this.morphTargetManagers.splice(index, 1);
  26463. }
  26464. return index;
  26465. };
  26466. /**
  26467. * Remove a light for the list of scene's lights
  26468. * @param toRemove defines the light to remove
  26469. * @returns the index where the light was in the light list
  26470. */
  26471. Scene.prototype.removeLight = function (toRemove) {
  26472. var index = this.lights.indexOf(toRemove);
  26473. if (index !== -1) {
  26474. // Remove from meshes
  26475. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26476. var mesh = _a[_i];
  26477. mesh._removeLightSource(toRemove);
  26478. }
  26479. // Remove from the scene if mesh found
  26480. this.lights.splice(index, 1);
  26481. this.sortLightsByPriority();
  26482. }
  26483. this.onLightRemovedObservable.notifyObservers(toRemove);
  26484. return index;
  26485. };
  26486. /**
  26487. * Remove a camera for the list of scene's cameras
  26488. * @param toRemove defines the camera to remove
  26489. * @returns the index where the camera was in the camera list
  26490. */
  26491. Scene.prototype.removeCamera = function (toRemove) {
  26492. var index = this.cameras.indexOf(toRemove);
  26493. if (index !== -1) {
  26494. // Remove from the scene if mesh found
  26495. this.cameras.splice(index, 1);
  26496. }
  26497. // Remove from activeCameras
  26498. var index2 = this.activeCameras.indexOf(toRemove);
  26499. if (index2 !== -1) {
  26500. // Remove from the scene if mesh found
  26501. this.activeCameras.splice(index2, 1);
  26502. }
  26503. // Reset the activeCamera
  26504. if (this.activeCamera === toRemove) {
  26505. if (this.cameras.length > 0) {
  26506. this.activeCamera = this.cameras[0];
  26507. }
  26508. else {
  26509. this.activeCamera = null;
  26510. }
  26511. }
  26512. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26513. return index;
  26514. };
  26515. /**
  26516. * Remove a particle system for the list of scene's particle systems
  26517. * @param toRemove defines the particle system to remove
  26518. * @returns the index where the particle system was in the particle system list
  26519. */
  26520. Scene.prototype.removeParticleSystem = function (toRemove) {
  26521. var index = this.particleSystems.indexOf(toRemove);
  26522. if (index !== -1) {
  26523. this.particleSystems.splice(index, 1);
  26524. }
  26525. return index;
  26526. };
  26527. /**
  26528. * Remove a animation for the list of scene's animations
  26529. * @param toRemove defines the animation to remove
  26530. * @returns the index where the animation was in the animation list
  26531. */
  26532. Scene.prototype.removeAnimation = function (toRemove) {
  26533. var index = this.animations.indexOf(toRemove);
  26534. if (index !== -1) {
  26535. this.animations.splice(index, 1);
  26536. }
  26537. return index;
  26538. };
  26539. /**
  26540. * Removes the given animation group from this scene.
  26541. * @param toRemove The animation group to remove
  26542. * @returns The index of the removed animation group
  26543. */
  26544. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26545. var index = this.animationGroups.indexOf(toRemove);
  26546. if (index !== -1) {
  26547. this.animationGroups.splice(index, 1);
  26548. }
  26549. return index;
  26550. };
  26551. /**
  26552. * Removes the given multi-material from this scene.
  26553. * @param toRemove The multi-material to remove
  26554. * @returns The index of the removed multi-material
  26555. */
  26556. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26557. var index = this.multiMaterials.indexOf(toRemove);
  26558. if (index !== -1) {
  26559. this.multiMaterials.splice(index, 1);
  26560. }
  26561. return index;
  26562. };
  26563. /**
  26564. * Removes the given material from this scene.
  26565. * @param toRemove The material to remove
  26566. * @returns The index of the removed material
  26567. */
  26568. Scene.prototype.removeMaterial = function (toRemove) {
  26569. var index = this.materials.indexOf(toRemove);
  26570. if (index !== -1) {
  26571. this.materials.splice(index, 1);
  26572. }
  26573. return index;
  26574. };
  26575. /**
  26576. * Removes the given action manager from this scene.
  26577. * @param toRemove The action manager to remove
  26578. * @returns The index of the removed action manager
  26579. */
  26580. Scene.prototype.removeActionManager = function (toRemove) {
  26581. var index = this.actionManagers.indexOf(toRemove);
  26582. if (index !== -1) {
  26583. this.actionManagers.splice(index, 1);
  26584. }
  26585. return index;
  26586. };
  26587. /**
  26588. * Removes the given texture from this scene.
  26589. * @param toRemove The texture to remove
  26590. * @returns The index of the removed texture
  26591. */
  26592. Scene.prototype.removeTexture = function (toRemove) {
  26593. var index = this.textures.indexOf(toRemove);
  26594. if (index !== -1) {
  26595. this.textures.splice(index, 1);
  26596. }
  26597. return index;
  26598. };
  26599. /**
  26600. * Adds the given light to this scene
  26601. * @param newLight The light to add
  26602. */
  26603. Scene.prototype.addLight = function (newLight) {
  26604. this.lights.push(newLight);
  26605. this.sortLightsByPriority();
  26606. // Add light to all meshes (To support if the light is removed and then readded)
  26607. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26608. var mesh = _a[_i];
  26609. if (mesh._lightSources.indexOf(newLight) === -1) {
  26610. mesh._lightSources.push(newLight);
  26611. mesh._resyncLightSources();
  26612. }
  26613. }
  26614. this.onNewLightAddedObservable.notifyObservers(newLight);
  26615. };
  26616. /**
  26617. * Sorts the list list based on light priorities
  26618. */
  26619. Scene.prototype.sortLightsByPriority = function () {
  26620. if (this.requireLightSorting) {
  26621. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26622. }
  26623. };
  26624. /**
  26625. * Adds the given camera to this scene
  26626. * @param newCamera The camera to add
  26627. */
  26628. Scene.prototype.addCamera = function (newCamera) {
  26629. this.cameras.push(newCamera);
  26630. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26631. };
  26632. /**
  26633. * Adds the given skeleton to this scene
  26634. * @param newSkeleton The skeleton to add
  26635. */
  26636. Scene.prototype.addSkeleton = function (newSkeleton) {
  26637. this.skeletons.push(newSkeleton);
  26638. };
  26639. /**
  26640. * Adds the given particle system to this scene
  26641. * @param newParticleSystem The particle system to add
  26642. */
  26643. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26644. this.particleSystems.push(newParticleSystem);
  26645. };
  26646. /**
  26647. * Adds the given animation to this scene
  26648. * @param newAnimation The animation to add
  26649. */
  26650. Scene.prototype.addAnimation = function (newAnimation) {
  26651. this.animations.push(newAnimation);
  26652. };
  26653. /**
  26654. * Adds the given animation group to this scene.
  26655. * @param newAnimationGroup The animation group to add
  26656. */
  26657. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26658. this.animationGroups.push(newAnimationGroup);
  26659. };
  26660. /**
  26661. * Adds the given multi-material to this scene
  26662. * @param newMultiMaterial The multi-material to add
  26663. */
  26664. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26665. this.multiMaterials.push(newMultiMaterial);
  26666. };
  26667. /**
  26668. * Adds the given material to this scene
  26669. * @param newMaterial The material to add
  26670. */
  26671. Scene.prototype.addMaterial = function (newMaterial) {
  26672. this.materials.push(newMaterial);
  26673. };
  26674. /**
  26675. * Adds the given morph target to this scene
  26676. * @param newMorphTargetManager The morph target to add
  26677. */
  26678. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26679. this.morphTargetManagers.push(newMorphTargetManager);
  26680. };
  26681. /**
  26682. * Adds the given geometry to this scene
  26683. * @param newGeometry The geometry to add
  26684. */
  26685. Scene.prototype.addGeometry = function (newGeometry) {
  26686. this.geometries.push(newGeometry);
  26687. };
  26688. /**
  26689. * Adds the given action manager to this scene
  26690. * @param newActionManager The action manager to add
  26691. */
  26692. Scene.prototype.addActionManager = function (newActionManager) {
  26693. this.actionManagers.push(newActionManager);
  26694. };
  26695. /**
  26696. * Adds the given texture to this scene.
  26697. * @param newTexture The texture to add
  26698. */
  26699. Scene.prototype.addTexture = function (newTexture) {
  26700. this.textures.push(newTexture);
  26701. };
  26702. /**
  26703. * Switch active camera
  26704. * @param newCamera defines the new active camera
  26705. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26706. */
  26707. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26708. if (attachControl === void 0) { attachControl = true; }
  26709. var canvas = this._engine.getRenderingCanvas();
  26710. if (!canvas) {
  26711. return;
  26712. }
  26713. if (this.activeCamera) {
  26714. this.activeCamera.detachControl(canvas);
  26715. }
  26716. this.activeCamera = newCamera;
  26717. if (attachControl) {
  26718. newCamera.attachControl(canvas);
  26719. }
  26720. };
  26721. /**
  26722. * sets the active camera of the scene using its ID
  26723. * @param id defines the camera's ID
  26724. * @return the new active camera or null if none found.
  26725. */
  26726. Scene.prototype.setActiveCameraByID = function (id) {
  26727. var camera = this.getCameraByID(id);
  26728. if (camera) {
  26729. this.activeCamera = camera;
  26730. return camera;
  26731. }
  26732. return null;
  26733. };
  26734. /**
  26735. * sets the active camera of the scene using its name
  26736. * @param name defines the camera's name
  26737. * @returns the new active camera or null if none found.
  26738. */
  26739. Scene.prototype.setActiveCameraByName = function (name) {
  26740. var camera = this.getCameraByName(name);
  26741. if (camera) {
  26742. this.activeCamera = camera;
  26743. return camera;
  26744. }
  26745. return null;
  26746. };
  26747. /**
  26748. * get an animation group using its name
  26749. * @param name defines the material's name
  26750. * @return the animation group or null if none found.
  26751. */
  26752. Scene.prototype.getAnimationGroupByName = function (name) {
  26753. for (var index = 0; index < this.animationGroups.length; index++) {
  26754. if (this.animationGroups[index].name === name) {
  26755. return this.animationGroups[index];
  26756. }
  26757. }
  26758. return null;
  26759. };
  26760. /**
  26761. * get a material using its id
  26762. * @param id defines the material's ID
  26763. * @return the material or null if none found.
  26764. */
  26765. Scene.prototype.getMaterialByID = function (id) {
  26766. for (var index = 0; index < this.materials.length; index++) {
  26767. if (this.materials[index].id === id) {
  26768. return this.materials[index];
  26769. }
  26770. }
  26771. return null;
  26772. };
  26773. /**
  26774. * Gets a material using its name
  26775. * @param name defines the material's name
  26776. * @return the material or null if none found.
  26777. */
  26778. Scene.prototype.getMaterialByName = function (name) {
  26779. for (var index = 0; index < this.materials.length; index++) {
  26780. if (this.materials[index].name === name) {
  26781. return this.materials[index];
  26782. }
  26783. }
  26784. return null;
  26785. };
  26786. /**
  26787. * Gets a camera using its id
  26788. * @param id defines the id to look for
  26789. * @returns the camera or null if not found
  26790. */
  26791. Scene.prototype.getCameraByID = function (id) {
  26792. for (var index = 0; index < this.cameras.length; index++) {
  26793. if (this.cameras[index].id === id) {
  26794. return this.cameras[index];
  26795. }
  26796. }
  26797. return null;
  26798. };
  26799. /**
  26800. * Gets a camera using its unique id
  26801. * @param uniqueId defines the unique id to look for
  26802. * @returns the camera or null if not found
  26803. */
  26804. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26805. for (var index = 0; index < this.cameras.length; index++) {
  26806. if (this.cameras[index].uniqueId === uniqueId) {
  26807. return this.cameras[index];
  26808. }
  26809. }
  26810. return null;
  26811. };
  26812. /**
  26813. * Gets a camera using its name
  26814. * @param name defines the camera's name
  26815. * @return the camera or null if none found.
  26816. */
  26817. Scene.prototype.getCameraByName = function (name) {
  26818. for (var index = 0; index < this.cameras.length; index++) {
  26819. if (this.cameras[index].name === name) {
  26820. return this.cameras[index];
  26821. }
  26822. }
  26823. return null;
  26824. };
  26825. /**
  26826. * Gets a bone using its id
  26827. * @param id defines the bone's id
  26828. * @return the bone or null if not found
  26829. */
  26830. Scene.prototype.getBoneByID = function (id) {
  26831. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26832. var skeleton = this.skeletons[skeletonIndex];
  26833. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26834. if (skeleton.bones[boneIndex].id === id) {
  26835. return skeleton.bones[boneIndex];
  26836. }
  26837. }
  26838. }
  26839. return null;
  26840. };
  26841. /**
  26842. * Gets a bone using its id
  26843. * @param name defines the bone's name
  26844. * @return the bone or null if not found
  26845. */
  26846. Scene.prototype.getBoneByName = function (name) {
  26847. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26848. var skeleton = this.skeletons[skeletonIndex];
  26849. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26850. if (skeleton.bones[boneIndex].name === name) {
  26851. return skeleton.bones[boneIndex];
  26852. }
  26853. }
  26854. }
  26855. return null;
  26856. };
  26857. /**
  26858. * Gets a light node using its name
  26859. * @param name defines the the light's name
  26860. * @return the light or null if none found.
  26861. */
  26862. Scene.prototype.getLightByName = function (name) {
  26863. for (var index = 0; index < this.lights.length; index++) {
  26864. if (this.lights[index].name === name) {
  26865. return this.lights[index];
  26866. }
  26867. }
  26868. return null;
  26869. };
  26870. /**
  26871. * Gets a light node using its id
  26872. * @param id defines the light's id
  26873. * @return the light or null if none found.
  26874. */
  26875. Scene.prototype.getLightByID = function (id) {
  26876. for (var index = 0; index < this.lights.length; index++) {
  26877. if (this.lights[index].id === id) {
  26878. return this.lights[index];
  26879. }
  26880. }
  26881. return null;
  26882. };
  26883. /**
  26884. * Gets a light node using its scene-generated unique ID
  26885. * @param uniqueId defines the light's unique id
  26886. * @return the light or null if none found.
  26887. */
  26888. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26889. for (var index = 0; index < this.lights.length; index++) {
  26890. if (this.lights[index].uniqueId === uniqueId) {
  26891. return this.lights[index];
  26892. }
  26893. }
  26894. return null;
  26895. };
  26896. /**
  26897. * Gets a particle system by id
  26898. * @param id defines the particle system id
  26899. * @return the corresponding system or null if none found
  26900. */
  26901. Scene.prototype.getParticleSystemByID = function (id) {
  26902. for (var index = 0; index < this.particleSystems.length; index++) {
  26903. if (this.particleSystems[index].id === id) {
  26904. return this.particleSystems[index];
  26905. }
  26906. }
  26907. return null;
  26908. };
  26909. /**
  26910. * Gets a geometry using its ID
  26911. * @param id defines the geometry's id
  26912. * @return the geometry or null if none found.
  26913. */
  26914. Scene.prototype.getGeometryByID = function (id) {
  26915. for (var index = 0; index < this.geometries.length; index++) {
  26916. if (this.geometries[index].id === id) {
  26917. return this.geometries[index];
  26918. }
  26919. }
  26920. return null;
  26921. };
  26922. /**
  26923. * Add a new geometry to this scene
  26924. * @param geometry defines the geometry to be added to the scene.
  26925. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26926. * @return a boolean defining if the geometry was added or not
  26927. */
  26928. Scene.prototype.pushGeometry = function (geometry, force) {
  26929. if (!force && this.getGeometryByID(geometry.id)) {
  26930. return false;
  26931. }
  26932. this.geometries.push(geometry);
  26933. //notify the collision coordinator
  26934. if (this.collisionCoordinator) {
  26935. this.collisionCoordinator.onGeometryAdded(geometry);
  26936. }
  26937. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26938. return true;
  26939. };
  26940. /**
  26941. * Removes an existing geometry
  26942. * @param geometry defines the geometry to be removed from the scene
  26943. * @return a boolean defining if the geometry was removed or not
  26944. */
  26945. Scene.prototype.removeGeometry = function (geometry) {
  26946. var index = this.geometries.indexOf(geometry);
  26947. if (index > -1) {
  26948. this.geometries.splice(index, 1);
  26949. //notify the collision coordinator
  26950. if (this.collisionCoordinator) {
  26951. this.collisionCoordinator.onGeometryDeleted(geometry);
  26952. }
  26953. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26954. return true;
  26955. }
  26956. return false;
  26957. };
  26958. /**
  26959. * Gets the list of geometries attached to the scene
  26960. * @returns an array of Geometry
  26961. */
  26962. Scene.prototype.getGeometries = function () {
  26963. return this.geometries;
  26964. };
  26965. /**
  26966. * Gets the first added mesh found of a given ID
  26967. * @param id defines the id to search for
  26968. * @return the mesh found or null if not found at all
  26969. */
  26970. Scene.prototype.getMeshByID = function (id) {
  26971. for (var index = 0; index < this.meshes.length; index++) {
  26972. if (this.meshes[index].id === id) {
  26973. return this.meshes[index];
  26974. }
  26975. }
  26976. return null;
  26977. };
  26978. /**
  26979. * Gets a list of meshes using their id
  26980. * @param id defines the id to search for
  26981. * @returns a list of meshes
  26982. */
  26983. Scene.prototype.getMeshesByID = function (id) {
  26984. return this.meshes.filter(function (m) {
  26985. return m.id === id;
  26986. });
  26987. };
  26988. /**
  26989. * Gets the first added transform node found of a given ID
  26990. * @param id defines the id to search for
  26991. * @return the found transform node or null if not found at all.
  26992. */
  26993. Scene.prototype.getTransformNodeByID = function (id) {
  26994. for (var index = 0; index < this.transformNodes.length; index++) {
  26995. if (this.transformNodes[index].id === id) {
  26996. return this.transformNodes[index];
  26997. }
  26998. }
  26999. return null;
  27000. };
  27001. /**
  27002. * Gets a list of transform nodes using their id
  27003. * @param id defines the id to search for
  27004. * @returns a list of transform nodes
  27005. */
  27006. Scene.prototype.getTransformNodesByID = function (id) {
  27007. return this.transformNodes.filter(function (m) {
  27008. return m.id === id;
  27009. });
  27010. };
  27011. /**
  27012. * Gets a mesh with its auto-generated unique id
  27013. * @param uniqueId defines the unique id to search for
  27014. * @return the found mesh or null if not found at all.
  27015. */
  27016. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27017. for (var index = 0; index < this.meshes.length; index++) {
  27018. if (this.meshes[index].uniqueId === uniqueId) {
  27019. return this.meshes[index];
  27020. }
  27021. }
  27022. return null;
  27023. };
  27024. /**
  27025. * Gets a the last added mesh using a given id
  27026. * @param id defines the id to search for
  27027. * @return the found mesh or null if not found at all.
  27028. */
  27029. Scene.prototype.getLastMeshByID = function (id) {
  27030. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27031. if (this.meshes[index].id === id) {
  27032. return this.meshes[index];
  27033. }
  27034. }
  27035. return null;
  27036. };
  27037. /**
  27038. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27039. * @param id defines the id to search for
  27040. * @return the found node or null if not found at all
  27041. */
  27042. Scene.prototype.getLastEntryByID = function (id) {
  27043. var index;
  27044. for (index = this.meshes.length - 1; index >= 0; index--) {
  27045. if (this.meshes[index].id === id) {
  27046. return this.meshes[index];
  27047. }
  27048. }
  27049. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27050. if (this.transformNodes[index].id === id) {
  27051. return this.transformNodes[index];
  27052. }
  27053. }
  27054. for (index = this.cameras.length - 1; index >= 0; index--) {
  27055. if (this.cameras[index].id === id) {
  27056. return this.cameras[index];
  27057. }
  27058. }
  27059. for (index = this.lights.length - 1; index >= 0; index--) {
  27060. if (this.lights[index].id === id) {
  27061. return this.lights[index];
  27062. }
  27063. }
  27064. return null;
  27065. };
  27066. /**
  27067. * Gets a node (Mesh, Camera, Light) using a given id
  27068. * @param id defines the id to search for
  27069. * @return the found node or null if not found at all
  27070. */
  27071. Scene.prototype.getNodeByID = function (id) {
  27072. var mesh = this.getMeshByID(id);
  27073. if (mesh) {
  27074. return mesh;
  27075. }
  27076. var light = this.getLightByID(id);
  27077. if (light) {
  27078. return light;
  27079. }
  27080. var camera = this.getCameraByID(id);
  27081. if (camera) {
  27082. return camera;
  27083. }
  27084. var bone = this.getBoneByID(id);
  27085. return bone;
  27086. };
  27087. /**
  27088. * Gets a node (Mesh, Camera, Light) using a given name
  27089. * @param name defines the name to search for
  27090. * @return the found node or null if not found at all.
  27091. */
  27092. Scene.prototype.getNodeByName = function (name) {
  27093. var mesh = this.getMeshByName(name);
  27094. if (mesh) {
  27095. return mesh;
  27096. }
  27097. var light = this.getLightByName(name);
  27098. if (light) {
  27099. return light;
  27100. }
  27101. var camera = this.getCameraByName(name);
  27102. if (camera) {
  27103. return camera;
  27104. }
  27105. var bone = this.getBoneByName(name);
  27106. return bone;
  27107. };
  27108. /**
  27109. * Gets a mesh using a given name
  27110. * @param name defines the name to search for
  27111. * @return the found mesh or null if not found at all.
  27112. */
  27113. Scene.prototype.getMeshByName = function (name) {
  27114. for (var index = 0; index < this.meshes.length; index++) {
  27115. if (this.meshes[index].name === name) {
  27116. return this.meshes[index];
  27117. }
  27118. }
  27119. return null;
  27120. };
  27121. /**
  27122. * Gets a transform node using a given name
  27123. * @param name defines the name to search for
  27124. * @return the found transform node or null if not found at all.
  27125. */
  27126. Scene.prototype.getTransformNodeByName = function (name) {
  27127. for (var index = 0; index < this.transformNodes.length; index++) {
  27128. if (this.transformNodes[index].name === name) {
  27129. return this.transformNodes[index];
  27130. }
  27131. }
  27132. return null;
  27133. };
  27134. /**
  27135. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27136. * @param id defines the id to search for
  27137. * @return the found skeleton or null if not found at all.
  27138. */
  27139. Scene.prototype.getLastSkeletonByID = function (id) {
  27140. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27141. if (this.skeletons[index].id === id) {
  27142. return this.skeletons[index];
  27143. }
  27144. }
  27145. return null;
  27146. };
  27147. /**
  27148. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27149. * @param id defines the id to search for
  27150. * @return the found skeleton or null if not found at all.
  27151. */
  27152. Scene.prototype.getSkeletonById = function (id) {
  27153. for (var index = 0; index < this.skeletons.length; index++) {
  27154. if (this.skeletons[index].id === id) {
  27155. return this.skeletons[index];
  27156. }
  27157. }
  27158. return null;
  27159. };
  27160. /**
  27161. * Gets a skeleton using a given name
  27162. * @param name defines the name to search for
  27163. * @return the found skeleton or null if not found at all.
  27164. */
  27165. Scene.prototype.getSkeletonByName = function (name) {
  27166. for (var index = 0; index < this.skeletons.length; index++) {
  27167. if (this.skeletons[index].name === name) {
  27168. return this.skeletons[index];
  27169. }
  27170. }
  27171. return null;
  27172. };
  27173. /**
  27174. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27175. * @param id defines the id to search for
  27176. * @return the found morph target manager or null if not found at all.
  27177. */
  27178. Scene.prototype.getMorphTargetManagerById = function (id) {
  27179. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27180. if (this.morphTargetManagers[index].uniqueId === id) {
  27181. return this.morphTargetManagers[index];
  27182. }
  27183. }
  27184. return null;
  27185. };
  27186. /**
  27187. * Gets a boolean indicating if the given mesh is active
  27188. * @param mesh defines the mesh to look for
  27189. * @returns true if the mesh is in the active list
  27190. */
  27191. Scene.prototype.isActiveMesh = function (mesh) {
  27192. return (this._activeMeshes.indexOf(mesh) !== -1);
  27193. };
  27194. Object.defineProperty(Scene.prototype, "uid", {
  27195. /**
  27196. * Return a unique id as a string which can serve as an identifier for the scene
  27197. */
  27198. get: function () {
  27199. if (!this._uid) {
  27200. this._uid = BABYLON.Tools.RandomId();
  27201. }
  27202. return this._uid;
  27203. },
  27204. enumerable: true,
  27205. configurable: true
  27206. });
  27207. /**
  27208. * Add an externaly attached data from its key.
  27209. * This method call will fail and return false, if such key already exists.
  27210. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27211. * @param key the unique key that identifies the data
  27212. * @param data the data object to associate to the key for this Engine instance
  27213. * @return true if no such key were already present and the data was added successfully, false otherwise
  27214. */
  27215. Scene.prototype.addExternalData = function (key, data) {
  27216. if (!this._externalData) {
  27217. this._externalData = new BABYLON.StringDictionary();
  27218. }
  27219. return this._externalData.add(key, data);
  27220. };
  27221. /**
  27222. * Get an externaly attached data from its key
  27223. * @param key the unique key that identifies the data
  27224. * @return the associated data, if present (can be null), or undefined if not present
  27225. */
  27226. Scene.prototype.getExternalData = function (key) {
  27227. if (!this._externalData) {
  27228. return null;
  27229. }
  27230. return this._externalData.get(key);
  27231. };
  27232. /**
  27233. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27234. * @param key the unique key that identifies the data
  27235. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27236. * @return the associated data, can be null if the factory returned null.
  27237. */
  27238. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27239. if (!this._externalData) {
  27240. this._externalData = new BABYLON.StringDictionary();
  27241. }
  27242. return this._externalData.getOrAddWithFactory(key, factory);
  27243. };
  27244. /**
  27245. * Remove an externaly attached data from the Engine instance
  27246. * @param key the unique key that identifies the data
  27247. * @return true if the data was successfully removed, false if it doesn't exist
  27248. */
  27249. Scene.prototype.removeExternalData = function (key) {
  27250. return this._externalData.remove(key);
  27251. };
  27252. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27253. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27254. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27255. var step = _a[_i];
  27256. step.action(mesh, subMesh);
  27257. }
  27258. var material = subMesh.getMaterial();
  27259. if (material !== null && material !== undefined) {
  27260. // Render targets
  27261. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27262. if (this._processedMaterials.indexOf(material) === -1) {
  27263. this._processedMaterials.push(material);
  27264. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27265. }
  27266. }
  27267. // Dispatch
  27268. this._activeIndices.addCount(subMesh.indexCount, false);
  27269. this._renderingManager.dispatch(subMesh, mesh, material);
  27270. }
  27271. }
  27272. };
  27273. /**
  27274. * Clear the processed materials smart array preventing retention point in material dispose.
  27275. */
  27276. Scene.prototype.freeProcessedMaterials = function () {
  27277. this._processedMaterials.dispose();
  27278. };
  27279. /**
  27280. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27281. */
  27282. Scene.prototype.freeActiveMeshes = function () {
  27283. this._activeMeshes.dispose();
  27284. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27285. this.activeCamera._activeMeshes.dispose();
  27286. }
  27287. if (this.activeCameras) {
  27288. for (var i = 0; i < this.activeCameras.length; i++) {
  27289. var activeCamera = this.activeCameras[i];
  27290. if (activeCamera && activeCamera._activeMeshes) {
  27291. activeCamera._activeMeshes.dispose();
  27292. }
  27293. }
  27294. }
  27295. };
  27296. /**
  27297. * Clear the info related to rendering groups preventing retention points during dispose.
  27298. */
  27299. Scene.prototype.freeRenderingGroups = function () {
  27300. if (this._renderingManager) {
  27301. this._renderingManager.freeRenderingGroups();
  27302. }
  27303. if (this.textures) {
  27304. for (var i = 0; i < this.textures.length; i++) {
  27305. var texture = this.textures[i];
  27306. if (texture && texture.renderList) {
  27307. texture.freeRenderingGroups();
  27308. }
  27309. }
  27310. }
  27311. };
  27312. /** @hidden */
  27313. Scene.prototype._isInIntermediateRendering = function () {
  27314. return this._intermediateRendering;
  27315. };
  27316. /**
  27317. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27318. * @returns the current scene
  27319. */
  27320. Scene.prototype.freezeActiveMeshes = function () {
  27321. if (!this.activeCamera) {
  27322. return this;
  27323. }
  27324. if (!this._frustumPlanes) {
  27325. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27326. }
  27327. this._evaluateActiveMeshes();
  27328. this._activeMeshesFrozen = true;
  27329. return this;
  27330. };
  27331. /**
  27332. * Use this function to restart evaluating active meshes on every frame
  27333. * @returns the current scene
  27334. */
  27335. Scene.prototype.unfreezeActiveMeshes = function () {
  27336. this._activeMeshesFrozen = false;
  27337. return this;
  27338. };
  27339. Scene.prototype._evaluateActiveMeshes = function () {
  27340. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27341. return;
  27342. }
  27343. if (!this.activeCamera) {
  27344. return;
  27345. }
  27346. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27347. this.activeCamera._activeMeshes.reset();
  27348. this._activeMeshes.reset();
  27349. this._renderingManager.reset();
  27350. this._processedMaterials.reset();
  27351. this._activeParticleSystems.reset();
  27352. this._activeSkeletons.reset();
  27353. this._softwareSkinnedMeshes.reset();
  27354. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27355. var step = _a[_i];
  27356. step.action();
  27357. }
  27358. // Determine mesh candidates
  27359. var meshes = this.getActiveMeshCandidates();
  27360. // Check each mesh
  27361. var len = meshes.length;
  27362. for (var i = 0; i < len; i++) {
  27363. var mesh = meshes.data[i];
  27364. if (mesh.isBlocked) {
  27365. continue;
  27366. }
  27367. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27368. if (!mesh.isReady() || !mesh.isEnabled()) {
  27369. continue;
  27370. }
  27371. mesh.computeWorldMatrix();
  27372. // Intersections
  27373. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27374. this._meshesForIntersections.pushNoDuplicate(mesh);
  27375. }
  27376. // Switch to current LOD
  27377. var meshLOD = mesh.getLOD(this.activeCamera);
  27378. if (meshLOD === undefined || meshLOD === null) {
  27379. continue;
  27380. }
  27381. mesh._preActivate();
  27382. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27383. this._activeMeshes.push(mesh);
  27384. this.activeCamera._activeMeshes.push(mesh);
  27385. mesh._activate(this._renderId);
  27386. if (meshLOD !== mesh) {
  27387. meshLOD._activate(this._renderId);
  27388. }
  27389. this._activeMesh(mesh, meshLOD);
  27390. }
  27391. }
  27392. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27393. // Particle systems
  27394. if (this.particlesEnabled) {
  27395. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27396. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27397. var particleSystem = this.particleSystems[particleIndex];
  27398. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27399. continue;
  27400. }
  27401. var emitter = particleSystem.emitter;
  27402. if (!emitter.position || emitter.isEnabled()) {
  27403. this._activeParticleSystems.push(particleSystem);
  27404. particleSystem.animate();
  27405. this._renderingManager.dispatchParticles(particleSystem);
  27406. }
  27407. }
  27408. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27409. }
  27410. };
  27411. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27412. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27413. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27414. mesh.skeleton.prepare();
  27415. }
  27416. if (!mesh.computeBonesUsingShaders) {
  27417. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27418. }
  27419. }
  27420. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27421. var step = _a[_i];
  27422. step.action(sourceMesh, mesh);
  27423. }
  27424. if (mesh !== undefined && mesh !== null
  27425. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27426. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27427. var len = subMeshes.length;
  27428. for (var i = 0; i < len; i++) {
  27429. var subMesh = subMeshes.data[i];
  27430. this._evaluateSubMesh(subMesh, mesh);
  27431. }
  27432. }
  27433. };
  27434. /**
  27435. * Update the transform matrix to update from the current active camera
  27436. * @param force defines a boolean used to force the update even if cache is up to date
  27437. */
  27438. Scene.prototype.updateTransformMatrix = function (force) {
  27439. if (!this.activeCamera) {
  27440. return;
  27441. }
  27442. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27443. };
  27444. /**
  27445. * 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)
  27446. * @param alternateCamera defines the camera to use
  27447. */
  27448. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27449. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27450. };
  27451. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27452. if (camera && camera._skipRendering) {
  27453. return;
  27454. }
  27455. var engine = this._engine;
  27456. this.activeCamera = camera;
  27457. if (!this.activeCamera)
  27458. throw new Error("Active camera not set");
  27459. // Viewport
  27460. engine.setViewport(this.activeCamera.viewport);
  27461. // Camera
  27462. this.resetCachedMaterial();
  27463. this._renderId++;
  27464. this.updateTransformMatrix();
  27465. if (camera._alternateCamera) {
  27466. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27467. this._alternateRendering = true;
  27468. }
  27469. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27470. // Meshes
  27471. this._evaluateActiveMeshes();
  27472. // Software skinning
  27473. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27474. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27475. mesh.applySkeleton(mesh.skeleton);
  27476. }
  27477. // Render targets
  27478. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27479. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27480. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27481. }
  27482. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27483. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27484. }
  27485. // Collects render targets from external components.
  27486. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27487. var step = _a[_i];
  27488. step.action(this._renderTargets);
  27489. }
  27490. if (this.renderTargetsEnabled) {
  27491. this._intermediateRendering = true;
  27492. if (this._renderTargets.length > 0) {
  27493. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27494. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27495. var renderTarget = this._renderTargets.data[renderIndex];
  27496. if (renderTarget._shouldRender()) {
  27497. this._renderId++;
  27498. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27499. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27500. }
  27501. }
  27502. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27503. this._renderId++;
  27504. }
  27505. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27506. var step = _c[_b];
  27507. step.action(this.activeCamera);
  27508. }
  27509. this._intermediateRendering = false;
  27510. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27511. }
  27512. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27513. // Prepare Frame
  27514. if (this.postProcessManager) {
  27515. this.postProcessManager._prepareFrame();
  27516. }
  27517. // Before Camera Draw
  27518. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27519. var step = _e[_d];
  27520. step.action(this.activeCamera);
  27521. }
  27522. // Render
  27523. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27524. this._renderingManager.render(null, null, true, true);
  27525. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27526. // After Camera Draw
  27527. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27528. var step = _g[_f];
  27529. step.action(this.activeCamera);
  27530. }
  27531. // Finalize frame
  27532. if (this.postProcessManager) {
  27533. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27534. }
  27535. // Reset some special arrays
  27536. this._renderTargets.reset();
  27537. this._alternateRendering = false;
  27538. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27539. };
  27540. Scene.prototype._processSubCameras = function (camera) {
  27541. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27542. this._renderForCamera(camera);
  27543. return;
  27544. }
  27545. // rig cameras
  27546. for (var index = 0; index < camera._rigCameras.length; index++) {
  27547. this._renderForCamera(camera._rigCameras[index], camera);
  27548. }
  27549. this.activeCamera = camera;
  27550. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27551. };
  27552. Scene.prototype._checkIntersections = function () {
  27553. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27554. var sourceMesh = this._meshesForIntersections.data[index];
  27555. if (!sourceMesh.actionManager) {
  27556. continue;
  27557. }
  27558. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27559. var action = sourceMesh.actionManager.actions[actionIndex];
  27560. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27561. var parameters = action.getTriggerParameter();
  27562. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27563. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27564. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27565. if (areIntersecting && currentIntersectionInProgress === -1) {
  27566. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27567. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27568. sourceMesh._intersectionsInProgress.push(otherMesh);
  27569. }
  27570. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27571. sourceMesh._intersectionsInProgress.push(otherMesh);
  27572. }
  27573. }
  27574. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27575. //They intersected, and now they don't.
  27576. //is this trigger an exit trigger? execute an event.
  27577. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27578. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27579. }
  27580. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27581. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27582. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27583. return otherMesh === parameterMesh;
  27584. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27585. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27586. }
  27587. }
  27588. }
  27589. }
  27590. }
  27591. };
  27592. /** @hidden */
  27593. Scene.prototype._advancePhysicsEngineStep = function (step) {
  27594. // Do nothing. Code will be replaced if physics engine component is referenced
  27595. };
  27596. /**
  27597. * Render the scene
  27598. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27599. */
  27600. Scene.prototype.render = function (updateCameras) {
  27601. if (updateCameras === void 0) { updateCameras = true; }
  27602. if (this.isDisposed) {
  27603. return;
  27604. }
  27605. this._frameId++;
  27606. // Register components that have been associated lately to the scene.
  27607. this._registerTransientComponents();
  27608. this._activeParticles.fetchNewFrame();
  27609. this._totalVertices.fetchNewFrame();
  27610. this._activeIndices.fetchNewFrame();
  27611. this._activeBones.fetchNewFrame();
  27612. this._meshesForIntersections.reset();
  27613. this.resetCachedMaterial();
  27614. this.onBeforeAnimationsObservable.notifyObservers(this);
  27615. // Actions
  27616. if (this.actionManager) {
  27617. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27618. }
  27619. if (this._engine.isDeterministicLockStep()) {
  27620. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27621. var defaultFPS = (60.0 / 1000.0);
  27622. var defaultFrameTime = this.getDeterministicFrameTime();
  27623. var stepsTaken = 0;
  27624. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27625. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27626. internalSteps = Math.min(internalSteps, maxSubSteps);
  27627. do {
  27628. this.onBeforeStepObservable.notifyObservers(this);
  27629. // Animations
  27630. this._animationRatio = defaultFrameTime * defaultFPS;
  27631. this._animate();
  27632. this.onAfterAnimationsObservable.notifyObservers(this);
  27633. // Physics
  27634. this._advancePhysicsEngineStep(defaultFrameTime);
  27635. this.onAfterStepObservable.notifyObservers(this);
  27636. this._currentStepId++;
  27637. stepsTaken++;
  27638. deltaTime -= defaultFrameTime;
  27639. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27640. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27641. }
  27642. else {
  27643. // Animations
  27644. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27645. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27646. this._animate();
  27647. this.onAfterAnimationsObservable.notifyObservers(this);
  27648. // Physics
  27649. this._advancePhysicsEngineStep(deltaTime);
  27650. }
  27651. // Before camera update steps
  27652. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27653. var step = _a[_i];
  27654. step.action();
  27655. }
  27656. // Update Cameras
  27657. if (updateCameras) {
  27658. if (this.activeCameras.length > 0) {
  27659. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27660. var camera = this.activeCameras[cameraIndex];
  27661. camera.update();
  27662. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27663. // rig cameras
  27664. for (var index = 0; index < camera._rigCameras.length; index++) {
  27665. camera._rigCameras[index].update();
  27666. }
  27667. }
  27668. }
  27669. }
  27670. else if (this.activeCamera) {
  27671. this.activeCamera.update();
  27672. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27673. // rig cameras
  27674. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27675. this.activeCamera._rigCameras[index].update();
  27676. }
  27677. }
  27678. }
  27679. }
  27680. // Before render
  27681. this.onBeforeRenderObservable.notifyObservers(this);
  27682. // Customs render targets
  27683. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27684. var engine = this.getEngine();
  27685. var currentActiveCamera = this.activeCamera;
  27686. if (this.renderTargetsEnabled) {
  27687. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27688. this._intermediateRendering = true;
  27689. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27690. var renderTarget = this.customRenderTargets[customIndex];
  27691. if (renderTarget._shouldRender()) {
  27692. this._renderId++;
  27693. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27694. if (!this.activeCamera)
  27695. throw new Error("Active camera not set");
  27696. // Viewport
  27697. engine.setViewport(this.activeCamera.viewport);
  27698. // Camera
  27699. this.updateTransformMatrix();
  27700. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27701. }
  27702. }
  27703. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27704. this._intermediateRendering = false;
  27705. this._renderId++;
  27706. }
  27707. // Restore back buffer
  27708. if (this.customRenderTargets.length > 0) {
  27709. engine.restoreDefaultFramebuffer();
  27710. }
  27711. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27712. this.activeCamera = currentActiveCamera;
  27713. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  27714. var step = _c[_b];
  27715. step.action();
  27716. }
  27717. // Clear
  27718. if (this.autoClearDepthAndStencil || this.autoClear) {
  27719. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27720. }
  27721. // Collects render targets from external components.
  27722. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  27723. var step = _e[_d];
  27724. step.action(this._renderTargets);
  27725. }
  27726. // Multi-cameras?
  27727. if (this.activeCameras.length > 0) {
  27728. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27729. if (cameraIndex > 0) {
  27730. this._engine.clear(null, false, true, true);
  27731. }
  27732. this._processSubCameras(this.activeCameras[cameraIndex]);
  27733. }
  27734. }
  27735. else {
  27736. if (!this.activeCamera) {
  27737. throw new Error("No camera defined");
  27738. }
  27739. this._processSubCameras(this.activeCamera);
  27740. }
  27741. // Intersection checks
  27742. this._checkIntersections();
  27743. // Executes the after render stage actions.
  27744. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  27745. var step = _g[_f];
  27746. step.action();
  27747. }
  27748. // After render
  27749. if (this.afterRender) {
  27750. this.afterRender();
  27751. }
  27752. this.onAfterRenderObservable.notifyObservers(this);
  27753. // Cleaning
  27754. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27755. var data = this._toBeDisposed.data[index];
  27756. if (data) {
  27757. data.dispose();
  27758. }
  27759. }
  27760. this._toBeDisposed.reset();
  27761. if (this.dumpNextRenderTargets) {
  27762. this.dumpNextRenderTargets = false;
  27763. }
  27764. this._activeBones.addCount(0, true);
  27765. this._activeIndices.addCount(0, true);
  27766. this._activeParticles.addCount(0, true);
  27767. };
  27768. /**
  27769. * Freeze all materials
  27770. * A frozen material will not be updatable but should be faster to render
  27771. */
  27772. Scene.prototype.freezeMaterials = function () {
  27773. for (var i = 0; i < this.materials.length; i++) {
  27774. this.materials[i].freeze();
  27775. }
  27776. };
  27777. /**
  27778. * Unfreeze all materials
  27779. * A frozen material will not be updatable but should be faster to render
  27780. */
  27781. Scene.prototype.unfreezeMaterials = function () {
  27782. for (var i = 0; i < this.materials.length; i++) {
  27783. this.materials[i].unfreeze();
  27784. }
  27785. };
  27786. /**
  27787. * Releases all held ressources
  27788. */
  27789. Scene.prototype.dispose = function () {
  27790. this.beforeRender = null;
  27791. this.afterRender = null;
  27792. this.skeletons = [];
  27793. this.morphTargetManagers = [];
  27794. this._transientComponents = [];
  27795. this._isReadyForMeshStage.clear();
  27796. this._beforeEvaluateActiveMeshStage.clear();
  27797. this._evaluateSubMeshStage.clear();
  27798. this._activeMeshStage.clear();
  27799. this._cameraDrawRenderTargetStage.clear();
  27800. this._beforeCameraDrawStage.clear();
  27801. this._beforeRenderingGroupDrawStage.clear();
  27802. this._beforeRenderingMeshStage.clear();
  27803. this._afterRenderingMeshStage.clear();
  27804. this._afterRenderingGroupDrawStage.clear();
  27805. this._afterCameraDrawStage.clear();
  27806. this._afterRenderStage.clear();
  27807. this._beforeCameraUpdateStage.clear();
  27808. this._beforeClearStage.clear();
  27809. this._gatherRenderTargetsStage.clear();
  27810. this._gatherActiveCameraRenderTargetsStage.clear();
  27811. this._pointerMoveStage.clear();
  27812. this._pointerDownStage.clear();
  27813. this._pointerUpStage.clear();
  27814. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27815. var component = _a[_i];
  27816. component.dispose();
  27817. }
  27818. this.importedMeshesFiles = new Array();
  27819. this.stopAllAnimations();
  27820. this.resetCachedMaterial();
  27821. // Smart arrays
  27822. if (this.activeCamera) {
  27823. this.activeCamera._activeMeshes.dispose();
  27824. this.activeCamera = null;
  27825. }
  27826. this._activeMeshes.dispose();
  27827. this._renderingManager.dispose();
  27828. this._processedMaterials.dispose();
  27829. this._activeParticleSystems.dispose();
  27830. this._activeSkeletons.dispose();
  27831. this._softwareSkinnedMeshes.dispose();
  27832. this._renderTargets.dispose();
  27833. this._registeredForLateAnimationBindings.dispose();
  27834. this._meshesForIntersections.dispose();
  27835. this._toBeDisposed.dispose();
  27836. // Abort active requests
  27837. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27838. var request = _c[_b];
  27839. request.abort();
  27840. }
  27841. // Events
  27842. this.onDisposeObservable.notifyObservers(this);
  27843. this.onDisposeObservable.clear();
  27844. this.onBeforeRenderObservable.clear();
  27845. this.onAfterRenderObservable.clear();
  27846. this.onBeforeRenderTargetsRenderObservable.clear();
  27847. this.onAfterRenderTargetsRenderObservable.clear();
  27848. this.onAfterStepObservable.clear();
  27849. this.onBeforeStepObservable.clear();
  27850. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27851. this.onAfterActiveMeshesEvaluationObservable.clear();
  27852. this.onBeforeParticlesRenderingObservable.clear();
  27853. this.onAfterParticlesRenderingObservable.clear();
  27854. this.onBeforeDrawPhaseObservable.clear();
  27855. this.onAfterDrawPhaseObservable.clear();
  27856. this.onBeforeAnimationsObservable.clear();
  27857. this.onAfterAnimationsObservable.clear();
  27858. this.onDataLoadedObservable.clear();
  27859. this.onBeforeRenderingGroupObservable.clear();
  27860. this.onAfterRenderingGroupObservable.clear();
  27861. this.onMeshImportedObservable.clear();
  27862. this.detachControl();
  27863. // Detach cameras
  27864. var canvas = this._engine.getRenderingCanvas();
  27865. if (canvas) {
  27866. var index;
  27867. for (index = 0; index < this.cameras.length; index++) {
  27868. this.cameras[index].detachControl(canvas);
  27869. }
  27870. }
  27871. // Release animation groups
  27872. while (this.animationGroups.length) {
  27873. this.animationGroups[0].dispose();
  27874. }
  27875. // Release lights
  27876. while (this.lights.length) {
  27877. this.lights[0].dispose();
  27878. }
  27879. // Release meshes
  27880. while (this.meshes.length) {
  27881. this.meshes[0].dispose(true);
  27882. }
  27883. while (this.transformNodes.length) {
  27884. this.removeTransformNode(this.transformNodes[0]);
  27885. }
  27886. // Release cameras
  27887. while (this.cameras.length) {
  27888. this.cameras[0].dispose();
  27889. }
  27890. // Release materials
  27891. if (this.defaultMaterial) {
  27892. this.defaultMaterial.dispose();
  27893. }
  27894. while (this.multiMaterials.length) {
  27895. this.multiMaterials[0].dispose();
  27896. }
  27897. while (this.materials.length) {
  27898. this.materials[0].dispose();
  27899. }
  27900. // Release particles
  27901. while (this.particleSystems.length) {
  27902. this.particleSystems[0].dispose();
  27903. }
  27904. // Release postProcesses
  27905. while (this.postProcesses.length) {
  27906. this.postProcesses[0].dispose();
  27907. }
  27908. // Release textures
  27909. while (this.textures.length) {
  27910. this.textures[0].dispose();
  27911. }
  27912. // Release UBO
  27913. this._sceneUbo.dispose();
  27914. if (this._alternateSceneUbo) {
  27915. this._alternateSceneUbo.dispose();
  27916. }
  27917. // Post-processes
  27918. this.postProcessManager.dispose();
  27919. // Remove from engine
  27920. index = this._engine.scenes.indexOf(this);
  27921. if (index > -1) {
  27922. this._engine.scenes.splice(index, 1);
  27923. }
  27924. this._engine.wipeCaches(true);
  27925. this._isDisposed = true;
  27926. };
  27927. Object.defineProperty(Scene.prototype, "isDisposed", {
  27928. /**
  27929. * Gets if the scene is already disposed
  27930. */
  27931. get: function () {
  27932. return this._isDisposed;
  27933. },
  27934. enumerable: true,
  27935. configurable: true
  27936. });
  27937. /**
  27938. * Call this function to reduce memory footprint of the scene.
  27939. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  27940. */
  27941. Scene.prototype.clearCachedVertexData = function () {
  27942. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27943. var mesh = this.meshes[meshIndex];
  27944. var geometry = mesh.geometry;
  27945. if (geometry) {
  27946. geometry._indices = [];
  27947. for (var vbName in geometry._vertexBuffers) {
  27948. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  27949. continue;
  27950. }
  27951. geometry._vertexBuffers[vbName]._buffer._data = null;
  27952. }
  27953. }
  27954. }
  27955. };
  27956. /**
  27957. * This function will remove the local cached buffer data from texture.
  27958. * It will save memory but will prevent the texture from being rebuilt
  27959. */
  27960. Scene.prototype.cleanCachedTextureBuffer = function () {
  27961. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  27962. var baseTexture = _a[_i];
  27963. var buffer = baseTexture._buffer;
  27964. if (buffer) {
  27965. baseTexture._buffer = null;
  27966. }
  27967. }
  27968. };
  27969. /**
  27970. * Get the world extend vectors with an optional filter
  27971. *
  27972. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27973. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27974. */
  27975. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27976. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27977. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27978. filterPredicate = filterPredicate || (function () { return true; });
  27979. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27980. mesh.computeWorldMatrix(true);
  27981. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27982. return;
  27983. }
  27984. var boundingInfo = mesh.getBoundingInfo();
  27985. var minBox = boundingInfo.boundingBox.minimumWorld;
  27986. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27987. BABYLON.Tools.CheckExtends(minBox, min, max);
  27988. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27989. });
  27990. return {
  27991. min: min,
  27992. max: max
  27993. };
  27994. };
  27995. // Picking
  27996. /**
  27997. * Creates a ray that can be used to pick in the scene
  27998. * @param x defines the x coordinate of the origin (on-screen)
  27999. * @param y defines the y coordinate of the origin (on-screen)
  28000. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28001. * @param camera defines the camera to use for the picking
  28002. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28003. * @returns a Ray
  28004. */
  28005. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28006. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28007. var result = BABYLON.Ray.Zero();
  28008. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28009. return result;
  28010. };
  28011. /**
  28012. * Creates a ray that can be used to pick in the scene
  28013. * @param x defines the x coordinate of the origin (on-screen)
  28014. * @param y defines the y coordinate of the origin (on-screen)
  28015. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28016. * @param result defines the ray where to store the picking ray
  28017. * @param camera defines the camera to use for the picking
  28018. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28019. * @returns the current scene
  28020. */
  28021. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28022. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28023. var engine = this._engine;
  28024. if (!camera) {
  28025. if (!this.activeCamera)
  28026. throw new Error("Active camera not set");
  28027. camera = this.activeCamera;
  28028. }
  28029. var cameraViewport = camera.viewport;
  28030. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28031. // Moving coordinates to local viewport world
  28032. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28033. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28034. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28035. return this;
  28036. };
  28037. /**
  28038. * Creates a ray that can be used to pick in the scene
  28039. * @param x defines the x coordinate of the origin (on-screen)
  28040. * @param y defines the y coordinate of the origin (on-screen)
  28041. * @param camera defines the camera to use for the picking
  28042. * @returns a Ray
  28043. */
  28044. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28045. var result = BABYLON.Ray.Zero();
  28046. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28047. return result;
  28048. };
  28049. /**
  28050. * Creates a ray that can be used to pick in the scene
  28051. * @param x defines the x coordinate of the origin (on-screen)
  28052. * @param y defines the y coordinate of the origin (on-screen)
  28053. * @param result defines the ray where to store the picking ray
  28054. * @param camera defines the camera to use for the picking
  28055. * @returns the current scene
  28056. */
  28057. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28058. if (!BABYLON.PickingInfo) {
  28059. return this;
  28060. }
  28061. var engine = this._engine;
  28062. if (!camera) {
  28063. if (!this.activeCamera)
  28064. throw new Error("Active camera not set");
  28065. camera = this.activeCamera;
  28066. }
  28067. var cameraViewport = camera.viewport;
  28068. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28069. var identity = BABYLON.Matrix.Identity();
  28070. // Moving coordinates to local viewport world
  28071. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28072. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28073. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28074. return this;
  28075. };
  28076. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28077. if (!BABYLON.PickingInfo) {
  28078. return null;
  28079. }
  28080. var pickingInfo = null;
  28081. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28082. var mesh = this.meshes[meshIndex];
  28083. if (predicate) {
  28084. if (!predicate(mesh)) {
  28085. continue;
  28086. }
  28087. }
  28088. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28089. continue;
  28090. }
  28091. var world = mesh.getWorldMatrix();
  28092. var ray = rayFunction(world);
  28093. var result = mesh.intersects(ray, fastCheck);
  28094. if (!result || !result.hit)
  28095. continue;
  28096. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28097. continue;
  28098. pickingInfo = result;
  28099. if (fastCheck) {
  28100. break;
  28101. }
  28102. }
  28103. return pickingInfo || new BABYLON.PickingInfo();
  28104. };
  28105. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28106. if (!BABYLON.PickingInfo) {
  28107. return null;
  28108. }
  28109. var pickingInfos = new Array();
  28110. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28111. var mesh = this.meshes[meshIndex];
  28112. if (predicate) {
  28113. if (!predicate(mesh)) {
  28114. continue;
  28115. }
  28116. }
  28117. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28118. continue;
  28119. }
  28120. var world = mesh.getWorldMatrix();
  28121. var ray = rayFunction(world);
  28122. var result = mesh.intersects(ray, false);
  28123. if (!result || !result.hit)
  28124. continue;
  28125. pickingInfos.push(result);
  28126. }
  28127. return pickingInfos;
  28128. };
  28129. /** Launch a ray to try to pick a mesh in the scene
  28130. * @param x position on screen
  28131. * @param y position on screen
  28132. * @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
  28133. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28134. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28135. * @returns a PickingInfo
  28136. */
  28137. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28138. var _this = this;
  28139. if (!BABYLON.PickingInfo) {
  28140. return null;
  28141. }
  28142. var result = this._internalPick(function (world) {
  28143. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28144. return _this._tempPickingRay;
  28145. }, predicate, fastCheck);
  28146. if (result) {
  28147. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28148. }
  28149. return result;
  28150. };
  28151. /** Use the given ray to pick a mesh in the scene
  28152. * @param ray The ray to use to pick meshes
  28153. * @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
  28154. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28155. * @returns a PickingInfo
  28156. */
  28157. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28158. var _this = this;
  28159. var result = this._internalPick(function (world) {
  28160. if (!_this._pickWithRayInverseMatrix) {
  28161. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28162. }
  28163. world.invertToRef(_this._pickWithRayInverseMatrix);
  28164. if (!_this._cachedRayForTransform) {
  28165. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28166. }
  28167. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28168. return _this._cachedRayForTransform;
  28169. }, predicate, fastCheck);
  28170. if (result) {
  28171. result.ray = ray;
  28172. }
  28173. return result;
  28174. };
  28175. /**
  28176. * Launch a ray to try to pick a mesh in the scene
  28177. * @param x X position on screen
  28178. * @param y Y position on screen
  28179. * @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
  28180. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28181. * @returns an array of PickingInfo
  28182. */
  28183. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28184. var _this = this;
  28185. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28186. };
  28187. /**
  28188. * Launch a ray to try to pick a mesh in the scene
  28189. * @param ray Ray to use
  28190. * @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
  28191. * @returns an array of PickingInfo
  28192. */
  28193. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28194. var _this = this;
  28195. return this._internalMultiPick(function (world) {
  28196. if (!_this._pickWithRayInverseMatrix) {
  28197. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28198. }
  28199. world.invertToRef(_this._pickWithRayInverseMatrix);
  28200. if (!_this._cachedRayForTransform) {
  28201. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28202. }
  28203. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28204. return _this._cachedRayForTransform;
  28205. }, predicate);
  28206. };
  28207. /**
  28208. * Force the value of meshUnderPointer
  28209. * @param mesh defines the mesh to use
  28210. */
  28211. Scene.prototype.setPointerOverMesh = function (mesh) {
  28212. if (this._pointerOverMesh === mesh) {
  28213. return;
  28214. }
  28215. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28216. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28217. }
  28218. this._pointerOverMesh = mesh;
  28219. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28220. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28221. }
  28222. };
  28223. /**
  28224. * Gets the mesh under the pointer
  28225. * @returns a Mesh or null if no mesh is under the pointer
  28226. */
  28227. Scene.prototype.getPointerOverMesh = function () {
  28228. return this._pointerOverMesh;
  28229. };
  28230. // Misc.
  28231. /** @hidden */
  28232. Scene.prototype._rebuildGeometries = function () {
  28233. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28234. var geometry = _a[_i];
  28235. geometry._rebuild();
  28236. }
  28237. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28238. var mesh = _c[_b];
  28239. mesh._rebuild();
  28240. }
  28241. if (this.postProcessManager) {
  28242. this.postProcessManager._rebuild();
  28243. }
  28244. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28245. var component = _e[_d];
  28246. component.rebuild();
  28247. }
  28248. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28249. var system = _g[_f];
  28250. system.rebuild();
  28251. }
  28252. };
  28253. /** @hidden */
  28254. Scene.prototype._rebuildTextures = function () {
  28255. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28256. var texture = _a[_i];
  28257. texture._rebuild();
  28258. }
  28259. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28260. };
  28261. // Tags
  28262. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28263. if (tagsQuery === undefined) {
  28264. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28265. return list;
  28266. }
  28267. var listByTags = [];
  28268. forEach = forEach || (function (item) { return; });
  28269. for (var i in list) {
  28270. var item = list[i];
  28271. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28272. listByTags.push(item);
  28273. forEach(item);
  28274. }
  28275. }
  28276. return listByTags;
  28277. };
  28278. /**
  28279. * Get a list of meshes by tags
  28280. * @param tagsQuery defines the tags query to use
  28281. * @param forEach defines a predicate used to filter results
  28282. * @returns an array of Mesh
  28283. */
  28284. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28285. return this._getByTags(this.meshes, tagsQuery, forEach);
  28286. };
  28287. /**
  28288. * Get a list of cameras by tags
  28289. * @param tagsQuery defines the tags query to use
  28290. * @param forEach defines a predicate used to filter results
  28291. * @returns an array of Camera
  28292. */
  28293. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28294. return this._getByTags(this.cameras, tagsQuery, forEach);
  28295. };
  28296. /**
  28297. * Get a list of lights by tags
  28298. * @param tagsQuery defines the tags query to use
  28299. * @param forEach defines a predicate used to filter results
  28300. * @returns an array of Light
  28301. */
  28302. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28303. return this._getByTags(this.lights, tagsQuery, forEach);
  28304. };
  28305. /**
  28306. * Get a list of materials by tags
  28307. * @param tagsQuery defines the tags query to use
  28308. * @param forEach defines a predicate used to filter results
  28309. * @returns an array of Material
  28310. */
  28311. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28312. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28313. };
  28314. /**
  28315. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28316. * This allowed control for front to back rendering or reversly depending of the special needs.
  28317. *
  28318. * @param renderingGroupId The rendering group id corresponding to its index
  28319. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28320. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28321. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28322. */
  28323. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28324. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28325. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28326. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28327. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28328. };
  28329. /**
  28330. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28331. *
  28332. * @param renderingGroupId The rendering group id corresponding to its index
  28333. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28334. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28335. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28336. */
  28337. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28338. if (depth === void 0) { depth = true; }
  28339. if (stencil === void 0) { stencil = true; }
  28340. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28341. };
  28342. /**
  28343. * Gets the current auto clear configuration for one rendering group of the rendering
  28344. * manager.
  28345. * @param index the rendering group index to get the information for
  28346. * @returns The auto clear setup for the requested rendering group
  28347. */
  28348. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28349. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28350. };
  28351. /**
  28352. * Will flag all materials as dirty to trigger new shader compilation
  28353. * @param flag defines the flag used to specify which material part must be marked as dirty
  28354. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28355. */
  28356. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28357. if (this.blockMaterialDirtyMechanism) {
  28358. return;
  28359. }
  28360. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28361. var material = _a[_i];
  28362. if (predicate && !predicate(material)) {
  28363. continue;
  28364. }
  28365. material.markAsDirty(flag);
  28366. }
  28367. };
  28368. /** @hidden */
  28369. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28370. var _this = this;
  28371. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28372. this._activeRequests.push(request);
  28373. request.onCompleteObservable.add(function (request) {
  28374. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28375. });
  28376. return request;
  28377. };
  28378. /** @hidden */
  28379. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28380. var _this = this;
  28381. return new Promise(function (resolve, reject) {
  28382. _this._loadFile(url, function (data) {
  28383. resolve(data);
  28384. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28385. reject(exception);
  28386. });
  28387. });
  28388. };
  28389. // Statics
  28390. Scene._uniqueIdCounter = 0;
  28391. /** The fog is deactivated */
  28392. Scene.FOGMODE_NONE = 0;
  28393. /** The fog density is following an exponential function */
  28394. Scene.FOGMODE_EXP = 1;
  28395. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28396. Scene.FOGMODE_EXP2 = 2;
  28397. /** The fog density is following a linear function. */
  28398. Scene.FOGMODE_LINEAR = 3;
  28399. /**
  28400. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28401. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28402. */
  28403. Scene.MinDeltaTime = 1.0;
  28404. /**
  28405. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28406. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28407. */
  28408. Scene.MaxDeltaTime = 1000.0;
  28409. /** The distance in pixel that you have to move to prevent some events */
  28410. Scene.DragMovementThreshold = 10; // in pixels
  28411. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28412. Scene.LongPressDelay = 500; // in milliseconds
  28413. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28414. Scene.DoubleClickDelay = 300; // in milliseconds
  28415. /** If you need to check double click without raising a single click at first click, enable this flag */
  28416. Scene.ExclusiveDoubleClickMode = false;
  28417. return Scene;
  28418. }(BABYLON.AbstractScene));
  28419. BABYLON.Scene = Scene;
  28420. })(BABYLON || (BABYLON = {}));
  28421. //# sourceMappingURL=babylon.scene.js.map
  28422. var BABYLON;
  28423. (function (BABYLON) {
  28424. /**
  28425. * Set of assets to keep when moving a scene into an asset container.
  28426. */
  28427. var KeepAssets = /** @class */ (function (_super) {
  28428. __extends(KeepAssets, _super);
  28429. function KeepAssets() {
  28430. return _super !== null && _super.apply(this, arguments) || this;
  28431. }
  28432. return KeepAssets;
  28433. }(BABYLON.AbstractScene));
  28434. BABYLON.KeepAssets = KeepAssets;
  28435. /**
  28436. * Container with a set of assets that can be added or removed from a scene.
  28437. */
  28438. var AssetContainer = /** @class */ (function (_super) {
  28439. __extends(AssetContainer, _super);
  28440. /**
  28441. * Instantiates an AssetContainer.
  28442. * @param scene The scene the AssetContainer belongs to.
  28443. */
  28444. function AssetContainer(scene) {
  28445. var _this = _super.call(this) || this;
  28446. _this.scene = scene;
  28447. return _this;
  28448. }
  28449. /**
  28450. * Adds all the assets from the container to the scene.
  28451. */
  28452. AssetContainer.prototype.addAllToScene = function () {
  28453. var _this = this;
  28454. this.cameras.forEach(function (o) {
  28455. _this.scene.addCamera(o);
  28456. });
  28457. this.lights.forEach(function (o) {
  28458. _this.scene.addLight(o);
  28459. });
  28460. this.meshes.forEach(function (o) {
  28461. _this.scene.addMesh(o);
  28462. });
  28463. this.skeletons.forEach(function (o) {
  28464. _this.scene.addSkeleton(o);
  28465. });
  28466. this.animations.forEach(function (o) {
  28467. _this.scene.addAnimation(o);
  28468. });
  28469. this.animationGroups.forEach(function (o) {
  28470. _this.scene.addAnimationGroup(o);
  28471. });
  28472. this.multiMaterials.forEach(function (o) {
  28473. _this.scene.addMultiMaterial(o);
  28474. });
  28475. this.materials.forEach(function (o) {
  28476. _this.scene.addMaterial(o);
  28477. });
  28478. this.morphTargetManagers.forEach(function (o) {
  28479. _this.scene.addMorphTargetManager(o);
  28480. });
  28481. this.geometries.forEach(function (o) {
  28482. _this.scene.addGeometry(o);
  28483. });
  28484. this.transformNodes.forEach(function (o) {
  28485. _this.scene.addTransformNode(o);
  28486. });
  28487. this.actionManagers.forEach(function (o) {
  28488. _this.scene.addActionManager(o);
  28489. });
  28490. this.textures.forEach(function (o) {
  28491. _this.scene.addTexture(o);
  28492. });
  28493. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28494. var component = _a[_i];
  28495. component.addFromContainer(this.scene);
  28496. }
  28497. };
  28498. /**
  28499. * Removes all the assets in the container from the scene
  28500. */
  28501. AssetContainer.prototype.removeAllFromScene = function () {
  28502. var _this = this;
  28503. this.cameras.forEach(function (o) {
  28504. _this.scene.removeCamera(o);
  28505. });
  28506. this.lights.forEach(function (o) {
  28507. _this.scene.removeLight(o);
  28508. });
  28509. this.meshes.forEach(function (o) {
  28510. _this.scene.removeMesh(o);
  28511. });
  28512. this.skeletons.forEach(function (o) {
  28513. _this.scene.removeSkeleton(o);
  28514. });
  28515. this.animations.forEach(function (o) {
  28516. _this.scene.removeAnimation(o);
  28517. });
  28518. this.animationGroups.forEach(function (o) {
  28519. _this.scene.removeAnimationGroup(o);
  28520. });
  28521. this.multiMaterials.forEach(function (o) {
  28522. _this.scene.removeMultiMaterial(o);
  28523. });
  28524. this.materials.forEach(function (o) {
  28525. _this.scene.removeMaterial(o);
  28526. });
  28527. this.morphTargetManagers.forEach(function (o) {
  28528. _this.scene.removeMorphTargetManager(o);
  28529. });
  28530. this.geometries.forEach(function (o) {
  28531. _this.scene.removeGeometry(o);
  28532. });
  28533. this.transformNodes.forEach(function (o) {
  28534. _this.scene.removeTransformNode(o);
  28535. });
  28536. this.actionManagers.forEach(function (o) {
  28537. _this.scene.removeActionManager(o);
  28538. });
  28539. this.textures.forEach(function (o) {
  28540. _this.scene.removeTexture(o);
  28541. });
  28542. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28543. var component = _a[_i];
  28544. component.removeFromContainer(this.scene);
  28545. }
  28546. };
  28547. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28548. if (!sourceAssets) {
  28549. return;
  28550. }
  28551. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28552. var asset = sourceAssets_1[_i];
  28553. var move = true;
  28554. if (keepAssets) {
  28555. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28556. var keepAsset = keepAssets_1[_a];
  28557. if (asset === keepAsset) {
  28558. move = false;
  28559. break;
  28560. }
  28561. }
  28562. }
  28563. if (move) {
  28564. targetAssets.push(asset);
  28565. }
  28566. }
  28567. };
  28568. /**
  28569. * Removes all the assets contained in the scene and adds them to the container.
  28570. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28571. */
  28572. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28573. if (keepAssets === undefined) {
  28574. keepAssets = new KeepAssets();
  28575. }
  28576. for (var key in this) {
  28577. if (this.hasOwnProperty(key)) {
  28578. this[key] = this[key] || [];
  28579. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28580. }
  28581. }
  28582. this.removeAllFromScene();
  28583. };
  28584. /**
  28585. * 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.
  28586. * @returns the root mesh
  28587. */
  28588. AssetContainer.prototype.createRootMesh = function () {
  28589. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28590. this.meshes.forEach(function (m) {
  28591. if (!m.parent) {
  28592. rootMesh.addChild(m);
  28593. }
  28594. });
  28595. this.meshes.unshift(rootMesh);
  28596. return rootMesh;
  28597. };
  28598. return AssetContainer;
  28599. }(BABYLON.AbstractScene));
  28600. BABYLON.AssetContainer = AssetContainer;
  28601. })(BABYLON || (BABYLON = {}));
  28602. //# sourceMappingURL=babylon.assetContainer.js.map
  28603. var BABYLON;
  28604. (function (BABYLON) {
  28605. var Buffer = /** @class */ (function () {
  28606. /**
  28607. * Constructor
  28608. * @param engine the engine
  28609. * @param data the data to use for this buffer
  28610. * @param updatable whether the data is updatable
  28611. * @param stride the stride (optional)
  28612. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28613. * @param instanced whether the buffer is instanced (optional)
  28614. * @param useBytes set to true if the stride in in bytes (optional)
  28615. */
  28616. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28617. if (stride === void 0) { stride = 0; }
  28618. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28619. if (instanced === void 0) { instanced = false; }
  28620. if (useBytes === void 0) { useBytes = false; }
  28621. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28622. this._engine = engine.getScene().getEngine();
  28623. }
  28624. else {
  28625. this._engine = engine;
  28626. }
  28627. this._updatable = updatable;
  28628. this._instanced = instanced;
  28629. this._data = data;
  28630. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28631. if (!postponeInternalCreation) { // by default
  28632. this.create();
  28633. }
  28634. }
  28635. /**
  28636. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28637. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28638. * @param offset defines offset in the buffer (0 by default)
  28639. * @param size defines the size in floats of attributes (position is 3 for instance)
  28640. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28641. * @param instanced defines if the vertex buffer contains indexed data
  28642. * @param useBytes defines if the offset and stride are in bytes
  28643. * @returns the new vertex buffer
  28644. */
  28645. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28646. if (useBytes === void 0) { useBytes = false; }
  28647. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28648. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28649. // a lot of these parameters are ignored as they are overriden by the buffer
  28650. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28651. };
  28652. // Properties
  28653. Buffer.prototype.isUpdatable = function () {
  28654. return this._updatable;
  28655. };
  28656. Buffer.prototype.getData = function () {
  28657. return this._data;
  28658. };
  28659. Buffer.prototype.getBuffer = function () {
  28660. return this._buffer;
  28661. };
  28662. /**
  28663. * Gets the stride in float32 units (i.e. byte stride / 4).
  28664. * May not be an integer if the byte stride is not divisible by 4.
  28665. * DEPRECATED. Use byteStride instead.
  28666. * @returns the stride in float32 units
  28667. */
  28668. Buffer.prototype.getStrideSize = function () {
  28669. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28670. };
  28671. // Methods
  28672. Buffer.prototype.create = function (data) {
  28673. if (data === void 0) { data = null; }
  28674. if (!data && this._buffer) {
  28675. return; // nothing to do
  28676. }
  28677. data = data || this._data;
  28678. if (!data) {
  28679. return;
  28680. }
  28681. if (!this._buffer) { // create buffer
  28682. if (this._updatable) {
  28683. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28684. this._data = data;
  28685. }
  28686. else {
  28687. this._buffer = this._engine.createVertexBuffer(data);
  28688. }
  28689. }
  28690. else if (this._updatable) { // update buffer
  28691. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28692. this._data = data;
  28693. }
  28694. };
  28695. /** @hidden */
  28696. Buffer.prototype._rebuild = function () {
  28697. this._buffer = null;
  28698. this.create(this._data);
  28699. };
  28700. Buffer.prototype.update = function (data) {
  28701. this.create(data);
  28702. };
  28703. /**
  28704. * Updates the data directly.
  28705. * @param data the new data
  28706. * @param offset the new offset
  28707. * @param vertexCount the vertex count (optional)
  28708. * @param useBytes set to true if the offset is in bytes
  28709. */
  28710. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28711. if (useBytes === void 0) { useBytes = false; }
  28712. if (!this._buffer) {
  28713. return;
  28714. }
  28715. if (this._updatable) { // update buffer
  28716. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28717. this._data = null;
  28718. }
  28719. };
  28720. Buffer.prototype.dispose = function () {
  28721. if (!this._buffer) {
  28722. return;
  28723. }
  28724. if (this._engine._releaseBuffer(this._buffer)) {
  28725. this._buffer = null;
  28726. }
  28727. };
  28728. return Buffer;
  28729. }());
  28730. BABYLON.Buffer = Buffer;
  28731. })(BABYLON || (BABYLON = {}));
  28732. //# sourceMappingURL=babylon.buffer.js.map
  28733. var BABYLON;
  28734. (function (BABYLON) {
  28735. var VertexBuffer = /** @class */ (function () {
  28736. /**
  28737. * Constructor
  28738. * @param engine the engine
  28739. * @param data the data to use for this vertex buffer
  28740. * @param kind the vertex buffer kind
  28741. * @param updatable whether the data is updatable
  28742. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28743. * @param stride the stride (optional)
  28744. * @param instanced whether the buffer is instanced (optional)
  28745. * @param offset the offset of the data (optional)
  28746. * @param size the number of components (optional)
  28747. * @param type the type of the component (optional)
  28748. * @param normalized whether the data contains normalized data (optional)
  28749. * @param useBytes set to true if stride and offset are in bytes (optional)
  28750. */
  28751. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28752. if (normalized === void 0) { normalized = false; }
  28753. if (useBytes === void 0) { useBytes = false; }
  28754. if (data instanceof BABYLON.Buffer) {
  28755. this._buffer = data;
  28756. this._ownsBuffer = false;
  28757. }
  28758. else {
  28759. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28760. this._ownsBuffer = true;
  28761. }
  28762. this._kind = kind;
  28763. if (type == undefined) {
  28764. var data_1 = this.getData();
  28765. this.type = VertexBuffer.FLOAT;
  28766. if (data_1 instanceof Int8Array)
  28767. this.type = VertexBuffer.BYTE;
  28768. else if (data_1 instanceof Uint8Array)
  28769. this.type = VertexBuffer.UNSIGNED_BYTE;
  28770. else if (data_1 instanceof Int16Array)
  28771. this.type = VertexBuffer.SHORT;
  28772. else if (data_1 instanceof Uint16Array)
  28773. this.type = VertexBuffer.UNSIGNED_SHORT;
  28774. else if (data_1 instanceof Int32Array)
  28775. this.type = VertexBuffer.INT;
  28776. else if (data_1 instanceof Uint32Array)
  28777. this.type = VertexBuffer.UNSIGNED_INT;
  28778. }
  28779. else {
  28780. this.type = type;
  28781. }
  28782. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28783. if (useBytes) {
  28784. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28785. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28786. this.byteOffset = offset || 0;
  28787. }
  28788. else {
  28789. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28790. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28791. this.byteOffset = (offset || 0) * typeByteLength;
  28792. }
  28793. this.normalized = normalized;
  28794. this._instanced = instanced !== undefined ? instanced : false;
  28795. this._instanceDivisor = instanced ? 1 : 0;
  28796. }
  28797. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28798. /**
  28799. * Gets or sets the instance divisor when in instanced mode
  28800. */
  28801. get: function () {
  28802. return this._instanceDivisor;
  28803. },
  28804. set: function (value) {
  28805. this._instanceDivisor = value;
  28806. if (value == 0) {
  28807. this._instanced = false;
  28808. }
  28809. else {
  28810. this._instanced = true;
  28811. }
  28812. },
  28813. enumerable: true,
  28814. configurable: true
  28815. });
  28816. /** @hidden */
  28817. VertexBuffer.prototype._rebuild = function () {
  28818. if (!this._buffer) {
  28819. return;
  28820. }
  28821. this._buffer._rebuild();
  28822. };
  28823. /**
  28824. * Returns the kind of the VertexBuffer (string).
  28825. */
  28826. VertexBuffer.prototype.getKind = function () {
  28827. return this._kind;
  28828. };
  28829. // Properties
  28830. /**
  28831. * Boolean : is the VertexBuffer updatable ?
  28832. */
  28833. VertexBuffer.prototype.isUpdatable = function () {
  28834. return this._buffer.isUpdatable();
  28835. };
  28836. /**
  28837. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28838. */
  28839. VertexBuffer.prototype.getData = function () {
  28840. return this._buffer.getData();
  28841. };
  28842. /**
  28843. * Returns the WebGLBuffer associated to the VertexBuffer.
  28844. */
  28845. VertexBuffer.prototype.getBuffer = function () {
  28846. return this._buffer.getBuffer();
  28847. };
  28848. /**
  28849. * Returns the stride as a multiple of the type byte length.
  28850. * DEPRECATED. Use byteStride instead.
  28851. */
  28852. VertexBuffer.prototype.getStrideSize = function () {
  28853. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28854. };
  28855. /**
  28856. * Returns the offset as a multiple of the type byte length.
  28857. * DEPRECATED. Use byteOffset instead.
  28858. */
  28859. VertexBuffer.prototype.getOffset = function () {
  28860. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28861. };
  28862. /**
  28863. * Returns the number of components per vertex attribute (integer).
  28864. */
  28865. VertexBuffer.prototype.getSize = function () {
  28866. return this._size;
  28867. };
  28868. /**
  28869. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28870. */
  28871. VertexBuffer.prototype.getIsInstanced = function () {
  28872. return this._instanced;
  28873. };
  28874. /**
  28875. * Returns the instancing divisor, zero for non-instanced (integer).
  28876. */
  28877. VertexBuffer.prototype.getInstanceDivisor = function () {
  28878. return this._instanceDivisor;
  28879. };
  28880. // Methods
  28881. /**
  28882. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  28883. * Returns the created WebGLBuffer.
  28884. */
  28885. VertexBuffer.prototype.create = function (data) {
  28886. return this._buffer.create(data);
  28887. };
  28888. /**
  28889. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28890. * This function will create a new buffer if the current one is not updatable
  28891. * Returns the updated WebGLBuffer.
  28892. */
  28893. VertexBuffer.prototype.update = function (data) {
  28894. return this._buffer.update(data);
  28895. };
  28896. /**
  28897. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28898. * Returns the directly updated WebGLBuffer.
  28899. * @param data the new data
  28900. * @param offset the new offset
  28901. * @param useBytes set to true if the offset is in bytes
  28902. */
  28903. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  28904. if (useBytes === void 0) { useBytes = false; }
  28905. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  28906. };
  28907. /**
  28908. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  28909. */
  28910. VertexBuffer.prototype.dispose = function () {
  28911. if (this._ownsBuffer) {
  28912. this._buffer.dispose();
  28913. }
  28914. };
  28915. /**
  28916. * Enumerates each value of this vertex buffer as numbers.
  28917. * @param count the number of values to enumerate
  28918. * @param callback the callback function called for each value
  28919. */
  28920. VertexBuffer.prototype.forEach = function (count, callback) {
  28921. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  28922. };
  28923. Object.defineProperty(VertexBuffer, "PositionKind", {
  28924. get: function () {
  28925. return VertexBuffer._PositionKind;
  28926. },
  28927. enumerable: true,
  28928. configurable: true
  28929. });
  28930. Object.defineProperty(VertexBuffer, "NormalKind", {
  28931. get: function () {
  28932. return VertexBuffer._NormalKind;
  28933. },
  28934. enumerable: true,
  28935. configurable: true
  28936. });
  28937. Object.defineProperty(VertexBuffer, "TangentKind", {
  28938. get: function () {
  28939. return VertexBuffer._TangentKind;
  28940. },
  28941. enumerable: true,
  28942. configurable: true
  28943. });
  28944. Object.defineProperty(VertexBuffer, "UVKind", {
  28945. get: function () {
  28946. return VertexBuffer._UVKind;
  28947. },
  28948. enumerable: true,
  28949. configurable: true
  28950. });
  28951. Object.defineProperty(VertexBuffer, "UV2Kind", {
  28952. get: function () {
  28953. return VertexBuffer._UV2Kind;
  28954. },
  28955. enumerable: true,
  28956. configurable: true
  28957. });
  28958. Object.defineProperty(VertexBuffer, "UV3Kind", {
  28959. get: function () {
  28960. return VertexBuffer._UV3Kind;
  28961. },
  28962. enumerable: true,
  28963. configurable: true
  28964. });
  28965. Object.defineProperty(VertexBuffer, "UV4Kind", {
  28966. get: function () {
  28967. return VertexBuffer._UV4Kind;
  28968. },
  28969. enumerable: true,
  28970. configurable: true
  28971. });
  28972. Object.defineProperty(VertexBuffer, "UV5Kind", {
  28973. get: function () {
  28974. return VertexBuffer._UV5Kind;
  28975. },
  28976. enumerable: true,
  28977. configurable: true
  28978. });
  28979. Object.defineProperty(VertexBuffer, "UV6Kind", {
  28980. get: function () {
  28981. return VertexBuffer._UV6Kind;
  28982. },
  28983. enumerable: true,
  28984. configurable: true
  28985. });
  28986. Object.defineProperty(VertexBuffer, "ColorKind", {
  28987. get: function () {
  28988. return VertexBuffer._ColorKind;
  28989. },
  28990. enumerable: true,
  28991. configurable: true
  28992. });
  28993. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  28994. get: function () {
  28995. return VertexBuffer._MatricesIndicesKind;
  28996. },
  28997. enumerable: true,
  28998. configurable: true
  28999. });
  29000. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29001. get: function () {
  29002. return VertexBuffer._MatricesWeightsKind;
  29003. },
  29004. enumerable: true,
  29005. configurable: true
  29006. });
  29007. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29008. get: function () {
  29009. return VertexBuffer._MatricesIndicesExtraKind;
  29010. },
  29011. enumerable: true,
  29012. configurable: true
  29013. });
  29014. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29015. get: function () {
  29016. return VertexBuffer._MatricesWeightsExtraKind;
  29017. },
  29018. enumerable: true,
  29019. configurable: true
  29020. });
  29021. /**
  29022. * Deduces the stride given a kind.
  29023. * @param kind The kind string to deduce
  29024. * @returns The deduced stride
  29025. */
  29026. VertexBuffer.DeduceStride = function (kind) {
  29027. switch (kind) {
  29028. case VertexBuffer.UVKind:
  29029. case VertexBuffer.UV2Kind:
  29030. case VertexBuffer.UV3Kind:
  29031. case VertexBuffer.UV4Kind:
  29032. case VertexBuffer.UV5Kind:
  29033. case VertexBuffer.UV6Kind:
  29034. return 2;
  29035. case VertexBuffer.NormalKind:
  29036. case VertexBuffer.PositionKind:
  29037. return 3;
  29038. case VertexBuffer.ColorKind:
  29039. case VertexBuffer.MatricesIndicesKind:
  29040. case VertexBuffer.MatricesIndicesExtraKind:
  29041. case VertexBuffer.MatricesWeightsKind:
  29042. case VertexBuffer.MatricesWeightsExtraKind:
  29043. case VertexBuffer.TangentKind:
  29044. return 4;
  29045. default:
  29046. throw new Error("Invalid kind '" + kind + "'");
  29047. }
  29048. };
  29049. /**
  29050. * Gets the byte length of the given type.
  29051. * @param type the type
  29052. * @returns the number of bytes
  29053. */
  29054. VertexBuffer.GetTypeByteLength = function (type) {
  29055. switch (type) {
  29056. case VertexBuffer.BYTE:
  29057. case VertexBuffer.UNSIGNED_BYTE:
  29058. return 1;
  29059. case VertexBuffer.SHORT:
  29060. case VertexBuffer.UNSIGNED_SHORT:
  29061. return 2;
  29062. case VertexBuffer.INT:
  29063. case VertexBuffer.FLOAT:
  29064. return 4;
  29065. default:
  29066. throw new Error("Invalid type '" + type + "'");
  29067. }
  29068. };
  29069. /**
  29070. * Enumerates each value of the given parameters as numbers.
  29071. * @param data the data to enumerate
  29072. * @param byteOffset the byte offset of the data
  29073. * @param byteStride the byte stride of the data
  29074. * @param componentCount the number of components per element
  29075. * @param componentType the type of the component
  29076. * @param count the total number of components
  29077. * @param normalized whether the data is normalized
  29078. * @param callback the callback function called for each value
  29079. */
  29080. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29081. if (data instanceof Array) {
  29082. var offset = byteOffset / 4;
  29083. var stride = byteStride / 4;
  29084. for (var index = 0; index < count; index += componentCount) {
  29085. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29086. callback(data[offset + componentIndex], index + componentIndex);
  29087. }
  29088. offset += stride;
  29089. }
  29090. }
  29091. else {
  29092. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29093. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29094. for (var index = 0; index < count; index += componentCount) {
  29095. var componentByteOffset = byteOffset;
  29096. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29097. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29098. callback(value, index + componentIndex);
  29099. componentByteOffset += componentByteLength;
  29100. }
  29101. byteOffset += byteStride;
  29102. }
  29103. }
  29104. };
  29105. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29106. switch (type) {
  29107. case VertexBuffer.BYTE: {
  29108. var value = dataView.getInt8(byteOffset);
  29109. if (normalized) {
  29110. value = Math.max(value / 127, -1);
  29111. }
  29112. return value;
  29113. }
  29114. case VertexBuffer.UNSIGNED_BYTE: {
  29115. var value = dataView.getUint8(byteOffset);
  29116. if (normalized) {
  29117. value = value / 255;
  29118. }
  29119. return value;
  29120. }
  29121. case VertexBuffer.SHORT: {
  29122. var value = dataView.getInt16(byteOffset, true);
  29123. if (normalized) {
  29124. value = Math.max(value / 16383, -1);
  29125. }
  29126. return value;
  29127. }
  29128. case VertexBuffer.UNSIGNED_SHORT: {
  29129. var value = dataView.getUint16(byteOffset, true);
  29130. if (normalized) {
  29131. value = value / 65535;
  29132. }
  29133. return value;
  29134. }
  29135. case VertexBuffer.FLOAT: {
  29136. return dataView.getFloat32(byteOffset, true);
  29137. }
  29138. default: {
  29139. throw new Error("Invalid component type " + type);
  29140. }
  29141. }
  29142. };
  29143. /**
  29144. * The byte type.
  29145. */
  29146. VertexBuffer.BYTE = 5120;
  29147. /**
  29148. * The unsigned byte type.
  29149. */
  29150. VertexBuffer.UNSIGNED_BYTE = 5121;
  29151. /**
  29152. * The short type.
  29153. */
  29154. VertexBuffer.SHORT = 5122;
  29155. /**
  29156. * The unsigned short type.
  29157. */
  29158. VertexBuffer.UNSIGNED_SHORT = 5123;
  29159. /**
  29160. * The integer type.
  29161. */
  29162. VertexBuffer.INT = 5124;
  29163. /**
  29164. * The unsigned integer type.
  29165. */
  29166. VertexBuffer.UNSIGNED_INT = 5125;
  29167. /**
  29168. * The float type.
  29169. */
  29170. VertexBuffer.FLOAT = 5126;
  29171. // Enums
  29172. VertexBuffer._PositionKind = "position";
  29173. VertexBuffer._NormalKind = "normal";
  29174. VertexBuffer._TangentKind = "tangent";
  29175. VertexBuffer._UVKind = "uv";
  29176. VertexBuffer._UV2Kind = "uv2";
  29177. VertexBuffer._UV3Kind = "uv3";
  29178. VertexBuffer._UV4Kind = "uv4";
  29179. VertexBuffer._UV5Kind = "uv5";
  29180. VertexBuffer._UV6Kind = "uv6";
  29181. VertexBuffer._ColorKind = "color";
  29182. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29183. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29184. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29185. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29186. return VertexBuffer;
  29187. }());
  29188. BABYLON.VertexBuffer = VertexBuffer;
  29189. })(BABYLON || (BABYLON = {}));
  29190. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29191. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29192. var BABYLON;
  29193. (function (BABYLON) {
  29194. /**
  29195. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29196. */
  29197. var DummyInternalTextureTracker = /** @class */ (function () {
  29198. function DummyInternalTextureTracker() {
  29199. /**
  29200. * Gets or set the previous tracker in the list
  29201. */
  29202. this.previous = null;
  29203. /**
  29204. * Gets or set the next tracker in the list
  29205. */
  29206. this.next = null;
  29207. }
  29208. return DummyInternalTextureTracker;
  29209. }());
  29210. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29211. })(BABYLON || (BABYLON = {}));
  29212. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29213. var BABYLON;
  29214. (function (BABYLON) {
  29215. /**
  29216. * Class used to store data associated with WebGL texture data for the engine
  29217. * This class should not be used directly
  29218. */
  29219. var InternalTexture = /** @class */ (function () {
  29220. /**
  29221. * Creates a new InternalTexture
  29222. * @param engine defines the engine to use
  29223. * @param dataSource defines the type of data that will be used
  29224. */
  29225. function InternalTexture(engine, dataSource) {
  29226. /**
  29227. * Observable called when the texture is loaded
  29228. */
  29229. this.onLoadedObservable = new BABYLON.Observable();
  29230. /**
  29231. * Gets or set the previous tracker in the list
  29232. */
  29233. this.previous = null;
  29234. /**
  29235. * Gets or set the next tracker in the list
  29236. */
  29237. this.next = null;
  29238. // Private
  29239. /** @hidden */
  29240. this._initialSlot = -1;
  29241. /** @hidden */
  29242. this._designatedSlot = -1;
  29243. /** @hidden */
  29244. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29245. /** @hidden */
  29246. this._comparisonFunction = 0;
  29247. /** @hidden */
  29248. this._sphericalPolynomial = null;
  29249. /** @hidden */
  29250. this._lodGenerationScale = 0;
  29251. /** @hidden */
  29252. this._lodGenerationOffset = 0;
  29253. /** @hidden */
  29254. this._isRGBD = false;
  29255. /** @hidden */
  29256. this._references = 1;
  29257. this._engine = engine;
  29258. this._dataSource = dataSource;
  29259. this._webGLTexture = engine._createTexture();
  29260. }
  29261. /**
  29262. * Gets the Engine the texture belongs to.
  29263. * @returns The babylon engine
  29264. */
  29265. InternalTexture.prototype.getEngine = function () {
  29266. return this._engine;
  29267. };
  29268. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29269. /**
  29270. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29271. */
  29272. get: function () {
  29273. return this._dataSource;
  29274. },
  29275. enumerable: true,
  29276. configurable: true
  29277. });
  29278. /**
  29279. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29280. */
  29281. InternalTexture.prototype.incrementReferences = function () {
  29282. this._references++;
  29283. };
  29284. /**
  29285. * Change the size of the texture (not the size of the content)
  29286. * @param width defines the new width
  29287. * @param height defines the new height
  29288. * @param depth defines the new depth (1 by default)
  29289. */
  29290. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29291. if (depth === void 0) { depth = 1; }
  29292. this.width = width;
  29293. this.height = height;
  29294. this.depth = depth;
  29295. this.baseWidth = width;
  29296. this.baseHeight = height;
  29297. this.baseDepth = depth;
  29298. this._size = width * height * depth;
  29299. };
  29300. /** @hidden */
  29301. InternalTexture.prototype._rebuild = function () {
  29302. var _this = this;
  29303. var proxy;
  29304. this.isReady = false;
  29305. this._cachedCoordinatesMode = null;
  29306. this._cachedWrapU = null;
  29307. this._cachedWrapV = null;
  29308. this._cachedAnisotropicFilteringLevel = null;
  29309. switch (this._dataSource) {
  29310. case InternalTexture.DATASOURCE_TEMP:
  29311. return;
  29312. case InternalTexture.DATASOURCE_URL:
  29313. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29314. _this.isReady = true;
  29315. }, null, this._buffer, undefined, this.format);
  29316. proxy._swapAndDie(this);
  29317. return;
  29318. case InternalTexture.DATASOURCE_RAW:
  29319. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29320. proxy._swapAndDie(this);
  29321. this.isReady = true;
  29322. return;
  29323. case InternalTexture.DATASOURCE_RAW3D:
  29324. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29325. proxy._swapAndDie(this);
  29326. this.isReady = true;
  29327. return;
  29328. case InternalTexture.DATASOURCE_DYNAMIC:
  29329. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29330. proxy._swapAndDie(this);
  29331. // The engine will make sure to update content so no need to flag it as isReady = true
  29332. return;
  29333. case InternalTexture.DATASOURCE_RENDERTARGET:
  29334. var options = new BABYLON.RenderTargetCreationOptions();
  29335. options.generateDepthBuffer = this._generateDepthBuffer;
  29336. options.generateMipMaps = this.generateMipMaps;
  29337. options.generateStencilBuffer = this._generateStencilBuffer;
  29338. options.samplingMode = this.samplingMode;
  29339. options.type = this.type;
  29340. if (this.isCube) {
  29341. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29342. }
  29343. else {
  29344. var size = {
  29345. width: this.width,
  29346. height: this.height
  29347. };
  29348. proxy = this._engine.createRenderTargetTexture(size, options);
  29349. }
  29350. proxy._swapAndDie(this);
  29351. this.isReady = true;
  29352. return;
  29353. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29354. var depthTextureOptions = {
  29355. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29356. comparisonFunction: this._comparisonFunction,
  29357. generateStencil: this._generateStencilBuffer,
  29358. isCube: this.isCube
  29359. };
  29360. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29361. proxy._swapAndDie(this);
  29362. this.isReady = true;
  29363. return;
  29364. case InternalTexture.DATASOURCE_CUBE:
  29365. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29366. _this.isReady = true;
  29367. }, null, this.format, this._extension);
  29368. proxy._swapAndDie(this);
  29369. return;
  29370. case InternalTexture.DATASOURCE_CUBERAW:
  29371. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29372. proxy._swapAndDie(this);
  29373. this.isReady = true;
  29374. return;
  29375. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29376. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29377. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29378. _this.isReady = true;
  29379. });
  29380. proxy._swapAndDie(this);
  29381. return;
  29382. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29383. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29384. if (proxy) {
  29385. proxy._swapAndDie(_this);
  29386. }
  29387. _this.isReady = true;
  29388. }, null, this.format, this._extension);
  29389. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29390. return;
  29391. }
  29392. };
  29393. /** @hidden */
  29394. InternalTexture.prototype._swapAndDie = function (target) {
  29395. target._webGLTexture = this._webGLTexture;
  29396. if (this._framebuffer) {
  29397. target._framebuffer = this._framebuffer;
  29398. }
  29399. if (this._depthStencilBuffer) {
  29400. target._depthStencilBuffer = this._depthStencilBuffer;
  29401. }
  29402. if (this._lodTextureHigh) {
  29403. if (target._lodTextureHigh) {
  29404. target._lodTextureHigh.dispose();
  29405. }
  29406. target._lodTextureHigh = this._lodTextureHigh;
  29407. }
  29408. if (this._lodTextureMid) {
  29409. if (target._lodTextureMid) {
  29410. target._lodTextureMid.dispose();
  29411. }
  29412. target._lodTextureMid = this._lodTextureMid;
  29413. }
  29414. if (this._lodTextureLow) {
  29415. if (target._lodTextureLow) {
  29416. target._lodTextureLow.dispose();
  29417. }
  29418. target._lodTextureLow = this._lodTextureLow;
  29419. }
  29420. var cache = this._engine.getLoadedTexturesCache();
  29421. var index = cache.indexOf(this);
  29422. if (index !== -1) {
  29423. cache.splice(index, 1);
  29424. }
  29425. };
  29426. /**
  29427. * Dispose the current allocated resources
  29428. */
  29429. InternalTexture.prototype.dispose = function () {
  29430. if (!this._webGLTexture) {
  29431. return;
  29432. }
  29433. this._references--;
  29434. if (this._references === 0) {
  29435. this._engine._releaseTexture(this);
  29436. this._webGLTexture = null;
  29437. this.previous = null;
  29438. this.next = null;
  29439. }
  29440. };
  29441. /**
  29442. * The source of the texture data is unknown
  29443. */
  29444. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29445. /**
  29446. * Texture data comes from an URL
  29447. */
  29448. InternalTexture.DATASOURCE_URL = 1;
  29449. /**
  29450. * Texture data is only used for temporary storage
  29451. */
  29452. InternalTexture.DATASOURCE_TEMP = 2;
  29453. /**
  29454. * Texture data comes from raw data (ArrayBuffer)
  29455. */
  29456. InternalTexture.DATASOURCE_RAW = 3;
  29457. /**
  29458. * Texture content is dynamic (video or dynamic texture)
  29459. */
  29460. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29461. /**
  29462. * Texture content is generated by rendering to it
  29463. */
  29464. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29465. /**
  29466. * Texture content is part of a multi render target process
  29467. */
  29468. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29469. /**
  29470. * Texture data comes from a cube data file
  29471. */
  29472. InternalTexture.DATASOURCE_CUBE = 7;
  29473. /**
  29474. * Texture data comes from a raw cube data
  29475. */
  29476. InternalTexture.DATASOURCE_CUBERAW = 8;
  29477. /**
  29478. * Texture data come from a prefiltered cube data file
  29479. */
  29480. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29481. /**
  29482. * Texture content is raw 3D data
  29483. */
  29484. InternalTexture.DATASOURCE_RAW3D = 10;
  29485. /**
  29486. * Texture content is a depth texture
  29487. */
  29488. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29489. /**
  29490. * Texture data comes from a raw cube data encoded with RGBD
  29491. */
  29492. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29493. return InternalTexture;
  29494. }());
  29495. BABYLON.InternalTexture = InternalTexture;
  29496. })(BABYLON || (BABYLON = {}));
  29497. //# sourceMappingURL=babylon.internalTexture.js.map
  29498. var BABYLON;
  29499. (function (BABYLON) {
  29500. var BaseTexture = /** @class */ (function () {
  29501. function BaseTexture(scene) {
  29502. this._hasAlpha = false;
  29503. this.getAlphaFromRGB = false;
  29504. this.level = 1;
  29505. this.coordinatesIndex = 0;
  29506. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29507. /**
  29508. * | Value | Type | Description |
  29509. * | ----- | ------------------ | ----------- |
  29510. * | 0 | CLAMP_ADDRESSMODE | |
  29511. * | 1 | WRAP_ADDRESSMODE | |
  29512. * | 2 | MIRROR_ADDRESSMODE | |
  29513. */
  29514. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29515. /**
  29516. * | Value | Type | Description |
  29517. * | ----- | ------------------ | ----------- |
  29518. * | 0 | CLAMP_ADDRESSMODE | |
  29519. * | 1 | WRAP_ADDRESSMODE | |
  29520. * | 2 | MIRROR_ADDRESSMODE | |
  29521. */
  29522. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29523. /**
  29524. * | Value | Type | Description |
  29525. * | ----- | ------------------ | ----------- |
  29526. * | 0 | CLAMP_ADDRESSMODE | |
  29527. * | 1 | WRAP_ADDRESSMODE | |
  29528. * | 2 | MIRROR_ADDRESSMODE | |
  29529. */
  29530. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29531. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29532. this.isCube = false;
  29533. this.is3D = false;
  29534. this.gammaSpace = true;
  29535. this.invertZ = false;
  29536. this.lodLevelInAlpha = false;
  29537. this.isRenderTarget = false;
  29538. this.animations = new Array();
  29539. /**
  29540. * An event triggered when the texture is disposed.
  29541. */
  29542. this.onDisposeObservable = new BABYLON.Observable();
  29543. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29544. this._cachedSize = BABYLON.Size.Zero();
  29545. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29546. if (this._scene) {
  29547. this._scene.textures.push(this);
  29548. }
  29549. this._uid = null;
  29550. }
  29551. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29552. get: function () {
  29553. return this._hasAlpha;
  29554. },
  29555. set: function (value) {
  29556. if (this._hasAlpha === value) {
  29557. return;
  29558. }
  29559. this._hasAlpha = value;
  29560. if (this._scene) {
  29561. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29562. }
  29563. },
  29564. enumerable: true,
  29565. configurable: true
  29566. });
  29567. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29568. get: function () {
  29569. return this._coordinatesMode;
  29570. },
  29571. /**
  29572. * How a texture is mapped.
  29573. *
  29574. * | Value | Type | Description |
  29575. * | ----- | ----------------------------------- | ----------- |
  29576. * | 0 | EXPLICIT_MODE | |
  29577. * | 1 | SPHERICAL_MODE | |
  29578. * | 2 | PLANAR_MODE | |
  29579. * | 3 | CUBIC_MODE | |
  29580. * | 4 | PROJECTION_MODE | |
  29581. * | 5 | SKYBOX_MODE | |
  29582. * | 6 | INVCUBIC_MODE | |
  29583. * | 7 | EQUIRECTANGULAR_MODE | |
  29584. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29585. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29586. */
  29587. set: function (value) {
  29588. if (this._coordinatesMode === value) {
  29589. return;
  29590. }
  29591. this._coordinatesMode = value;
  29592. if (this._scene) {
  29593. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29594. }
  29595. },
  29596. enumerable: true,
  29597. configurable: true
  29598. });
  29599. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29600. /**
  29601. * Gets whether or not the texture contains RGBD data.
  29602. */
  29603. get: function () {
  29604. return this._texture != null && this._texture._isRGBD;
  29605. },
  29606. enumerable: true,
  29607. configurable: true
  29608. });
  29609. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29610. get: function () {
  29611. if (this._texture)
  29612. return this._texture._lodGenerationOffset;
  29613. return 0.0;
  29614. },
  29615. set: function (value) {
  29616. if (this._texture)
  29617. this._texture._lodGenerationOffset = value;
  29618. },
  29619. enumerable: true,
  29620. configurable: true
  29621. });
  29622. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29623. get: function () {
  29624. if (this._texture)
  29625. return this._texture._lodGenerationScale;
  29626. return 0.0;
  29627. },
  29628. set: function (value) {
  29629. if (this._texture)
  29630. this._texture._lodGenerationScale = value;
  29631. },
  29632. enumerable: true,
  29633. configurable: true
  29634. });
  29635. Object.defineProperty(BaseTexture.prototype, "uid", {
  29636. get: function () {
  29637. if (!this._uid) {
  29638. this._uid = BABYLON.Tools.RandomId();
  29639. }
  29640. return this._uid;
  29641. },
  29642. enumerable: true,
  29643. configurable: true
  29644. });
  29645. BaseTexture.prototype.toString = function () {
  29646. return this.name;
  29647. };
  29648. BaseTexture.prototype.getClassName = function () {
  29649. return "BaseTexture";
  29650. };
  29651. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29652. set: function (callback) {
  29653. if (this._onDisposeObserver) {
  29654. this.onDisposeObservable.remove(this._onDisposeObserver);
  29655. }
  29656. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29657. },
  29658. enumerable: true,
  29659. configurable: true
  29660. });
  29661. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29662. get: function () {
  29663. return true;
  29664. },
  29665. enumerable: true,
  29666. configurable: true
  29667. });
  29668. BaseTexture.prototype.getScene = function () {
  29669. return this._scene;
  29670. };
  29671. BaseTexture.prototype.getTextureMatrix = function () {
  29672. return BABYLON.Matrix.IdentityReadOnly;
  29673. };
  29674. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29675. return BABYLON.Matrix.IdentityReadOnly;
  29676. };
  29677. BaseTexture.prototype.getInternalTexture = function () {
  29678. return this._texture;
  29679. };
  29680. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29681. return !this.isBlocking || this.isReady();
  29682. };
  29683. BaseTexture.prototype.isReady = function () {
  29684. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29685. this.delayLoad();
  29686. return false;
  29687. }
  29688. if (this._texture) {
  29689. return this._texture.isReady;
  29690. }
  29691. return false;
  29692. };
  29693. BaseTexture.prototype.getSize = function () {
  29694. if (this._texture) {
  29695. if (this._texture.width) {
  29696. this._cachedSize.width = this._texture.width;
  29697. this._cachedSize.height = this._texture.height;
  29698. return this._cachedSize;
  29699. }
  29700. if (this._texture._size) {
  29701. this._cachedSize.width = this._texture._size;
  29702. this._cachedSize.height = this._texture._size;
  29703. return this._cachedSize;
  29704. }
  29705. }
  29706. return this._cachedSize;
  29707. };
  29708. BaseTexture.prototype.getBaseSize = function () {
  29709. if (!this.isReady() || !this._texture)
  29710. return BABYLON.Size.Zero();
  29711. if (this._texture._size) {
  29712. return new BABYLON.Size(this._texture._size, this._texture._size);
  29713. }
  29714. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29715. };
  29716. BaseTexture.prototype.scale = function (ratio) {
  29717. };
  29718. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29719. get: function () {
  29720. return false;
  29721. },
  29722. enumerable: true,
  29723. configurable: true
  29724. });
  29725. /** @hidden */
  29726. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29727. if (!this._scene) {
  29728. return null;
  29729. }
  29730. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29731. for (var index = 0; index < texturesCache.length; index++) {
  29732. var texturesCacheEntry = texturesCache[index];
  29733. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29734. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29735. texturesCacheEntry.incrementReferences();
  29736. return texturesCacheEntry;
  29737. }
  29738. }
  29739. }
  29740. return null;
  29741. };
  29742. /** @hidden */
  29743. BaseTexture.prototype._rebuild = function () {
  29744. };
  29745. BaseTexture.prototype.delayLoad = function () {
  29746. };
  29747. BaseTexture.prototype.clone = function () {
  29748. return null;
  29749. };
  29750. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29751. get: function () {
  29752. if (!this._texture) {
  29753. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29754. }
  29755. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29756. },
  29757. enumerable: true,
  29758. configurable: true
  29759. });
  29760. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29761. get: function () {
  29762. if (!this._texture) {
  29763. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29764. }
  29765. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29766. },
  29767. enumerable: true,
  29768. configurable: true
  29769. });
  29770. /**
  29771. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  29772. * This will returns an RGBA array buffer containing either in values (0-255) or
  29773. * float values (0-1) depending of the underlying buffer type.
  29774. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  29775. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  29776. * @param buffer defines a user defined buffer to fill with data (can be null)
  29777. * @returns The Array buffer containing the pixels data.
  29778. */
  29779. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  29780. if (faceIndex === void 0) { faceIndex = 0; }
  29781. if (level === void 0) { level = 0; }
  29782. if (buffer === void 0) { buffer = null; }
  29783. if (!this._texture) {
  29784. return null;
  29785. }
  29786. var size = this.getSize();
  29787. var width = size.width;
  29788. var height = size.height;
  29789. var scene = this.getScene();
  29790. if (!scene) {
  29791. return null;
  29792. }
  29793. var engine = scene.getEngine();
  29794. if (level != 0) {
  29795. width = width / Math.pow(2, level);
  29796. height = height / Math.pow(2, level);
  29797. width = Math.round(width);
  29798. height = Math.round(height);
  29799. }
  29800. if (this._texture.isCube) {
  29801. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  29802. }
  29803. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  29804. };
  29805. BaseTexture.prototype.releaseInternalTexture = function () {
  29806. if (this._texture) {
  29807. this._texture.dispose();
  29808. this._texture = null;
  29809. }
  29810. };
  29811. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29812. get: function () {
  29813. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29814. return null;
  29815. }
  29816. if (!this._texture._sphericalPolynomial) {
  29817. this._texture._sphericalPolynomial =
  29818. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29819. }
  29820. return this._texture._sphericalPolynomial;
  29821. },
  29822. set: function (value) {
  29823. if (this._texture) {
  29824. this._texture._sphericalPolynomial = value;
  29825. }
  29826. },
  29827. enumerable: true,
  29828. configurable: true
  29829. });
  29830. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29831. get: function () {
  29832. if (this._texture) {
  29833. return this._texture._lodTextureHigh;
  29834. }
  29835. return null;
  29836. },
  29837. enumerable: true,
  29838. configurable: true
  29839. });
  29840. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29841. get: function () {
  29842. if (this._texture) {
  29843. return this._texture._lodTextureMid;
  29844. }
  29845. return null;
  29846. },
  29847. enumerable: true,
  29848. configurable: true
  29849. });
  29850. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29851. get: function () {
  29852. if (this._texture) {
  29853. return this._texture._lodTextureLow;
  29854. }
  29855. return null;
  29856. },
  29857. enumerable: true,
  29858. configurable: true
  29859. });
  29860. BaseTexture.prototype.dispose = function () {
  29861. if (!this._scene) {
  29862. return;
  29863. }
  29864. // Animations
  29865. this._scene.stopAnimation(this);
  29866. // Remove from scene
  29867. this._scene._removePendingData(this);
  29868. var index = this._scene.textures.indexOf(this);
  29869. if (index >= 0) {
  29870. this._scene.textures.splice(index, 1);
  29871. }
  29872. if (this._texture === undefined) {
  29873. return;
  29874. }
  29875. // Release
  29876. this.releaseInternalTexture();
  29877. // Callback
  29878. this.onDisposeObservable.notifyObservers(this);
  29879. this.onDisposeObservable.clear();
  29880. };
  29881. BaseTexture.prototype.serialize = function () {
  29882. if (!this.name) {
  29883. return null;
  29884. }
  29885. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29886. // Animations
  29887. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29888. return serializationObject;
  29889. };
  29890. BaseTexture.WhenAllReady = function (textures, callback) {
  29891. var numRemaining = textures.length;
  29892. if (numRemaining === 0) {
  29893. callback();
  29894. return;
  29895. }
  29896. var _loop_1 = function () {
  29897. texture = textures[i];
  29898. if (texture.isReady()) {
  29899. if (--numRemaining === 0) {
  29900. callback();
  29901. }
  29902. }
  29903. else {
  29904. onLoadObservable = texture.onLoadObservable;
  29905. var onLoadCallback_1 = function () {
  29906. onLoadObservable.removeCallback(onLoadCallback_1);
  29907. if (--numRemaining === 0) {
  29908. callback();
  29909. }
  29910. };
  29911. onLoadObservable.add(onLoadCallback_1);
  29912. }
  29913. };
  29914. var texture, onLoadObservable;
  29915. for (var i = 0; i < textures.length; i++) {
  29916. _loop_1();
  29917. }
  29918. };
  29919. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29920. __decorate([
  29921. BABYLON.serialize()
  29922. ], BaseTexture.prototype, "name", void 0);
  29923. __decorate([
  29924. BABYLON.serialize("hasAlpha")
  29925. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29926. __decorate([
  29927. BABYLON.serialize()
  29928. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29929. __decorate([
  29930. BABYLON.serialize()
  29931. ], BaseTexture.prototype, "level", void 0);
  29932. __decorate([
  29933. BABYLON.serialize()
  29934. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29935. __decorate([
  29936. BABYLON.serialize("coordinatesMode")
  29937. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29938. __decorate([
  29939. BABYLON.serialize()
  29940. ], BaseTexture.prototype, "wrapU", void 0);
  29941. __decorate([
  29942. BABYLON.serialize()
  29943. ], BaseTexture.prototype, "wrapV", void 0);
  29944. __decorate([
  29945. BABYLON.serialize()
  29946. ], BaseTexture.prototype, "wrapR", void 0);
  29947. __decorate([
  29948. BABYLON.serialize()
  29949. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29950. __decorate([
  29951. BABYLON.serialize()
  29952. ], BaseTexture.prototype, "isCube", void 0);
  29953. __decorate([
  29954. BABYLON.serialize()
  29955. ], BaseTexture.prototype, "is3D", void 0);
  29956. __decorate([
  29957. BABYLON.serialize()
  29958. ], BaseTexture.prototype, "gammaSpace", void 0);
  29959. __decorate([
  29960. BABYLON.serialize()
  29961. ], BaseTexture.prototype, "invertZ", void 0);
  29962. __decorate([
  29963. BABYLON.serialize()
  29964. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  29965. __decorate([
  29966. BABYLON.serialize()
  29967. ], BaseTexture.prototype, "lodGenerationOffset", null);
  29968. __decorate([
  29969. BABYLON.serialize()
  29970. ], BaseTexture.prototype, "lodGenerationScale", null);
  29971. __decorate([
  29972. BABYLON.serialize()
  29973. ], BaseTexture.prototype, "isRenderTarget", void 0);
  29974. return BaseTexture;
  29975. }());
  29976. BABYLON.BaseTexture = BaseTexture;
  29977. })(BABYLON || (BABYLON = {}));
  29978. //# sourceMappingURL=babylon.baseTexture.js.map
  29979. var BABYLON;
  29980. (function (BABYLON) {
  29981. var Texture = /** @class */ (function (_super) {
  29982. __extends(Texture, _super);
  29983. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  29984. if (noMipmap === void 0) { noMipmap = false; }
  29985. if (invertY === void 0) { invertY = true; }
  29986. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29987. if (onLoad === void 0) { onLoad = null; }
  29988. if (onError === void 0) { onError = null; }
  29989. if (buffer === void 0) { buffer = null; }
  29990. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29991. var _this = _super.call(this, scene) || this;
  29992. _this.uOffset = 0;
  29993. _this.vOffset = 0;
  29994. _this.uScale = 1.0;
  29995. _this.vScale = 1.0;
  29996. _this.uAng = 0;
  29997. _this.vAng = 0;
  29998. _this.wAng = 0;
  29999. /**
  30000. * Defines the center of rotation (U)
  30001. */
  30002. _this.uRotationCenter = 0.5;
  30003. /**
  30004. * Defines the center of rotation (V)
  30005. */
  30006. _this.vRotationCenter = 0.5;
  30007. /**
  30008. * Defines the center of rotation (W)
  30009. */
  30010. _this.wRotationCenter = 0.5;
  30011. _this._isBlocking = true;
  30012. _this.name = url || "";
  30013. _this.url = url;
  30014. _this._noMipmap = noMipmap;
  30015. _this._invertY = invertY;
  30016. _this._samplingMode = samplingMode;
  30017. _this._buffer = buffer;
  30018. _this._deleteBuffer = deleteBuffer;
  30019. if (format) {
  30020. _this._format = format;
  30021. }
  30022. scene = _this.getScene();
  30023. if (!scene) {
  30024. return _this;
  30025. }
  30026. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30027. var load = function () {
  30028. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30029. _this.onLoadObservable.notifyObservers(_this);
  30030. }
  30031. if (onLoad) {
  30032. onLoad();
  30033. }
  30034. if (!_this.isBlocking && scene) {
  30035. scene.resetCachedMaterial();
  30036. }
  30037. };
  30038. if (!_this.url) {
  30039. _this._delayedOnLoad = load;
  30040. _this._delayedOnError = onError;
  30041. return _this;
  30042. }
  30043. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30044. if (!_this._texture) {
  30045. if (!scene.useDelayedTextureLoading) {
  30046. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30047. if (deleteBuffer) {
  30048. delete _this._buffer;
  30049. }
  30050. }
  30051. else {
  30052. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30053. _this._delayedOnLoad = load;
  30054. _this._delayedOnError = onError;
  30055. }
  30056. }
  30057. else {
  30058. if (_this._texture.isReady) {
  30059. BABYLON.Tools.SetImmediate(function () { return load(); });
  30060. }
  30061. else {
  30062. _this._texture.onLoadedObservable.add(load);
  30063. }
  30064. }
  30065. return _this;
  30066. }
  30067. Object.defineProperty(Texture.prototype, "noMipmap", {
  30068. get: function () {
  30069. return this._noMipmap;
  30070. },
  30071. enumerable: true,
  30072. configurable: true
  30073. });
  30074. Object.defineProperty(Texture.prototype, "isBlocking", {
  30075. get: function () {
  30076. return this._isBlocking;
  30077. },
  30078. set: function (value) {
  30079. this._isBlocking = value;
  30080. },
  30081. enumerable: true,
  30082. configurable: true
  30083. });
  30084. Object.defineProperty(Texture.prototype, "samplingMode", {
  30085. get: function () {
  30086. return this._samplingMode;
  30087. },
  30088. enumerable: true,
  30089. configurable: true
  30090. });
  30091. /**
  30092. * Update the url (and optional buffer) of this texture if url was null during construction.
  30093. * @param url the url of the texture
  30094. * @param buffer the buffer of the texture (defaults to null)
  30095. */
  30096. Texture.prototype.updateURL = function (url, buffer) {
  30097. if (buffer === void 0) { buffer = null; }
  30098. if (this.url) {
  30099. throw new Error("URL is already set");
  30100. }
  30101. this.url = url;
  30102. this._buffer = buffer;
  30103. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30104. this.delayLoad();
  30105. };
  30106. Texture.prototype.delayLoad = function () {
  30107. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30108. return;
  30109. }
  30110. var scene = this.getScene();
  30111. if (!scene) {
  30112. return;
  30113. }
  30114. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30115. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30116. if (!this._texture) {
  30117. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30118. if (this._deleteBuffer) {
  30119. delete this._buffer;
  30120. }
  30121. }
  30122. else {
  30123. if (this._delayedOnLoad) {
  30124. if (this._texture.isReady) {
  30125. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30126. }
  30127. else {
  30128. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30129. }
  30130. }
  30131. }
  30132. this._delayedOnLoad = null;
  30133. this._delayedOnError = null;
  30134. };
  30135. /**
  30136. * Default is Trilinear mode.
  30137. *
  30138. * | Value | Type | Description |
  30139. * | ----- | ------------------ | ----------- |
  30140. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30141. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30142. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30143. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30144. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30145. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30146. * | 7 | NEAREST_LINEAR | |
  30147. * | 8 | NEAREST_NEAREST | |
  30148. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30149. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30150. * | 11 | LINEAR_LINEAR | |
  30151. * | 12 | LINEAR_NEAREST | |
  30152. *
  30153. * > _mag_: magnification filter (close to the viewer)
  30154. * > _min_: minification filter (far from the viewer)
  30155. * > _mip_: filter used between mip map levels
  30156. *
  30157. */
  30158. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30159. if (!this._texture) {
  30160. return;
  30161. }
  30162. var scene = this.getScene();
  30163. if (!scene) {
  30164. return;
  30165. }
  30166. this._samplingMode = samplingMode;
  30167. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30168. };
  30169. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30170. x *= this.uScale;
  30171. y *= this.vScale;
  30172. x -= this.uRotationCenter * this.uScale;
  30173. y -= this.vRotationCenter * this.vScale;
  30174. z -= this.wRotationCenter;
  30175. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30176. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30177. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30178. t.z += this.wRotationCenter;
  30179. };
  30180. Texture.prototype.getTextureMatrix = function () {
  30181. var _this = this;
  30182. if (this.uOffset === this._cachedUOffset &&
  30183. this.vOffset === this._cachedVOffset &&
  30184. this.uScale === this._cachedUScale &&
  30185. this.vScale === this._cachedVScale &&
  30186. this.uAng === this._cachedUAng &&
  30187. this.vAng === this._cachedVAng &&
  30188. this.wAng === this._cachedWAng) {
  30189. return this._cachedTextureMatrix;
  30190. }
  30191. this._cachedUOffset = this.uOffset;
  30192. this._cachedVOffset = this.vOffset;
  30193. this._cachedUScale = this.uScale;
  30194. this._cachedVScale = this.vScale;
  30195. this._cachedUAng = this.uAng;
  30196. this._cachedVAng = this.vAng;
  30197. this._cachedWAng = this.wAng;
  30198. if (!this._cachedTextureMatrix) {
  30199. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30200. this._rowGenerationMatrix = new BABYLON.Matrix();
  30201. this._t0 = BABYLON.Vector3.Zero();
  30202. this._t1 = BABYLON.Vector3.Zero();
  30203. this._t2 = BABYLON.Vector3.Zero();
  30204. }
  30205. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30206. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30207. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30208. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30209. this._t1.subtractInPlace(this._t0);
  30210. this._t2.subtractInPlace(this._t0);
  30211. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30212. this._cachedTextureMatrix.m[0] = this._t1.x;
  30213. this._cachedTextureMatrix.m[1] = this._t1.y;
  30214. this._cachedTextureMatrix.m[2] = this._t1.z;
  30215. this._cachedTextureMatrix.m[4] = this._t2.x;
  30216. this._cachedTextureMatrix.m[5] = this._t2.y;
  30217. this._cachedTextureMatrix.m[6] = this._t2.z;
  30218. this._cachedTextureMatrix.m[8] = this._t0.x;
  30219. this._cachedTextureMatrix.m[9] = this._t0.y;
  30220. this._cachedTextureMatrix.m[10] = this._t0.z;
  30221. var scene = this.getScene();
  30222. if (!scene) {
  30223. return this._cachedTextureMatrix;
  30224. }
  30225. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30226. return mat.hasTexture(_this);
  30227. });
  30228. return this._cachedTextureMatrix;
  30229. };
  30230. Texture.prototype.getReflectionTextureMatrix = function () {
  30231. var _this = this;
  30232. var scene = this.getScene();
  30233. if (!scene) {
  30234. return this._cachedTextureMatrix;
  30235. }
  30236. if (this.uOffset === this._cachedUOffset &&
  30237. this.vOffset === this._cachedVOffset &&
  30238. this.uScale === this._cachedUScale &&
  30239. this.vScale === this._cachedVScale &&
  30240. this.coordinatesMode === this._cachedCoordinatesMode) {
  30241. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30242. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30243. return this._cachedTextureMatrix;
  30244. }
  30245. }
  30246. else {
  30247. return this._cachedTextureMatrix;
  30248. }
  30249. }
  30250. if (!this._cachedTextureMatrix) {
  30251. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30252. }
  30253. if (!this._projectionModeMatrix) {
  30254. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30255. }
  30256. this._cachedUOffset = this.uOffset;
  30257. this._cachedVOffset = this.vOffset;
  30258. this._cachedUScale = this.uScale;
  30259. this._cachedVScale = this.vScale;
  30260. this._cachedCoordinatesMode = this.coordinatesMode;
  30261. switch (this.coordinatesMode) {
  30262. case Texture.PLANAR_MODE:
  30263. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30264. this._cachedTextureMatrix[0] = this.uScale;
  30265. this._cachedTextureMatrix[5] = this.vScale;
  30266. this._cachedTextureMatrix[12] = this.uOffset;
  30267. this._cachedTextureMatrix[13] = this.vOffset;
  30268. break;
  30269. case Texture.PROJECTION_MODE:
  30270. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30271. this._projectionModeMatrix.m[0] = 0.5;
  30272. this._projectionModeMatrix.m[5] = -0.5;
  30273. this._projectionModeMatrix.m[10] = 0.0;
  30274. this._projectionModeMatrix.m[12] = 0.5;
  30275. this._projectionModeMatrix.m[13] = 0.5;
  30276. this._projectionModeMatrix.m[14] = 1.0;
  30277. this._projectionModeMatrix.m[15] = 1.0;
  30278. var projectionMatrix = scene.getProjectionMatrix();
  30279. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30280. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30281. break;
  30282. default:
  30283. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30284. break;
  30285. }
  30286. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30287. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30288. });
  30289. return this._cachedTextureMatrix;
  30290. };
  30291. Texture.prototype.clone = function () {
  30292. var _this = this;
  30293. return BABYLON.SerializationHelper.Clone(function () {
  30294. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30295. }, this);
  30296. };
  30297. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30298. get: function () {
  30299. if (!this._onLoadObservable) {
  30300. this._onLoadObservable = new BABYLON.Observable();
  30301. }
  30302. return this._onLoadObservable;
  30303. },
  30304. enumerable: true,
  30305. configurable: true
  30306. });
  30307. Texture.prototype.serialize = function () {
  30308. var serializationObject = _super.prototype.serialize.call(this);
  30309. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30310. serializationObject.base64String = this._buffer;
  30311. serializationObject.name = serializationObject.name.replace("data:", "");
  30312. }
  30313. serializationObject.invertY = this._invertY;
  30314. serializationObject.samplingMode = this.samplingMode;
  30315. return serializationObject;
  30316. };
  30317. Texture.prototype.getClassName = function () {
  30318. return "Texture";
  30319. };
  30320. Texture.prototype.dispose = function () {
  30321. _super.prototype.dispose.call(this);
  30322. if (this._onLoadObservable) {
  30323. this._onLoadObservable.clear();
  30324. this._onLoadObservable = null;
  30325. }
  30326. this._delayedOnLoad = null;
  30327. this._delayedOnError = null;
  30328. };
  30329. // Statics
  30330. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30331. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30332. if (onLoad === void 0) { onLoad = null; }
  30333. if (onError === void 0) { onError = null; }
  30334. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30335. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30336. };
  30337. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30338. if (parsedTexture.customType) {
  30339. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30340. // Update Sampling Mode
  30341. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30342. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30343. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30344. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30345. }
  30346. }
  30347. return parsedCustomTexture;
  30348. }
  30349. if (parsedTexture.isCube) {
  30350. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30351. }
  30352. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30353. return null;
  30354. }
  30355. var texture = BABYLON.SerializationHelper.Parse(function () {
  30356. var generateMipMaps = true;
  30357. if (parsedTexture.noMipmap) {
  30358. generateMipMaps = false;
  30359. }
  30360. if (parsedTexture.mirrorPlane) {
  30361. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30362. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30363. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30364. return mirrorTexture;
  30365. }
  30366. else if (parsedTexture.isRenderTarget) {
  30367. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30368. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30369. return renderTargetTexture;
  30370. }
  30371. else {
  30372. var texture;
  30373. if (parsedTexture.base64String) {
  30374. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30375. }
  30376. else {
  30377. var url = rootUrl + parsedTexture.name;
  30378. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30379. url = parsedTexture.url;
  30380. }
  30381. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30382. }
  30383. return texture;
  30384. }
  30385. }, parsedTexture, scene);
  30386. // Update Sampling Mode
  30387. if (parsedTexture.samplingMode) {
  30388. var sampling = parsedTexture.samplingMode;
  30389. if (texture._samplingMode !== sampling) {
  30390. texture.updateSamplingMode(sampling);
  30391. }
  30392. }
  30393. // Animations
  30394. if (parsedTexture.animations) {
  30395. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30396. var parsedAnimation = parsedTexture.animations[animationIndex];
  30397. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30398. }
  30399. }
  30400. return texture;
  30401. };
  30402. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30403. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30404. if (noMipmap === void 0) { noMipmap = false; }
  30405. if (invertY === void 0) { invertY = true; }
  30406. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30407. if (onLoad === void 0) { onLoad = null; }
  30408. if (onError === void 0) { onError = null; }
  30409. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30410. if (name.substr(0, 5) !== "data:") {
  30411. name = "data:" + name;
  30412. }
  30413. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30414. };
  30415. // Constants
  30416. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30417. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30418. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30419. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30420. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30421. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30422. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30423. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30424. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30425. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30426. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30427. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30428. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30429. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30430. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30431. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30432. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30433. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30434. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30435. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30436. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30437. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30438. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30439. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30440. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30441. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30442. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30443. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30444. /**
  30445. * 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
  30446. */
  30447. Texture.UseSerializedUrlIfAny = false;
  30448. __decorate([
  30449. BABYLON.serialize()
  30450. ], Texture.prototype, "url", void 0);
  30451. __decorate([
  30452. BABYLON.serialize()
  30453. ], Texture.prototype, "uOffset", void 0);
  30454. __decorate([
  30455. BABYLON.serialize()
  30456. ], Texture.prototype, "vOffset", void 0);
  30457. __decorate([
  30458. BABYLON.serialize()
  30459. ], Texture.prototype, "uScale", void 0);
  30460. __decorate([
  30461. BABYLON.serialize()
  30462. ], Texture.prototype, "vScale", void 0);
  30463. __decorate([
  30464. BABYLON.serialize()
  30465. ], Texture.prototype, "uAng", void 0);
  30466. __decorate([
  30467. BABYLON.serialize()
  30468. ], Texture.prototype, "vAng", void 0);
  30469. __decorate([
  30470. BABYLON.serialize()
  30471. ], Texture.prototype, "wAng", void 0);
  30472. __decorate([
  30473. BABYLON.serialize()
  30474. ], Texture.prototype, "uRotationCenter", void 0);
  30475. __decorate([
  30476. BABYLON.serialize()
  30477. ], Texture.prototype, "vRotationCenter", void 0);
  30478. __decorate([
  30479. BABYLON.serialize()
  30480. ], Texture.prototype, "wRotationCenter", void 0);
  30481. __decorate([
  30482. BABYLON.serialize()
  30483. ], Texture.prototype, "isBlocking", null);
  30484. return Texture;
  30485. }(BABYLON.BaseTexture));
  30486. BABYLON.Texture = Texture;
  30487. })(BABYLON || (BABYLON = {}));
  30488. //# sourceMappingURL=babylon.texture.js.map
  30489. var BABYLON;
  30490. (function (BABYLON) {
  30491. /**
  30492. * @hidden
  30493. **/
  30494. var _InstancesBatch = /** @class */ (function () {
  30495. function _InstancesBatch() {
  30496. this.mustReturn = false;
  30497. this.visibleInstances = new Array();
  30498. this.renderSelf = new Array();
  30499. }
  30500. return _InstancesBatch;
  30501. }());
  30502. BABYLON._InstancesBatch = _InstancesBatch;
  30503. var Mesh = /** @class */ (function (_super) {
  30504. __extends(Mesh, _super);
  30505. /**
  30506. * @constructor
  30507. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30508. * @param {Scene} scene The scene to add this mesh to.
  30509. * @param {Node} parent The parent of this mesh, if it has one
  30510. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30511. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30512. * When false, achieved by calling a clone(), also passing False.
  30513. * This will make creation of children, recursive.
  30514. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30515. */
  30516. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30517. if (scene === void 0) { scene = null; }
  30518. if (parent === void 0) { parent = null; }
  30519. if (source === void 0) { source = null; }
  30520. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30521. var _this = _super.call(this, name, scene) || this;
  30522. // Members
  30523. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30524. _this.instances = new Array();
  30525. _this._LODLevels = new Array();
  30526. /** @hidden */
  30527. _this._visibleInstances = {};
  30528. _this._renderIdForInstances = new Array();
  30529. _this._batchCache = new _InstancesBatch();
  30530. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30531. // Use by builder only to know what orientation were the mesh build in.
  30532. /** @hidden */
  30533. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30534. _this.overrideMaterialSideOrientation = null;
  30535. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30536. // Will be used to save a source mesh reference, If any
  30537. _this._source = null;
  30538. scene = _this.getScene();
  30539. if (source) {
  30540. // Geometry
  30541. if (source._geometry) {
  30542. source._geometry.applyToMesh(_this);
  30543. }
  30544. // Deep copy
  30545. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30546. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30547. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30548. ], ["_poseMatrix"]);
  30549. // Source mesh
  30550. _this._source = source;
  30551. // Construction Params
  30552. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30553. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30554. var myAnyThis = _this;
  30555. var myAnySource = source;
  30556. myAnyThis._closePath = myAnySource._closePath;
  30557. myAnyThis._idx = myAnySource._idx;
  30558. myAnyThis.dashSize = myAnySource.dashSize;
  30559. myAnyThis.gapSize = myAnySource.gapSize;
  30560. myAnyThis.path3D = myAnySource.path3D;
  30561. myAnyThis.pathArray = myAnySource.pathArray;
  30562. myAnyThis.arc = myAnySource.arc;
  30563. myAnyThis.radius = myAnySource.radius;
  30564. // Animation ranges
  30565. if (_this._source._ranges) {
  30566. var ranges = _this._source._ranges;
  30567. for (var name in ranges) {
  30568. if (!ranges.hasOwnProperty(name)) {
  30569. continue;
  30570. }
  30571. if (!ranges[name]) {
  30572. continue;
  30573. }
  30574. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  30575. }
  30576. }
  30577. // Metadata
  30578. if (source.metadata && source.metadata.clone) {
  30579. _this.metadata = source.metadata.clone();
  30580. }
  30581. else {
  30582. _this.metadata = source.metadata;
  30583. }
  30584. // Tags
  30585. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30586. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30587. }
  30588. // Parent
  30589. _this.parent = source.parent;
  30590. // Pivot
  30591. _this.setPivotMatrix(source.getPivotMatrix());
  30592. _this.id = name + "." + source.id;
  30593. // Material
  30594. _this.material = source.material;
  30595. var index;
  30596. if (!doNotCloneChildren) {
  30597. // Children
  30598. var directDescendants = source.getDescendants(true);
  30599. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30600. var child = directDescendants[index_1];
  30601. if (child.clone) {
  30602. child.clone(name + "." + child.name, _this);
  30603. }
  30604. }
  30605. }
  30606. // Physics clone
  30607. var physicsEngine = _this.getScene().getPhysicsEngine();
  30608. if (clonePhysicsImpostor && physicsEngine) {
  30609. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30610. if (impostor) {
  30611. _this.physicsImpostor = impostor.clone(_this);
  30612. }
  30613. }
  30614. // Particles
  30615. for (index = 0; index < scene.particleSystems.length; index++) {
  30616. var system = scene.particleSystems[index];
  30617. if (system.emitter === source) {
  30618. system.clone(system.name, _this);
  30619. }
  30620. }
  30621. _this.refreshBoundingInfo();
  30622. _this.computeWorldMatrix(true);
  30623. }
  30624. // Parent
  30625. if (parent !== null) {
  30626. _this.parent = parent;
  30627. }
  30628. return _this;
  30629. }
  30630. Object.defineProperty(Mesh, "FRONTSIDE", {
  30631. /**
  30632. * Mesh side orientation : usually the external or front surface
  30633. */
  30634. get: function () {
  30635. return Mesh._FRONTSIDE;
  30636. },
  30637. enumerable: true,
  30638. configurable: true
  30639. });
  30640. Object.defineProperty(Mesh, "BACKSIDE", {
  30641. /**
  30642. * Mesh side orientation : usually the internal or back surface
  30643. */
  30644. get: function () {
  30645. return Mesh._BACKSIDE;
  30646. },
  30647. enumerable: true,
  30648. configurable: true
  30649. });
  30650. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30651. /**
  30652. * Mesh side orientation : both internal and external or front and back surfaces
  30653. */
  30654. get: function () {
  30655. return Mesh._DOUBLESIDE;
  30656. },
  30657. enumerable: true,
  30658. configurable: true
  30659. });
  30660. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30661. /**
  30662. * Mesh side orientation : by default, `FRONTSIDE`
  30663. */
  30664. get: function () {
  30665. return Mesh._DEFAULTSIDE;
  30666. },
  30667. enumerable: true,
  30668. configurable: true
  30669. });
  30670. Object.defineProperty(Mesh, "NO_CAP", {
  30671. /**
  30672. * Mesh cap setting : no cap
  30673. */
  30674. get: function () {
  30675. return Mesh._NO_CAP;
  30676. },
  30677. enumerable: true,
  30678. configurable: true
  30679. });
  30680. Object.defineProperty(Mesh, "CAP_START", {
  30681. /**
  30682. * Mesh cap setting : one cap at the beginning of the mesh
  30683. */
  30684. get: function () {
  30685. return Mesh._CAP_START;
  30686. },
  30687. enumerable: true,
  30688. configurable: true
  30689. });
  30690. Object.defineProperty(Mesh, "CAP_END", {
  30691. /**
  30692. * Mesh cap setting : one cap at the end of the mesh
  30693. */
  30694. get: function () {
  30695. return Mesh._CAP_END;
  30696. },
  30697. enumerable: true,
  30698. configurable: true
  30699. });
  30700. Object.defineProperty(Mesh, "CAP_ALL", {
  30701. /**
  30702. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30703. */
  30704. get: function () {
  30705. return Mesh._CAP_ALL;
  30706. },
  30707. enumerable: true,
  30708. configurable: true
  30709. });
  30710. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  30711. /**
  30712. * An event triggered before rendering the mesh
  30713. */
  30714. get: function () {
  30715. if (!this._onBeforeRenderObservable) {
  30716. this._onBeforeRenderObservable = new BABYLON.Observable();
  30717. }
  30718. return this._onBeforeRenderObservable;
  30719. },
  30720. enumerable: true,
  30721. configurable: true
  30722. });
  30723. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  30724. /**
  30725. * An event triggered after rendering the mesh
  30726. */
  30727. get: function () {
  30728. if (!this._onAfterRenderObservable) {
  30729. this._onAfterRenderObservable = new BABYLON.Observable();
  30730. }
  30731. return this._onAfterRenderObservable;
  30732. },
  30733. enumerable: true,
  30734. configurable: true
  30735. });
  30736. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  30737. /**
  30738. * An event triggered before drawing the mesh
  30739. */
  30740. get: function () {
  30741. if (!this._onBeforeDrawObservable) {
  30742. this._onBeforeDrawObservable = new BABYLON.Observable();
  30743. }
  30744. return this._onBeforeDrawObservable;
  30745. },
  30746. enumerable: true,
  30747. configurable: true
  30748. });
  30749. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30750. set: function (callback) {
  30751. if (this._onBeforeDrawObserver) {
  30752. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30753. }
  30754. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30755. },
  30756. enumerable: true,
  30757. configurable: true
  30758. });
  30759. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30760. get: function () {
  30761. return this._morphTargetManager;
  30762. },
  30763. set: function (value) {
  30764. if (this._morphTargetManager === value) {
  30765. return;
  30766. }
  30767. this._morphTargetManager = value;
  30768. this._syncGeometryWithMorphTargetManager();
  30769. },
  30770. enumerable: true,
  30771. configurable: true
  30772. });
  30773. Object.defineProperty(Mesh.prototype, "source", {
  30774. get: function () {
  30775. return this._source;
  30776. },
  30777. enumerable: true,
  30778. configurable: true
  30779. });
  30780. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30781. get: function () {
  30782. return this._unIndexed;
  30783. },
  30784. set: function (value) {
  30785. if (this._unIndexed !== value) {
  30786. this._unIndexed = value;
  30787. this._markSubMeshesAsAttributesDirty();
  30788. }
  30789. },
  30790. enumerable: true,
  30791. configurable: true
  30792. });
  30793. // Methods
  30794. /**
  30795. * Returns the string "Mesh".
  30796. */
  30797. Mesh.prototype.getClassName = function () {
  30798. return "Mesh";
  30799. };
  30800. /**
  30801. * Returns a string.
  30802. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30803. */
  30804. Mesh.prototype.toString = function (fullDetails) {
  30805. var ret = _super.prototype.toString.call(this, fullDetails);
  30806. ret += ", n vertices: " + this.getTotalVertices();
  30807. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30808. if (this.animations) {
  30809. for (var i = 0; i < this.animations.length; i++) {
  30810. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30811. }
  30812. }
  30813. if (fullDetails) {
  30814. if (this._geometry) {
  30815. var ib = this.getIndices();
  30816. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30817. if (vb && ib) {
  30818. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30819. }
  30820. }
  30821. else {
  30822. ret += ", flat shading: UNKNOWN";
  30823. }
  30824. }
  30825. return ret;
  30826. };
  30827. /** @hidden */
  30828. Mesh.prototype._unBindEffect = function () {
  30829. _super.prototype._unBindEffect.call(this);
  30830. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  30831. var instance = _a[_i];
  30832. instance._unBindEffect();
  30833. }
  30834. };
  30835. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30836. /**
  30837. * True if the mesh has some Levels Of Details (LOD).
  30838. * Returns a boolean.
  30839. */
  30840. get: function () {
  30841. return this._LODLevels.length > 0;
  30842. },
  30843. enumerable: true,
  30844. configurable: true
  30845. });
  30846. /**
  30847. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30848. * @returns an array of {BABYLON.MeshLODLevel}
  30849. */
  30850. Mesh.prototype.getLODLevels = function () {
  30851. return this._LODLevels;
  30852. };
  30853. Mesh.prototype._sortLODLevels = function () {
  30854. this._LODLevels.sort(function (a, b) {
  30855. if (a.distance < b.distance) {
  30856. return 1;
  30857. }
  30858. if (a.distance > b.distance) {
  30859. return -1;
  30860. }
  30861. return 0;
  30862. });
  30863. };
  30864. /**
  30865. * Add a mesh as LOD level triggered at the given distance.
  30866. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30867. * @param distance The distance from the center of the object to show this level
  30868. * @param mesh The mesh to be added as LOD level (can be null)
  30869. * @return This mesh (for chaining)
  30870. */
  30871. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30872. if (mesh && mesh._masterMesh) {
  30873. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30874. return this;
  30875. }
  30876. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30877. this._LODLevels.push(level);
  30878. if (mesh) {
  30879. mesh._masterMesh = this;
  30880. }
  30881. this._sortLODLevels();
  30882. return this;
  30883. };
  30884. /**
  30885. * Returns the LOD level mesh at the passed distance or null if not found.
  30886. * It is related to the method `addLODLevel(distance, mesh)`.
  30887. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30888. * Returns an object Mesh or `null`.
  30889. */
  30890. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30891. for (var index = 0; index < this._LODLevels.length; index++) {
  30892. var level = this._LODLevels[index];
  30893. if (level.distance === distance) {
  30894. return level.mesh;
  30895. }
  30896. }
  30897. return null;
  30898. };
  30899. /**
  30900. * Remove a mesh from the LOD array
  30901. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30902. * @param {Mesh} mesh The mesh to be removed.
  30903. * @return {Mesh} This mesh (for chaining)
  30904. */
  30905. Mesh.prototype.removeLODLevel = function (mesh) {
  30906. for (var index = 0; index < this._LODLevels.length; index++) {
  30907. if (this._LODLevels[index].mesh === mesh) {
  30908. this._LODLevels.splice(index, 1);
  30909. if (mesh) {
  30910. mesh._masterMesh = null;
  30911. }
  30912. }
  30913. }
  30914. this._sortLODLevels();
  30915. return this;
  30916. };
  30917. /**
  30918. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30919. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  30920. */
  30921. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30922. if (!this._LODLevels || this._LODLevels.length === 0) {
  30923. return this;
  30924. }
  30925. var bSphere;
  30926. if (boundingSphere) {
  30927. bSphere = boundingSphere;
  30928. }
  30929. else {
  30930. var boundingInfo = this.getBoundingInfo();
  30931. bSphere = boundingInfo.boundingSphere;
  30932. }
  30933. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30934. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30935. if (this.onLODLevelSelection) {
  30936. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30937. }
  30938. return this;
  30939. }
  30940. for (var index = 0; index < this._LODLevels.length; index++) {
  30941. var level = this._LODLevels[index];
  30942. if (level.distance < distanceToCamera) {
  30943. if (level.mesh) {
  30944. level.mesh._preActivate();
  30945. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30946. }
  30947. if (this.onLODLevelSelection) {
  30948. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30949. }
  30950. return level.mesh;
  30951. }
  30952. }
  30953. if (this.onLODLevelSelection) {
  30954. this.onLODLevelSelection(distanceToCamera, this, this);
  30955. }
  30956. return this;
  30957. };
  30958. Object.defineProperty(Mesh.prototype, "geometry", {
  30959. /**
  30960. * Returns the mesh internal Geometry object.
  30961. */
  30962. get: function () {
  30963. return this._geometry;
  30964. },
  30965. enumerable: true,
  30966. configurable: true
  30967. });
  30968. /**
  30969. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30970. */
  30971. Mesh.prototype.getTotalVertices = function () {
  30972. if (this._geometry === null || this._geometry === undefined) {
  30973. return 0;
  30974. }
  30975. return this._geometry.getTotalVertices();
  30976. };
  30977. /**
  30978. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30979. * 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.
  30980. * You can force the copy with forceCopy === true
  30981. * Returns null if the mesh has no geometry or no vertex buffer.
  30982. * Possible `kind` values :
  30983. * - BABYLON.VertexBuffer.PositionKind
  30984. * - BABYLON.VertexBuffer.UVKind
  30985. * - BABYLON.VertexBuffer.UV2Kind
  30986. * - BABYLON.VertexBuffer.UV3Kind
  30987. * - BABYLON.VertexBuffer.UV4Kind
  30988. * - BABYLON.VertexBuffer.UV5Kind
  30989. * - BABYLON.VertexBuffer.UV6Kind
  30990. * - BABYLON.VertexBuffer.ColorKind
  30991. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30992. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30993. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30994. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30995. */
  30996. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30997. if (!this._geometry) {
  30998. return null;
  30999. }
  31000. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31001. };
  31002. /**
  31003. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31004. * Returns `null` if the mesh has no geometry.
  31005. * Possible `kind` values :
  31006. * - BABYLON.VertexBuffer.PositionKind
  31007. * - BABYLON.VertexBuffer.UVKind
  31008. * - BABYLON.VertexBuffer.UV2Kind
  31009. * - BABYLON.VertexBuffer.UV3Kind
  31010. * - BABYLON.VertexBuffer.UV4Kind
  31011. * - BABYLON.VertexBuffer.UV5Kind
  31012. * - BABYLON.VertexBuffer.UV6Kind
  31013. * - BABYLON.VertexBuffer.ColorKind
  31014. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31015. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31016. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31017. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31018. */
  31019. Mesh.prototype.getVertexBuffer = function (kind) {
  31020. if (!this._geometry) {
  31021. return null;
  31022. }
  31023. return this._geometry.getVertexBuffer(kind);
  31024. };
  31025. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31026. if (!this._geometry) {
  31027. if (this._delayInfo) {
  31028. return this._delayInfo.indexOf(kind) !== -1;
  31029. }
  31030. return false;
  31031. }
  31032. return this._geometry.isVerticesDataPresent(kind);
  31033. };
  31034. /**
  31035. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31036. * Possible `kind` values :
  31037. * - BABYLON.VertexBuffer.PositionKind
  31038. * - BABYLON.VertexBuffer.UVKind
  31039. * - BABYLON.VertexBuffer.UV2Kind
  31040. * - BABYLON.VertexBuffer.UV3Kind
  31041. * - BABYLON.VertexBuffer.UV4Kind
  31042. * - BABYLON.VertexBuffer.UV5Kind
  31043. * - BABYLON.VertexBuffer.UV6Kind
  31044. * - BABYLON.VertexBuffer.ColorKind
  31045. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31046. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31047. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31048. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31049. */
  31050. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31051. if (!this._geometry) {
  31052. if (this._delayInfo) {
  31053. return this._delayInfo.indexOf(kind) !== -1;
  31054. }
  31055. return false;
  31056. }
  31057. return this._geometry.isVertexBufferUpdatable(kind);
  31058. };
  31059. /**
  31060. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31061. * Possible `kind` values :
  31062. * - BABYLON.VertexBuffer.PositionKind
  31063. * - BABYLON.VertexBuffer.UVKind
  31064. * - BABYLON.VertexBuffer.UV2Kind
  31065. * - BABYLON.VertexBuffer.UV3Kind
  31066. * - BABYLON.VertexBuffer.UV4Kind
  31067. * - BABYLON.VertexBuffer.UV5Kind
  31068. * - BABYLON.VertexBuffer.UV6Kind
  31069. * - BABYLON.VertexBuffer.ColorKind
  31070. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31071. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31072. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31073. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31074. */
  31075. Mesh.prototype.getVerticesDataKinds = function () {
  31076. if (!this._geometry) {
  31077. var result = new Array();
  31078. if (this._delayInfo) {
  31079. this._delayInfo.forEach(function (kind, index, array) {
  31080. result.push(kind);
  31081. });
  31082. }
  31083. return result;
  31084. }
  31085. return this._geometry.getVerticesDataKinds();
  31086. };
  31087. /**
  31088. * Returns a positive integer : the total number of indices in this mesh geometry.
  31089. * Returns zero if the mesh has no geometry.
  31090. */
  31091. Mesh.prototype.getTotalIndices = function () {
  31092. if (!this._geometry) {
  31093. return 0;
  31094. }
  31095. return this._geometry.getTotalIndices();
  31096. };
  31097. /**
  31098. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31099. * @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.
  31100. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31101. * @returns the indices array or an empty array if the mesh has no geometry
  31102. */
  31103. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31104. if (!this._geometry) {
  31105. return [];
  31106. }
  31107. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31108. };
  31109. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31110. get: function () {
  31111. return this._masterMesh !== null && this._masterMesh !== undefined;
  31112. },
  31113. enumerable: true,
  31114. configurable: true
  31115. });
  31116. /**
  31117. * Determine if the current mesh is ready to be rendered
  31118. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31119. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31120. * @returns true if all associated assets are ready (material, textures, shaders)
  31121. */
  31122. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31123. if (completeCheck === void 0) { completeCheck = false; }
  31124. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31125. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31126. return false;
  31127. }
  31128. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31129. return false;
  31130. }
  31131. if (!this.subMeshes || this.subMeshes.length === 0) {
  31132. return true;
  31133. }
  31134. if (!completeCheck) {
  31135. return true;
  31136. }
  31137. var engine = this.getEngine();
  31138. var scene = this.getScene();
  31139. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31140. this.computeWorldMatrix();
  31141. var mat = this.material || scene.defaultMaterial;
  31142. if (mat) {
  31143. if (mat.storeEffectOnSubMeshes) {
  31144. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31145. var subMesh = _a[_i];
  31146. var effectiveMaterial = subMesh.getMaterial();
  31147. if (effectiveMaterial) {
  31148. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31149. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31150. return false;
  31151. }
  31152. }
  31153. else {
  31154. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31155. return false;
  31156. }
  31157. }
  31158. }
  31159. }
  31160. }
  31161. else {
  31162. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31163. return false;
  31164. }
  31165. }
  31166. }
  31167. // Shadows
  31168. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31169. var light = _c[_b];
  31170. var generator = light.getShadowGenerator();
  31171. if (generator) {
  31172. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31173. var subMesh = _e[_d];
  31174. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31175. return false;
  31176. }
  31177. }
  31178. }
  31179. }
  31180. // LOD
  31181. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31182. var lod = _g[_f];
  31183. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31184. return false;
  31185. }
  31186. }
  31187. return true;
  31188. };
  31189. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31190. /**
  31191. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31192. * This property is pertinent only for updatable parametric shapes.
  31193. */
  31194. get: function () {
  31195. return this._areNormalsFrozen;
  31196. },
  31197. enumerable: true,
  31198. configurable: true
  31199. });
  31200. /**
  31201. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31202. * It has no effect at all on other shapes.
  31203. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31204. * Returns the Mesh.
  31205. */
  31206. Mesh.prototype.freezeNormals = function () {
  31207. this._areNormalsFrozen = true;
  31208. return this;
  31209. };
  31210. /**
  31211. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31212. * It has no effect at all on other shapes.
  31213. * It reactivates the mesh normals computation if it was previously frozen.
  31214. * Returns the Mesh.
  31215. */
  31216. Mesh.prototype.unfreezeNormals = function () {
  31217. this._areNormalsFrozen = false;
  31218. return this;
  31219. };
  31220. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31221. /**
  31222. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31223. */
  31224. set: function (count) {
  31225. this._overridenInstanceCount = count;
  31226. },
  31227. enumerable: true,
  31228. configurable: true
  31229. });
  31230. // Methods
  31231. /** @hidden */
  31232. Mesh.prototype._preActivate = function () {
  31233. var sceneRenderId = this.getScene().getRenderId();
  31234. if (this._preActivateId === sceneRenderId) {
  31235. return this;
  31236. }
  31237. this._preActivateId = sceneRenderId;
  31238. this._visibleInstances = null;
  31239. return this;
  31240. };
  31241. /** @hidden */
  31242. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31243. if (this._visibleInstances) {
  31244. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31245. }
  31246. return this;
  31247. };
  31248. /** @hidden */
  31249. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31250. if (!this._visibleInstances) {
  31251. this._visibleInstances = {};
  31252. this._visibleInstances.defaultRenderId = renderId;
  31253. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31254. }
  31255. if (!this._visibleInstances[renderId]) {
  31256. this._visibleInstances[renderId] = new Array();
  31257. }
  31258. this._visibleInstances[renderId].push(instance);
  31259. return this;
  31260. };
  31261. /**
  31262. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31263. * This means the mesh underlying bounding box and sphere are recomputed.
  31264. * Returns the Mesh.
  31265. */
  31266. Mesh.prototype.refreshBoundingInfo = function () {
  31267. return this._refreshBoundingInfo(false);
  31268. };
  31269. /** @hidden */
  31270. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31271. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31272. return this;
  31273. }
  31274. var data = this._getPositionData(applySkeleton);
  31275. if (data) {
  31276. var bias = this.geometry ? this.geometry.boundingBias : null;
  31277. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31278. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31279. }
  31280. if (this.subMeshes) {
  31281. for (var index = 0; index < this.subMeshes.length; index++) {
  31282. this.subMeshes[index].refreshBoundingInfo();
  31283. }
  31284. }
  31285. this._updateBoundingInfo();
  31286. return this;
  31287. };
  31288. Mesh.prototype._getPositionData = function (applySkeleton) {
  31289. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31290. if (data && applySkeleton && this.skeleton) {
  31291. data = BABYLON.Tools.Slice(data);
  31292. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31293. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31294. if (matricesWeightsData && matricesIndicesData) {
  31295. var needExtras = this.numBoneInfluencers > 4;
  31296. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31297. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31298. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31299. var tempVector = BABYLON.Tmp.Vector3[0];
  31300. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31301. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31302. var matWeightIdx = 0;
  31303. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31304. finalMatrix.reset();
  31305. var inf;
  31306. var weight;
  31307. for (inf = 0; inf < 4; inf++) {
  31308. weight = matricesWeightsData[matWeightIdx + inf];
  31309. if (weight > 0) {
  31310. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31311. finalMatrix.addToSelf(tempMatrix);
  31312. }
  31313. }
  31314. if (needExtras) {
  31315. for (inf = 0; inf < 4; inf++) {
  31316. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31317. if (weight > 0) {
  31318. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31319. finalMatrix.addToSelf(tempMatrix);
  31320. }
  31321. }
  31322. }
  31323. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31324. tempVector.toArray(data, index);
  31325. }
  31326. }
  31327. }
  31328. return data;
  31329. };
  31330. /** @hidden */
  31331. Mesh.prototype._createGlobalSubMesh = function (force) {
  31332. var totalVertices = this.getTotalVertices();
  31333. if (!totalVertices || !this.getIndices()) {
  31334. return null;
  31335. }
  31336. // Check if we need to recreate the submeshes
  31337. if (this.subMeshes && this.subMeshes.length > 0) {
  31338. var ib = this.getIndices();
  31339. if (!ib) {
  31340. return null;
  31341. }
  31342. var totalIndices = ib.length;
  31343. var needToRecreate = false;
  31344. if (force) {
  31345. needToRecreate = true;
  31346. }
  31347. else {
  31348. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31349. var submesh = _a[_i];
  31350. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31351. needToRecreate = true;
  31352. break;
  31353. }
  31354. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31355. needToRecreate = true;
  31356. break;
  31357. }
  31358. }
  31359. }
  31360. if (!needToRecreate) {
  31361. return this.subMeshes[0];
  31362. }
  31363. }
  31364. this.releaseSubMeshes();
  31365. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31366. };
  31367. Mesh.prototype.subdivide = function (count) {
  31368. if (count < 1) {
  31369. return;
  31370. }
  31371. var totalIndices = this.getTotalIndices();
  31372. var subdivisionSize = (totalIndices / count) | 0;
  31373. var offset = 0;
  31374. // Ensure that subdivisionSize is a multiple of 3
  31375. while (subdivisionSize % 3 !== 0) {
  31376. subdivisionSize++;
  31377. }
  31378. this.releaseSubMeshes();
  31379. for (var index = 0; index < count; index++) {
  31380. if (offset >= totalIndices) {
  31381. break;
  31382. }
  31383. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31384. offset += subdivisionSize;
  31385. }
  31386. this.synchronizeInstances();
  31387. };
  31388. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31389. if (updatable === void 0) { updatable = false; }
  31390. if (!this._geometry) {
  31391. var vertexData = new BABYLON.VertexData();
  31392. vertexData.set(data, kind);
  31393. var scene = this.getScene();
  31394. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31395. }
  31396. else {
  31397. this._geometry.setVerticesData(kind, data, updatable, stride);
  31398. }
  31399. return this;
  31400. };
  31401. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31402. if (updatable === void 0) { updatable = true; }
  31403. var vb = this.getVertexBuffer(kind);
  31404. if (!vb || vb.isUpdatable() === updatable) {
  31405. return;
  31406. }
  31407. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31408. };
  31409. /**
  31410. * Sets the mesh VertexBuffer.
  31411. * Returns the Mesh.
  31412. */
  31413. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31414. if (!this._geometry) {
  31415. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31416. }
  31417. this._geometry.setVerticesBuffer(buffer);
  31418. return this;
  31419. };
  31420. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31421. if (!this._geometry) {
  31422. return this;
  31423. }
  31424. if (!makeItUnique) {
  31425. this._geometry.updateVerticesData(kind, data, updateExtends);
  31426. }
  31427. else {
  31428. this.makeGeometryUnique();
  31429. this.updateVerticesData(kind, data, updateExtends, false);
  31430. }
  31431. return this;
  31432. };
  31433. /**
  31434. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31435. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31436. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31437. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31438. * Returns the Mesh.
  31439. */
  31440. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31441. if (computeNormals === void 0) { computeNormals = true; }
  31442. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31443. if (!positions) {
  31444. return this;
  31445. }
  31446. positionFunction(positions);
  31447. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31448. if (computeNormals) {
  31449. var indices = this.getIndices();
  31450. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31451. if (!normals) {
  31452. return this;
  31453. }
  31454. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31455. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31456. }
  31457. return this;
  31458. };
  31459. /**
  31460. * Creates a un-shared specific occurence of the geometry for the mesh.
  31461. * Returns the Mesh.
  31462. */
  31463. Mesh.prototype.makeGeometryUnique = function () {
  31464. if (!this._geometry) {
  31465. return this;
  31466. }
  31467. var oldGeometry = this._geometry;
  31468. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31469. oldGeometry.releaseForMesh(this, true);
  31470. geometry.applyToMesh(this);
  31471. return this;
  31472. };
  31473. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31474. if (totalVertices === void 0) { totalVertices = null; }
  31475. if (updatable === void 0) { updatable = false; }
  31476. if (!this._geometry) {
  31477. var vertexData = new BABYLON.VertexData();
  31478. vertexData.indices = indices;
  31479. var scene = this.getScene();
  31480. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31481. }
  31482. else {
  31483. this._geometry.setIndices(indices, totalVertices, updatable);
  31484. }
  31485. return this;
  31486. };
  31487. /**
  31488. * Update the current index buffer
  31489. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31490. * Returns the Mesh.
  31491. */
  31492. Mesh.prototype.updateIndices = function (indices, offset) {
  31493. if (!this._geometry) {
  31494. return this;
  31495. }
  31496. this._geometry.updateIndices(indices, offset);
  31497. return this;
  31498. };
  31499. /**
  31500. * Invert the geometry to move from a right handed system to a left handed one.
  31501. * Returns the Mesh.
  31502. */
  31503. Mesh.prototype.toLeftHanded = function () {
  31504. if (!this._geometry) {
  31505. return this;
  31506. }
  31507. this._geometry.toLeftHanded();
  31508. return this;
  31509. };
  31510. /** @hidden */
  31511. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31512. if (!this._geometry) {
  31513. return this;
  31514. }
  31515. var engine = this.getScene().getEngine();
  31516. // Wireframe
  31517. var indexToBind;
  31518. if (this._unIndexed) {
  31519. indexToBind = null;
  31520. }
  31521. else {
  31522. switch (fillMode) {
  31523. case BABYLON.Material.PointFillMode:
  31524. indexToBind = null;
  31525. break;
  31526. case BABYLON.Material.WireFrameFillMode:
  31527. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31528. break;
  31529. default:
  31530. case BABYLON.Material.TriangleFillMode:
  31531. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31532. break;
  31533. }
  31534. }
  31535. // VBOs
  31536. this._geometry._bind(effect, indexToBind);
  31537. return this;
  31538. };
  31539. /** @hidden */
  31540. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31541. if (alternate === void 0) { alternate = false; }
  31542. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31543. return this;
  31544. }
  31545. if (this._onBeforeDrawObservable) {
  31546. this._onBeforeDrawObservable.notifyObservers(this);
  31547. }
  31548. var scene = this.getScene();
  31549. var engine = scene.getEngine();
  31550. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31551. // or triangles as points
  31552. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31553. }
  31554. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31555. // Triangles as wireframe
  31556. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31557. }
  31558. else {
  31559. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31560. }
  31561. if (scene._isAlternateRenderingEnabled && !alternate) {
  31562. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31563. if (!effect || !scene.activeCamera) {
  31564. return this;
  31565. }
  31566. scene._switchToAlternateCameraConfiguration(true);
  31567. this._effectiveMaterial.bindView(effect);
  31568. this._effectiveMaterial.bindViewProjection(effect);
  31569. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31570. this._draw(subMesh, fillMode, instancesCount, true);
  31571. engine.setViewport(scene.activeCamera.viewport);
  31572. scene._switchToAlternateCameraConfiguration(false);
  31573. this._effectiveMaterial.bindView(effect);
  31574. this._effectiveMaterial.bindViewProjection(effect);
  31575. }
  31576. return this;
  31577. };
  31578. /**
  31579. * Registers for this mesh a javascript function called just before the rendering process.
  31580. * This function is passed the current mesh.
  31581. * Return the Mesh.
  31582. */
  31583. Mesh.prototype.registerBeforeRender = function (func) {
  31584. this.onBeforeRenderObservable.add(func);
  31585. return this;
  31586. };
  31587. /**
  31588. * Disposes a previously registered javascript function called before the rendering.
  31589. * This function is passed the current mesh.
  31590. * Returns the Mesh.
  31591. */
  31592. Mesh.prototype.unregisterBeforeRender = function (func) {
  31593. this.onBeforeRenderObservable.removeCallback(func);
  31594. return this;
  31595. };
  31596. /**
  31597. * Registers for this mesh a javascript function called just after the rendering is complete.
  31598. * This function is passed the current mesh.
  31599. * Returns the Mesh.
  31600. */
  31601. Mesh.prototype.registerAfterRender = function (func) {
  31602. this.onAfterRenderObservable.add(func);
  31603. return this;
  31604. };
  31605. /**
  31606. * Disposes a previously registered javascript function called after the rendering.
  31607. * This function is passed the current mesh.
  31608. * Return the Mesh.
  31609. */
  31610. Mesh.prototype.unregisterAfterRender = function (func) {
  31611. this.onAfterRenderObservable.removeCallback(func);
  31612. return this;
  31613. };
  31614. /** @hidden */
  31615. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31616. var scene = this.getScene();
  31617. this._batchCache.mustReturn = false;
  31618. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31619. this._batchCache.visibleInstances[subMeshId] = null;
  31620. if (this._visibleInstances) {
  31621. var currentRenderId = scene.getRenderId();
  31622. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31623. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31624. var selfRenderId = this._renderId;
  31625. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31626. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31627. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31628. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31629. }
  31630. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31631. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31632. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31633. this._batchCache.mustReturn = true;
  31634. return this._batchCache;
  31635. }
  31636. if (currentRenderId !== selfRenderId) {
  31637. this._batchCache.renderSelf[subMeshId] = false;
  31638. }
  31639. }
  31640. this._renderIdForInstances[subMeshId] = currentRenderId;
  31641. }
  31642. return this._batchCache;
  31643. };
  31644. /** @hidden */
  31645. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31646. var visibleInstances = batch.visibleInstances[subMesh._id];
  31647. if (!visibleInstances) {
  31648. return this;
  31649. }
  31650. var matricesCount = visibleInstances.length + 1;
  31651. var bufferSize = matricesCount * 16 * 4;
  31652. var currentInstancesBufferSize = this._instancesBufferSize;
  31653. var instancesBuffer = this._instancesBuffer;
  31654. while (this._instancesBufferSize < bufferSize) {
  31655. this._instancesBufferSize *= 2;
  31656. }
  31657. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31658. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31659. }
  31660. var offset = 0;
  31661. var instancesCount = 0;
  31662. var world = this.getWorldMatrix();
  31663. if (batch.renderSelf[subMesh._id]) {
  31664. world.copyToArray(this._instancesData, offset);
  31665. offset += 16;
  31666. instancesCount++;
  31667. }
  31668. if (visibleInstances) {
  31669. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31670. var instance = visibleInstances[instanceIndex];
  31671. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31672. offset += 16;
  31673. instancesCount++;
  31674. }
  31675. }
  31676. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31677. if (instancesBuffer) {
  31678. instancesBuffer.dispose();
  31679. }
  31680. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31681. this._instancesBuffer = instancesBuffer;
  31682. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31683. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31684. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31685. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31686. }
  31687. else {
  31688. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31689. }
  31690. this._bind(subMesh, effect, fillMode);
  31691. this._draw(subMesh, fillMode, instancesCount);
  31692. engine.unbindInstanceAttributes();
  31693. return this;
  31694. };
  31695. /** @hidden */
  31696. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31697. var scene = this.getScene();
  31698. var engine = scene.getEngine();
  31699. if (hardwareInstancedRendering) {
  31700. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31701. }
  31702. else {
  31703. if (batch.renderSelf[subMesh._id]) {
  31704. // Draw
  31705. if (onBeforeDraw) {
  31706. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31707. }
  31708. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31709. }
  31710. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31711. if (visibleInstancesForSubMesh) {
  31712. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31713. var instance = visibleInstancesForSubMesh[instanceIndex];
  31714. // World
  31715. var world = instance.getWorldMatrix();
  31716. if (onBeforeDraw) {
  31717. onBeforeDraw(true, world, effectiveMaterial);
  31718. }
  31719. // Draw
  31720. this._draw(subMesh, fillMode);
  31721. }
  31722. }
  31723. }
  31724. return this;
  31725. };
  31726. /**
  31727. * 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
  31728. * @param subMesh defines the subMesh to render
  31729. * @param enableAlphaMode defines if alpha mode can be changed
  31730. * @returns the current mesh
  31731. */
  31732. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31733. this._checkOcclusionQuery();
  31734. if (this._isOccluded) {
  31735. return this;
  31736. }
  31737. var scene = this.getScene();
  31738. // Managing instances
  31739. var batch = this._getInstancesRenderList(subMesh._id);
  31740. if (batch.mustReturn) {
  31741. return this;
  31742. }
  31743. // Checking geometry state
  31744. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31745. return this;
  31746. }
  31747. if (this._onBeforeRenderObservable) {
  31748. this._onBeforeRenderObservable.notifyObservers(this);
  31749. }
  31750. var engine = scene.getEngine();
  31751. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31752. // Material
  31753. var material = subMesh.getMaterial();
  31754. if (!material) {
  31755. return this;
  31756. }
  31757. this._effectiveMaterial = material;
  31758. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31759. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31760. return this;
  31761. }
  31762. }
  31763. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31764. return this;
  31765. }
  31766. // Alpha mode
  31767. if (enableAlphaMode) {
  31768. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31769. }
  31770. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  31771. var step = _a[_i];
  31772. step.action(this, subMesh, batch);
  31773. }
  31774. var effect;
  31775. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31776. effect = subMesh.effect;
  31777. }
  31778. else {
  31779. effect = this._effectiveMaterial.getEffect();
  31780. }
  31781. if (!effect) {
  31782. return this;
  31783. }
  31784. var sideOrientation = this.overrideMaterialSideOrientation;
  31785. if (sideOrientation == null) {
  31786. sideOrientation = this._effectiveMaterial.sideOrientation;
  31787. if (this._getWorldMatrixDeterminant() < 0) {
  31788. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31789. }
  31790. }
  31791. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31792. if (this._effectiveMaterial.forceDepthWrite) {
  31793. engine.setDepthWrite(true);
  31794. }
  31795. // Bind
  31796. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31797. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  31798. this._bind(subMesh, effect, fillMode);
  31799. }
  31800. var world = this.getWorldMatrix();
  31801. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31802. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31803. }
  31804. else {
  31805. this._effectiveMaterial.bind(world, this);
  31806. }
  31807. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31808. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31809. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31810. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31811. }
  31812. // Draw
  31813. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31814. // Unbind
  31815. this._effectiveMaterial.unbind();
  31816. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  31817. var step = _c[_b];
  31818. step.action(this, subMesh, batch);
  31819. }
  31820. if (this._onAfterRenderObservable) {
  31821. this._onAfterRenderObservable.notifyObservers(this);
  31822. }
  31823. return this;
  31824. };
  31825. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31826. if (isInstance && effectiveMaterial) {
  31827. effectiveMaterial.bindOnlyWorldMatrix(world);
  31828. }
  31829. };
  31830. /**
  31831. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  31832. */
  31833. Mesh.prototype.getEmittedParticleSystems = function () {
  31834. var results = new Array();
  31835. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31836. var particleSystem = this.getScene().particleSystems[index];
  31837. if (particleSystem.emitter === this) {
  31838. results.push(particleSystem);
  31839. }
  31840. }
  31841. return results;
  31842. };
  31843. /**
  31844. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  31845. */
  31846. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31847. var results = new Array();
  31848. var descendants = this.getDescendants();
  31849. descendants.push(this);
  31850. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31851. var particleSystem = this.getScene().particleSystems[index];
  31852. var emitter = particleSystem.emitter;
  31853. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31854. results.push(particleSystem);
  31855. }
  31856. }
  31857. return results;
  31858. };
  31859. /**
  31860. * Normalize matrix weights so that all vertices have a total weight set to 1
  31861. */
  31862. Mesh.prototype.cleanMatrixWeights = function () {
  31863. var epsilon = 1e-3;
  31864. var noInfluenceBoneIndex = 0.0;
  31865. if (this.skeleton) {
  31866. noInfluenceBoneIndex = this.skeleton.bones.length;
  31867. }
  31868. else {
  31869. return;
  31870. }
  31871. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31872. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31873. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31874. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31875. var influencers = this.numBoneInfluencers;
  31876. var size = matricesWeights.length;
  31877. for (var i = 0; i < size; i += 4) {
  31878. var weight = 0.0;
  31879. var firstZeroWeight = -1;
  31880. for (var j = 0; j < 4; j++) {
  31881. var w = matricesWeights[i + j];
  31882. weight += w;
  31883. if (w < epsilon && firstZeroWeight < 0) {
  31884. firstZeroWeight = j;
  31885. }
  31886. }
  31887. if (matricesWeightsExtra) {
  31888. for (var j = 0; j < 4; j++) {
  31889. var w = matricesWeightsExtra[i + j];
  31890. weight += w;
  31891. if (w < epsilon && firstZeroWeight < 0) {
  31892. firstZeroWeight = j + 4;
  31893. }
  31894. }
  31895. }
  31896. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31897. firstZeroWeight = influencers - 1;
  31898. }
  31899. if (weight > epsilon) {
  31900. var mweight = 1.0 / weight;
  31901. for (var j = 0; j < 4; j++) {
  31902. matricesWeights[i + j] *= mweight;
  31903. }
  31904. if (matricesWeightsExtra) {
  31905. for (var j = 0; j < 4; j++) {
  31906. matricesWeightsExtra[i + j] *= mweight;
  31907. }
  31908. }
  31909. }
  31910. else {
  31911. if (firstZeroWeight >= 4) {
  31912. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31913. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31914. }
  31915. else {
  31916. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31917. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31918. }
  31919. }
  31920. }
  31921. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31922. if (matricesIndicesExtra) {
  31923. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31924. }
  31925. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  31926. if (matricesWeightsExtra) {
  31927. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  31928. }
  31929. };
  31930. /** @hidden */
  31931. Mesh.prototype._checkDelayState = function () {
  31932. var scene = this.getScene();
  31933. if (this._geometry) {
  31934. this._geometry.load(scene);
  31935. }
  31936. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31937. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31938. this._queueLoad(scene);
  31939. }
  31940. return this;
  31941. };
  31942. Mesh.prototype._queueLoad = function (scene) {
  31943. var _this = this;
  31944. scene._addPendingData(this);
  31945. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31946. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31947. if (data instanceof ArrayBuffer) {
  31948. _this._delayLoadingFunction(data, _this);
  31949. }
  31950. else {
  31951. _this._delayLoadingFunction(JSON.parse(data), _this);
  31952. }
  31953. _this.instances.forEach(function (instance) {
  31954. instance._syncSubMeshes();
  31955. });
  31956. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31957. scene._removePendingData(_this);
  31958. }, function () { }, scene.database, getBinaryData);
  31959. return this;
  31960. };
  31961. /**
  31962. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  31963. * A mesh is in the frustum if its bounding box intersects the frustum
  31964. * @param frustumPlanes defines the frustum to test
  31965. * @returns true if the mesh is in the frustum planes
  31966. */
  31967. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31968. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31969. return false;
  31970. }
  31971. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31972. return false;
  31973. }
  31974. this._checkDelayState();
  31975. return true;
  31976. };
  31977. /**
  31978. * Sets the mesh material by the material or multiMaterial `id` property.
  31979. * The material `id` is a string identifying the material or the multiMaterial.
  31980. * This method returns the Mesh.
  31981. */
  31982. Mesh.prototype.setMaterialByID = function (id) {
  31983. var materials = this.getScene().materials;
  31984. var index;
  31985. for (index = materials.length - 1; index > -1; index--) {
  31986. if (materials[index].id === id) {
  31987. this.material = materials[index];
  31988. return this;
  31989. }
  31990. }
  31991. // Multi
  31992. var multiMaterials = this.getScene().multiMaterials;
  31993. for (index = multiMaterials.length - 1; index > -1; index--) {
  31994. if (multiMaterials[index].id === id) {
  31995. this.material = multiMaterials[index];
  31996. return this;
  31997. }
  31998. }
  31999. return this;
  32000. };
  32001. /**
  32002. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32003. */
  32004. Mesh.prototype.getAnimatables = function () {
  32005. var results = new Array();
  32006. if (this.material) {
  32007. results.push(this.material);
  32008. }
  32009. if (this.skeleton) {
  32010. results.push(this.skeleton);
  32011. }
  32012. return results;
  32013. };
  32014. /**
  32015. * Modifies the mesh geometry according to the passed transformation matrix.
  32016. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32017. * The mesh normals are modified using the same transformation.
  32018. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32019. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32020. * Returns the Mesh.
  32021. */
  32022. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32023. // Position
  32024. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32025. return this;
  32026. }
  32027. var submeshes = this.subMeshes.splice(0);
  32028. this._resetPointsArrayCache();
  32029. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32030. var temp = new Array();
  32031. var index;
  32032. for (index = 0; index < data.length; index += 3) {
  32033. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32034. }
  32035. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32036. // Normals
  32037. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32038. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32039. temp = [];
  32040. for (index = 0; index < data.length; index += 3) {
  32041. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32042. }
  32043. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32044. }
  32045. // flip faces?
  32046. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32047. this.flipFaces();
  32048. }
  32049. // Restore submeshes
  32050. this.releaseSubMeshes();
  32051. this.subMeshes = submeshes;
  32052. return this;
  32053. };
  32054. /**
  32055. * Modifies the mesh geometry according to its own current World Matrix.
  32056. * The mesh World Matrix is then reset.
  32057. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32058. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32059. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32060. * Returns the Mesh.
  32061. */
  32062. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32063. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32064. this.scaling.copyFromFloats(1, 1, 1);
  32065. this.position.copyFromFloats(0, 0, 0);
  32066. this.rotation.copyFromFloats(0, 0, 0);
  32067. //only if quaternion is already set
  32068. if (this.rotationQuaternion) {
  32069. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32070. }
  32071. this._worldMatrix = BABYLON.Matrix.Identity();
  32072. return this;
  32073. };
  32074. Object.defineProperty(Mesh.prototype, "_positions", {
  32075. // Cache
  32076. get: function () {
  32077. if (this._geometry) {
  32078. return this._geometry._positions;
  32079. }
  32080. return null;
  32081. },
  32082. enumerable: true,
  32083. configurable: true
  32084. });
  32085. /** @hidden */
  32086. Mesh.prototype._resetPointsArrayCache = function () {
  32087. if (this._geometry) {
  32088. this._geometry._resetPointsArrayCache();
  32089. }
  32090. return this;
  32091. };
  32092. /** @hidden */
  32093. Mesh.prototype._generatePointsArray = function () {
  32094. if (this._geometry) {
  32095. return this._geometry._generatePointsArray();
  32096. }
  32097. return false;
  32098. };
  32099. /**
  32100. * Returns a new Mesh object generated from the current mesh properties.
  32101. * This method must not get confused with createInstance().
  32102. * The parameter `name` is a string, the name given to the new mesh.
  32103. * The optional parameter `newParent` can be any Node object (default `null`).
  32104. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32105. * 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.
  32106. */
  32107. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32108. if (name === void 0) { name = ""; }
  32109. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32110. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32111. };
  32112. /**
  32113. * Releases resources associated with this mesh.
  32114. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32115. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32116. */
  32117. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32118. var _this = this;
  32119. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32120. this.morphTargetManager = null;
  32121. if (this._geometry) {
  32122. this._geometry.releaseForMesh(this, true);
  32123. }
  32124. if (this._onBeforeDrawObservable) {
  32125. this._onBeforeDrawObservable.clear();
  32126. }
  32127. if (this._onBeforeRenderObservable) {
  32128. this._onBeforeRenderObservable.clear();
  32129. }
  32130. if (this._onAfterRenderObservable) {
  32131. this._onAfterRenderObservable.clear();
  32132. }
  32133. // Sources
  32134. var meshes = this.getScene().meshes;
  32135. meshes.forEach(function (abstractMesh) {
  32136. var mesh = abstractMesh;
  32137. if (mesh._source && mesh._source === _this) {
  32138. mesh._source = null;
  32139. }
  32140. });
  32141. this._source = null;
  32142. // Instances
  32143. if (this._instancesBuffer) {
  32144. this._instancesBuffer.dispose();
  32145. this._instancesBuffer = null;
  32146. }
  32147. while (this.instances.length) {
  32148. this.instances[0].dispose();
  32149. }
  32150. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32151. };
  32152. /**
  32153. * Modifies the mesh geometry according to a displacement map.
  32154. * 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.
  32155. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32156. * This method returns nothing.
  32157. * @param url is a string, the URL from the image file is to be downloaded.
  32158. * @param minHeight is the lower limit of the displacement.
  32159. * @param maxHeight is the upper limit of the displacement.
  32160. * @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.
  32161. * @param uvOffset is an optional vector2 used to offset UV.
  32162. * @param uvScale is an optional vector2 used to scale UV.
  32163. * @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.
  32164. * @returns the Mesh.
  32165. */
  32166. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32167. var _this = this;
  32168. if (forceUpdate === void 0) { forceUpdate = false; }
  32169. var scene = this.getScene();
  32170. var onload = function (img) {
  32171. // Getting height map data
  32172. var canvas = document.createElement("canvas");
  32173. var context = canvas.getContext("2d");
  32174. var heightMapWidth = img.width;
  32175. var heightMapHeight = img.height;
  32176. canvas.width = heightMapWidth;
  32177. canvas.height = heightMapHeight;
  32178. context.drawImage(img, 0, 0);
  32179. // Create VertexData from map data
  32180. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32181. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32182. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32183. //execute success callback, if set
  32184. if (onSuccess) {
  32185. onSuccess(_this);
  32186. }
  32187. };
  32188. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32189. return this;
  32190. };
  32191. /**
  32192. * Modifies the mesh geometry according to a displacementMap buffer.
  32193. * 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.
  32194. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32195. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32196. * @param heightMapWidth is the width of the buffer image.
  32197. * @param heightMapHeight is the height of the buffer image.
  32198. * @param minHeight is the lower limit of the displacement.
  32199. * @param maxHeight is the upper limit of the displacement.
  32200. * @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.
  32201. * @param uvOffset is an optional vector2 used to offset UV.
  32202. * @param uvScale is an optional vector2 used to scale UV.
  32203. * @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.
  32204. * @returns the Mesh.
  32205. */
  32206. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32207. if (forceUpdate === void 0) { forceUpdate = false; }
  32208. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32209. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32210. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32211. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32212. return this;
  32213. }
  32214. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32215. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32216. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32217. var position = BABYLON.Vector3.Zero();
  32218. var normal = BABYLON.Vector3.Zero();
  32219. var uv = BABYLON.Vector2.Zero();
  32220. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32221. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32222. for (var index = 0; index < positions.length; index += 3) {
  32223. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32224. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32225. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32226. // Compute height
  32227. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32228. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32229. var pos = (u + v * heightMapWidth) * 4;
  32230. var r = buffer[pos] / 255.0;
  32231. var g = buffer[pos + 1] / 255.0;
  32232. var b = buffer[pos + 2] / 255.0;
  32233. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32234. normal.normalize();
  32235. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32236. position = position.add(normal);
  32237. position.toArray(positions, index);
  32238. }
  32239. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32240. if (forceUpdate) {
  32241. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32242. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32243. }
  32244. else {
  32245. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32246. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32247. }
  32248. return this;
  32249. };
  32250. /**
  32251. * Modify the mesh to get a flat shading rendering.
  32252. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32253. * This method returns the Mesh.
  32254. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32255. */
  32256. Mesh.prototype.convertToFlatShadedMesh = function () {
  32257. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32258. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32259. var kinds = this.getVerticesDataKinds();
  32260. var vbs = {};
  32261. var data = {};
  32262. var newdata = {};
  32263. var updatableNormals = false;
  32264. var kindIndex;
  32265. var kind;
  32266. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32267. kind = kinds[kindIndex];
  32268. var vertexBuffer = this.getVertexBuffer(kind);
  32269. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32270. updatableNormals = vertexBuffer.isUpdatable();
  32271. kinds.splice(kindIndex, 1);
  32272. kindIndex--;
  32273. continue;
  32274. }
  32275. vbs[kind] = vertexBuffer;
  32276. data[kind] = vbs[kind].getData();
  32277. newdata[kind] = [];
  32278. }
  32279. // Save previous submeshes
  32280. var previousSubmeshes = this.subMeshes.slice(0);
  32281. var indices = this.getIndices();
  32282. var totalIndices = this.getTotalIndices();
  32283. // Generating unique vertices per face
  32284. var index;
  32285. for (index = 0; index < totalIndices; index++) {
  32286. var vertexIndex = indices[index];
  32287. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32288. kind = kinds[kindIndex];
  32289. var stride = vbs[kind].getStrideSize();
  32290. for (var offset = 0; offset < stride; offset++) {
  32291. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32292. }
  32293. }
  32294. }
  32295. // Updating faces & normal
  32296. var normals = [];
  32297. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32298. for (index = 0; index < totalIndices; index += 3) {
  32299. indices[index] = index;
  32300. indices[index + 1] = index + 1;
  32301. indices[index + 2] = index + 2;
  32302. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32303. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32304. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32305. var p1p2 = p1.subtract(p2);
  32306. var p3p2 = p3.subtract(p2);
  32307. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32308. // Store same normals for every vertex
  32309. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32310. normals.push(normal.x);
  32311. normals.push(normal.y);
  32312. normals.push(normal.z);
  32313. }
  32314. }
  32315. this.setIndices(indices);
  32316. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32317. // Updating vertex buffers
  32318. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32319. kind = kinds[kindIndex];
  32320. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32321. }
  32322. // Updating submeshes
  32323. this.releaseSubMeshes();
  32324. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32325. var previousOne = previousSubmeshes[submeshIndex];
  32326. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32327. }
  32328. this.synchronizeInstances();
  32329. return this;
  32330. };
  32331. /**
  32332. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32333. * In other words, more vertices, no more indices and a single bigger VBO.
  32334. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32335. * Returns the Mesh.
  32336. */
  32337. Mesh.prototype.convertToUnIndexedMesh = function () {
  32338. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32339. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32340. var kinds = this.getVerticesDataKinds();
  32341. var vbs = {};
  32342. var data = {};
  32343. var newdata = {};
  32344. var kindIndex;
  32345. var kind;
  32346. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32347. kind = kinds[kindIndex];
  32348. var vertexBuffer = this.getVertexBuffer(kind);
  32349. vbs[kind] = vertexBuffer;
  32350. data[kind] = vbs[kind].getData();
  32351. newdata[kind] = [];
  32352. }
  32353. // Save previous submeshes
  32354. var previousSubmeshes = this.subMeshes.slice(0);
  32355. var indices = this.getIndices();
  32356. var totalIndices = this.getTotalIndices();
  32357. // Generating unique vertices per face
  32358. var index;
  32359. for (index = 0; index < totalIndices; index++) {
  32360. var vertexIndex = indices[index];
  32361. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32362. kind = kinds[kindIndex];
  32363. var stride = vbs[kind].getStrideSize();
  32364. for (var offset = 0; offset < stride; offset++) {
  32365. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32366. }
  32367. }
  32368. }
  32369. // Updating indices
  32370. for (index = 0; index < totalIndices; index += 3) {
  32371. indices[index] = index;
  32372. indices[index + 1] = index + 1;
  32373. indices[index + 2] = index + 2;
  32374. }
  32375. this.setIndices(indices);
  32376. // Updating vertex buffers
  32377. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32378. kind = kinds[kindIndex];
  32379. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32380. }
  32381. // Updating submeshes
  32382. this.releaseSubMeshes();
  32383. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32384. var previousOne = previousSubmeshes[submeshIndex];
  32385. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32386. }
  32387. this._unIndexed = true;
  32388. this.synchronizeInstances();
  32389. return this;
  32390. };
  32391. /**
  32392. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32393. * This method returns the Mesh.
  32394. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32395. */
  32396. Mesh.prototype.flipFaces = function (flipNormals) {
  32397. if (flipNormals === void 0) { flipNormals = false; }
  32398. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32399. var i;
  32400. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32401. for (i = 0; i < vertex_data.normals.length; i++) {
  32402. vertex_data.normals[i] *= -1;
  32403. }
  32404. }
  32405. if (vertex_data.indices) {
  32406. var temp;
  32407. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32408. // reassign indices
  32409. temp = vertex_data.indices[i + 1];
  32410. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32411. vertex_data.indices[i + 2] = temp;
  32412. }
  32413. }
  32414. vertex_data.applyToMesh(this);
  32415. return this;
  32416. };
  32417. // Instances
  32418. /**
  32419. * Creates a new InstancedMesh object from the mesh model.
  32420. * An instance shares the same properties and the same material than its model.
  32421. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  32422. * Only these properties of each instance can then be set individually :
  32423. * - position
  32424. * - rotation
  32425. * - rotationQuaternion
  32426. * - setPivotMatrix
  32427. * - scaling
  32428. *
  32429. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32430. * Warning : this method is not supported for Line mesh and LineSystem
  32431. */
  32432. Mesh.prototype.createInstance = function (name) {
  32433. return new BABYLON.InstancedMesh(name, this);
  32434. };
  32435. /**
  32436. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32437. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32438. * This method returns the Mesh.
  32439. */
  32440. Mesh.prototype.synchronizeInstances = function () {
  32441. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32442. var instance = this.instances[instanceIndex];
  32443. instance._syncSubMeshes();
  32444. }
  32445. return this;
  32446. };
  32447. /**
  32448. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32449. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32450. * This should be used together with the simplification to avoid disappearing triangles.
  32451. * Returns the Mesh.
  32452. * @param successCallback an optional success callback to be called after the optimization finished.
  32453. */
  32454. Mesh.prototype.optimizeIndices = function (successCallback) {
  32455. var _this = this;
  32456. var indices = this.getIndices();
  32457. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32458. if (!positions || !indices) {
  32459. return this;
  32460. }
  32461. var vectorPositions = new Array();
  32462. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32463. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32464. }
  32465. var dupes = new Array();
  32466. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32467. var realPos = vectorPositions.length - 1 - iteration;
  32468. var testedPosition = vectorPositions[realPos];
  32469. for (var j = 0; j < realPos; ++j) {
  32470. var againstPosition = vectorPositions[j];
  32471. if (testedPosition.equals(againstPosition)) {
  32472. dupes[realPos] = j;
  32473. break;
  32474. }
  32475. }
  32476. }, function () {
  32477. for (var i = 0; i < indices.length; ++i) {
  32478. indices[i] = dupes[indices[i]] || indices[i];
  32479. }
  32480. //indices are now reordered
  32481. var originalSubMeshes = _this.subMeshes.slice(0);
  32482. _this.setIndices(indices);
  32483. _this.subMeshes = originalSubMeshes;
  32484. if (successCallback) {
  32485. successCallback(_this);
  32486. }
  32487. });
  32488. return this;
  32489. };
  32490. Mesh.prototype.serialize = function (serializationObject) {
  32491. serializationObject.name = this.name;
  32492. serializationObject.id = this.id;
  32493. serializationObject.type = this.getClassName();
  32494. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32495. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32496. }
  32497. serializationObject.position = this.position.asArray();
  32498. if (this.rotationQuaternion) {
  32499. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32500. }
  32501. else if (this.rotation) {
  32502. serializationObject.rotation = this.rotation.asArray();
  32503. }
  32504. serializationObject.scaling = this.scaling.asArray();
  32505. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32506. serializationObject.isEnabled = this.isEnabled(false);
  32507. serializationObject.isVisible = this.isVisible;
  32508. serializationObject.infiniteDistance = this.infiniteDistance;
  32509. serializationObject.pickable = this.isPickable;
  32510. serializationObject.receiveShadows = this.receiveShadows;
  32511. serializationObject.billboardMode = this.billboardMode;
  32512. serializationObject.visibility = this.visibility;
  32513. serializationObject.checkCollisions = this.checkCollisions;
  32514. serializationObject.isBlocker = this.isBlocker;
  32515. // Parent
  32516. if (this.parent) {
  32517. serializationObject.parentId = this.parent.id;
  32518. }
  32519. // Geometry
  32520. serializationObject.isUnIndexed = this.isUnIndexed;
  32521. var geometry = this._geometry;
  32522. if (geometry) {
  32523. var geometryId = geometry.id;
  32524. serializationObject.geometryId = geometryId;
  32525. // SubMeshes
  32526. serializationObject.subMeshes = [];
  32527. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32528. var subMesh = this.subMeshes[subIndex];
  32529. serializationObject.subMeshes.push({
  32530. materialIndex: subMesh.materialIndex,
  32531. verticesStart: subMesh.verticesStart,
  32532. verticesCount: subMesh.verticesCount,
  32533. indexStart: subMesh.indexStart,
  32534. indexCount: subMesh.indexCount
  32535. });
  32536. }
  32537. }
  32538. // Material
  32539. if (this.material) {
  32540. serializationObject.materialId = this.material.id;
  32541. }
  32542. else {
  32543. this.material = null;
  32544. }
  32545. // Morph targets
  32546. if (this.morphTargetManager) {
  32547. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32548. }
  32549. // Skeleton
  32550. if (this.skeleton) {
  32551. serializationObject.skeletonId = this.skeleton.id;
  32552. }
  32553. // Physics
  32554. //TODO implement correct serialization for physics impostors.
  32555. var impostor = this.getPhysicsImpostor();
  32556. if (impostor) {
  32557. serializationObject.physicsMass = impostor.getParam("mass");
  32558. serializationObject.physicsFriction = impostor.getParam("friction");
  32559. serializationObject.physicsRestitution = impostor.getParam("mass");
  32560. serializationObject.physicsImpostor = impostor.type;
  32561. }
  32562. // Metadata
  32563. if (this.metadata) {
  32564. serializationObject.metadata = this.metadata;
  32565. }
  32566. // Instances
  32567. serializationObject.instances = [];
  32568. for (var index = 0; index < this.instances.length; index++) {
  32569. var instance = this.instances[index];
  32570. if (instance.doNotSerialize) {
  32571. continue;
  32572. }
  32573. var serializationInstance = {
  32574. name: instance.name,
  32575. id: instance.id,
  32576. position: instance.position.asArray(),
  32577. scaling: instance.scaling.asArray()
  32578. };
  32579. if (instance.parent) {
  32580. serializationInstance.parentId = instance.parent.id;
  32581. }
  32582. if (instance.rotationQuaternion) {
  32583. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32584. }
  32585. else if (instance.rotation) {
  32586. serializationInstance.rotation = instance.rotation.asArray();
  32587. }
  32588. serializationObject.instances.push(serializationInstance);
  32589. // Animations
  32590. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32591. serializationInstance.ranges = instance.serializeAnimationRanges();
  32592. }
  32593. //
  32594. // Animations
  32595. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32596. serializationObject.ranges = this.serializeAnimationRanges();
  32597. // Layer mask
  32598. serializationObject.layerMask = this.layerMask;
  32599. // Alpha
  32600. serializationObject.alphaIndex = this.alphaIndex;
  32601. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32602. // Overlay
  32603. serializationObject.overlayAlpha = this.overlayAlpha;
  32604. serializationObject.overlayColor = this.overlayColor.asArray();
  32605. serializationObject.renderOverlay = this.renderOverlay;
  32606. // Fog
  32607. serializationObject.applyFog = this.applyFog;
  32608. // Action Manager
  32609. if (this.actionManager) {
  32610. serializationObject.actions = this.actionManager.serialize(this.name);
  32611. }
  32612. };
  32613. /** @hidden */
  32614. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32615. if (!this.geometry) {
  32616. return;
  32617. }
  32618. this._markSubMeshesAsAttributesDirty();
  32619. var morphTargetManager = this._morphTargetManager;
  32620. if (morphTargetManager && morphTargetManager.vertexCount) {
  32621. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32622. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32623. this.morphTargetManager = null;
  32624. return;
  32625. }
  32626. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32627. var morphTarget = morphTargetManager.getActiveTarget(index);
  32628. var positions = morphTarget.getPositions();
  32629. if (!positions) {
  32630. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32631. return;
  32632. }
  32633. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32634. var normals = morphTarget.getNormals();
  32635. if (normals) {
  32636. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32637. }
  32638. var tangents = morphTarget.getTangents();
  32639. if (tangents) {
  32640. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32641. }
  32642. }
  32643. }
  32644. else {
  32645. var index = 0;
  32646. // Positions
  32647. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32648. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32649. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32650. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32651. }
  32652. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32653. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32654. }
  32655. index++;
  32656. }
  32657. }
  32658. };
  32659. // Statics
  32660. /**
  32661. * Returns a new Mesh object parsed from the source provided.
  32662. * The parameter `parsedMesh` is the source.
  32663. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32664. */
  32665. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32666. var mesh;
  32667. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32668. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32669. }
  32670. else {
  32671. mesh = new Mesh(parsedMesh.name, scene);
  32672. }
  32673. mesh.id = parsedMesh.id;
  32674. if (BABYLON.Tags) {
  32675. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32676. }
  32677. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32678. if (parsedMesh.metadata !== undefined) {
  32679. mesh.metadata = parsedMesh.metadata;
  32680. }
  32681. if (parsedMesh.rotationQuaternion) {
  32682. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32683. }
  32684. else if (parsedMesh.rotation) {
  32685. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32686. }
  32687. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32688. if (parsedMesh.localMatrix) {
  32689. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32690. }
  32691. else if (parsedMesh.pivotMatrix) {
  32692. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32693. }
  32694. mesh.setEnabled(parsedMesh.isEnabled);
  32695. mesh.isVisible = parsedMesh.isVisible;
  32696. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32697. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32698. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32699. if (parsedMesh.applyFog !== undefined) {
  32700. mesh.applyFog = parsedMesh.applyFog;
  32701. }
  32702. if (parsedMesh.pickable !== undefined) {
  32703. mesh.isPickable = parsedMesh.pickable;
  32704. }
  32705. if (parsedMesh.alphaIndex !== undefined) {
  32706. mesh.alphaIndex = parsedMesh.alphaIndex;
  32707. }
  32708. mesh.receiveShadows = parsedMesh.receiveShadows;
  32709. mesh.billboardMode = parsedMesh.billboardMode;
  32710. if (parsedMesh.visibility !== undefined) {
  32711. mesh.visibility = parsedMesh.visibility;
  32712. }
  32713. mesh.checkCollisions = parsedMesh.checkCollisions;
  32714. if (parsedMesh.isBlocker !== undefined) {
  32715. mesh.isBlocker = parsedMesh.isBlocker;
  32716. }
  32717. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32718. // freezeWorldMatrix
  32719. if (parsedMesh.freezeWorldMatrix) {
  32720. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32721. }
  32722. // Parent
  32723. if (parsedMesh.parentId) {
  32724. mesh._waitingParentId = parsedMesh.parentId;
  32725. }
  32726. // Actions
  32727. if (parsedMesh.actions !== undefined) {
  32728. mesh._waitingActions = parsedMesh.actions;
  32729. }
  32730. // Overlay
  32731. if (parsedMesh.overlayAlpha !== undefined) {
  32732. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32733. }
  32734. if (parsedMesh.overlayColor !== undefined) {
  32735. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32736. }
  32737. if (parsedMesh.renderOverlay !== undefined) {
  32738. mesh.renderOverlay = parsedMesh.renderOverlay;
  32739. }
  32740. // Geometry
  32741. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32742. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32743. if (parsedMesh.delayLoadingFile) {
  32744. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32745. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32746. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32747. if (parsedMesh._binaryInfo) {
  32748. mesh._binaryInfo = parsedMesh._binaryInfo;
  32749. }
  32750. mesh._delayInfo = [];
  32751. if (parsedMesh.hasUVs) {
  32752. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32753. }
  32754. if (parsedMesh.hasUVs2) {
  32755. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32756. }
  32757. if (parsedMesh.hasUVs3) {
  32758. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32759. }
  32760. if (parsedMesh.hasUVs4) {
  32761. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32762. }
  32763. if (parsedMesh.hasUVs5) {
  32764. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32765. }
  32766. if (parsedMesh.hasUVs6) {
  32767. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32768. }
  32769. if (parsedMesh.hasColors) {
  32770. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32771. }
  32772. if (parsedMesh.hasMatricesIndices) {
  32773. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32774. }
  32775. if (parsedMesh.hasMatricesWeights) {
  32776. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32777. }
  32778. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32779. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32780. mesh._checkDelayState();
  32781. }
  32782. }
  32783. else {
  32784. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32785. }
  32786. // Material
  32787. if (parsedMesh.materialId) {
  32788. mesh.setMaterialByID(parsedMesh.materialId);
  32789. }
  32790. else {
  32791. mesh.material = null;
  32792. }
  32793. // Morph targets
  32794. if (parsedMesh.morphTargetManagerId > -1) {
  32795. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32796. }
  32797. // Skeleton
  32798. if (parsedMesh.skeletonId > -1) {
  32799. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32800. if (parsedMesh.numBoneInfluencers) {
  32801. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32802. }
  32803. }
  32804. // Animations
  32805. if (parsedMesh.animations) {
  32806. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32807. var parsedAnimation = parsedMesh.animations[animationIndex];
  32808. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32809. }
  32810. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32811. }
  32812. if (parsedMesh.autoAnimate) {
  32813. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32814. }
  32815. // Layer Mask
  32816. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32817. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32818. }
  32819. else {
  32820. mesh.layerMask = 0x0FFFFFFF;
  32821. }
  32822. // Physics
  32823. if (parsedMesh.physicsImpostor) {
  32824. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32825. mass: parsedMesh.physicsMass,
  32826. friction: parsedMesh.physicsFriction,
  32827. restitution: parsedMesh.physicsRestitution
  32828. }, scene);
  32829. }
  32830. // Instances
  32831. if (parsedMesh.instances) {
  32832. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32833. var parsedInstance = parsedMesh.instances[index];
  32834. var instance = mesh.createInstance(parsedInstance.name);
  32835. if (parsedInstance.id) {
  32836. instance.id = parsedInstance.id;
  32837. }
  32838. if (BABYLON.Tags) {
  32839. if (parsedInstance.tags) {
  32840. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32841. }
  32842. else {
  32843. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  32844. }
  32845. }
  32846. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32847. if (parsedInstance.parentId) {
  32848. instance._waitingParentId = parsedInstance.parentId;
  32849. }
  32850. if (parsedInstance.rotationQuaternion) {
  32851. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32852. }
  32853. else if (parsedInstance.rotation) {
  32854. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32855. }
  32856. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32857. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  32858. instance.checkCollisions = parsedInstance.checkCollisions;
  32859. }
  32860. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  32861. instance.isPickable = parsedInstance.pickable;
  32862. }
  32863. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  32864. instance.showBoundingBox = parsedInstance.showBoundingBox;
  32865. }
  32866. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  32867. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  32868. }
  32869. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  32870. instance.alphaIndex = parsedInstance.alphaIndex;
  32871. }
  32872. // Physics
  32873. if (parsedInstance.physicsImpostor) {
  32874. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  32875. mass: parsedInstance.physicsMass,
  32876. friction: parsedInstance.physicsFriction,
  32877. restitution: parsedInstance.physicsRestitution
  32878. }, scene);
  32879. }
  32880. // Animation
  32881. if (parsedInstance.animations) {
  32882. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  32883. parsedAnimation = parsedInstance.animations[animationIndex];
  32884. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32885. }
  32886. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  32887. if (parsedInstance.autoAnimate) {
  32888. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  32889. }
  32890. }
  32891. }
  32892. }
  32893. return mesh;
  32894. };
  32895. /**
  32896. * Creates a ribbon mesh.
  32897. * Please consider using the same method from the MeshBuilder class instead.
  32898. * 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.
  32899. *
  32900. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32901. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32902. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32903. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32904. * 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.
  32905. * 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.
  32906. * 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
  32907. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32908. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32909. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32910. */
  32911. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32912. if (closeArray === void 0) { closeArray = false; }
  32913. if (updatable === void 0) { updatable = false; }
  32914. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32915. pathArray: pathArray,
  32916. closeArray: closeArray,
  32917. closePath: closePath,
  32918. offset: offset,
  32919. updatable: updatable,
  32920. sideOrientation: sideOrientation,
  32921. instance: instance
  32922. }, scene);
  32923. };
  32924. /**
  32925. * Creates a plane polygonal mesh. By default, this is a disc.
  32926. * Please consider using the same method from the MeshBuilder class instead.
  32927. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32928. * 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.
  32929. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32930. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32931. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32932. */
  32933. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32934. if (scene === void 0) { scene = null; }
  32935. var options = {
  32936. radius: radius,
  32937. tessellation: tessellation,
  32938. sideOrientation: sideOrientation,
  32939. updatable: updatable
  32940. };
  32941. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32942. };
  32943. /**
  32944. * Creates a box mesh.
  32945. * Please consider using the same method from the MeshBuilder class instead.
  32946. * The parameter `size` sets the size (float) of each box side (default 1).
  32947. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32948. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32949. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32950. */
  32951. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32952. if (scene === void 0) { scene = null; }
  32953. var options = {
  32954. size: size,
  32955. sideOrientation: sideOrientation,
  32956. updatable: updatable
  32957. };
  32958. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32959. };
  32960. /**
  32961. * Creates a sphere mesh.
  32962. * Please consider using the same method from the MeshBuilder class instead.
  32963. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32964. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32965. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32966. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32968. */
  32969. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32970. var options = {
  32971. segments: segments,
  32972. diameterX: diameter,
  32973. diameterY: diameter,
  32974. diameterZ: diameter,
  32975. sideOrientation: sideOrientation,
  32976. updatable: updatable
  32977. };
  32978. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32979. };
  32980. /**
  32981. * Creates a cylinder or a cone mesh.
  32982. * Please consider using the same method from the MeshBuilder class instead.
  32983. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32984. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32985. * 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.
  32986. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32987. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32988. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32989. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32991. */
  32992. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32993. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32994. if (scene !== undefined) {
  32995. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32996. updatable = scene;
  32997. }
  32998. scene = subdivisions;
  32999. subdivisions = 1;
  33000. }
  33001. var options = {
  33002. height: height,
  33003. diameterTop: diameterTop,
  33004. diameterBottom: diameterBottom,
  33005. tessellation: tessellation,
  33006. subdivisions: subdivisions,
  33007. sideOrientation: sideOrientation,
  33008. updatable: updatable
  33009. };
  33010. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33011. };
  33012. // Torus (Code from SharpDX.org)
  33013. /**
  33014. * Creates a torus mesh.
  33015. * Please consider using the same method from the MeshBuilder class instead.
  33016. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33017. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33018. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33019. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33020. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33021. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33022. */
  33023. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33024. var options = {
  33025. diameter: diameter,
  33026. thickness: thickness,
  33027. tessellation: tessellation,
  33028. sideOrientation: sideOrientation,
  33029. updatable: updatable
  33030. };
  33031. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33032. };
  33033. /**
  33034. * Creates a torus knot mesh.
  33035. * Please consider using the same method from the MeshBuilder class instead.
  33036. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33037. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33038. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33039. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33040. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33041. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33042. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33043. */
  33044. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33045. var options = {
  33046. radius: radius,
  33047. tube: tube,
  33048. radialSegments: radialSegments,
  33049. tubularSegments: tubularSegments,
  33050. p: p,
  33051. q: q,
  33052. sideOrientation: sideOrientation,
  33053. updatable: updatable
  33054. };
  33055. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33056. };
  33057. /**
  33058. * Creates a line mesh.
  33059. * Please consider using the same method from the MeshBuilder class instead.
  33060. * 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.
  33061. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33062. * The parameter `points` is an array successive Vector3.
  33063. * 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
  33064. * When updating an instance, remember that only point positions can change, not the number of points.
  33065. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33066. */
  33067. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33068. if (scene === void 0) { scene = null; }
  33069. if (updatable === void 0) { updatable = false; }
  33070. if (instance === void 0) { instance = null; }
  33071. var options = {
  33072. points: points,
  33073. updatable: updatable,
  33074. instance: instance
  33075. };
  33076. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33077. };
  33078. /**
  33079. * Creates a dashed line mesh.
  33080. * Please consider using the same method from the MeshBuilder class instead.
  33081. * 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.
  33082. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33083. * The parameter `points` is an array successive Vector3.
  33084. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33085. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33086. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33087. * 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
  33088. * When updating an instance, remember that only point positions can change, not the number of points.
  33089. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33090. */
  33091. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33092. if (scene === void 0) { scene = null; }
  33093. var options = {
  33094. points: points,
  33095. dashSize: dashSize,
  33096. gapSize: gapSize,
  33097. dashNb: dashNb,
  33098. updatable: updatable,
  33099. instance: instance
  33100. };
  33101. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33102. };
  33103. /**
  33104. * Creates a polygon mesh.
  33105. * Please consider using the same method from the MeshBuilder class instead.
  33106. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33107. * 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.
  33108. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33109. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33110. * Remember you can only change the shape positions, not their number when updating a polygon.
  33111. */
  33112. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33113. var options = {
  33114. shape: shape,
  33115. holes: holes,
  33116. updatable: updatable,
  33117. sideOrientation: sideOrientation
  33118. };
  33119. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33120. };
  33121. /**
  33122. * Creates an extruded polygon mesh, with depth in the Y direction.
  33123. * Please consider using the same method from the MeshBuilder class instead.
  33124. */
  33125. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33126. var options = {
  33127. shape: shape,
  33128. holes: holes,
  33129. depth: depth,
  33130. updatable: updatable,
  33131. sideOrientation: sideOrientation
  33132. };
  33133. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33134. };
  33135. /**
  33136. * Creates an extruded shape mesh.
  33137. * 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.
  33138. * Please consider using the same method from the MeshBuilder class instead.
  33139. *
  33140. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33141. * 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
  33142. * extruded along the Z axis.
  33143. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33144. * 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.
  33145. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33146. * 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
  33147. * 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
  33148. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  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.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33154. if (scene === void 0) { scene = null; }
  33155. var options = {
  33156. shape: shape,
  33157. path: path,
  33158. scale: scale,
  33159. rotation: rotation,
  33160. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33161. sideOrientation: sideOrientation,
  33162. instance: instance,
  33163. updatable: updatable
  33164. };
  33165. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33166. };
  33167. /**
  33168. * Creates an custom extruded shape mesh.
  33169. * 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.
  33170. * Please consider using the same method from the MeshBuilder class instead.
  33171. *
  33172. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33173. * 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
  33174. * extruded along the Z axis.
  33175. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33176. * 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
  33177. * and the distance of this point from the begining of the path :
  33178. * ```javascript
  33179. * var rotationFunction = function(i, distance) {
  33180. * // do things
  33181. * return rotationValue; }
  33182. * ```
  33183. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33184. * 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
  33185. * and the distance of this point from the begining of the path :
  33186. * ```javascript
  33187. * var scaleFunction = function(i, distance) {
  33188. * // do things
  33189. * return scaleValue;}
  33190. * ```
  33191. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33192. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33193. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33194. * 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
  33195. * 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
  33196. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33197. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33198. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33199. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33200. */
  33201. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33202. var options = {
  33203. shape: shape,
  33204. path: path,
  33205. scaleFunction: scaleFunction,
  33206. rotationFunction: rotationFunction,
  33207. ribbonCloseArray: ribbonCloseArray,
  33208. ribbonClosePath: ribbonClosePath,
  33209. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33210. sideOrientation: sideOrientation,
  33211. instance: instance,
  33212. updatable: updatable
  33213. };
  33214. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33215. };
  33216. /**
  33217. * Creates lathe mesh.
  33218. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33219. * Please consider using the same method from the MeshBuilder class instead.
  33220. * 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
  33221. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33222. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33223. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33224. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33225. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33227. */
  33228. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33229. var options = {
  33230. shape: shape,
  33231. radius: radius,
  33232. tessellation: tessellation,
  33233. sideOrientation: sideOrientation,
  33234. updatable: updatable
  33235. };
  33236. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33237. };
  33238. /**
  33239. * Creates a plane mesh.
  33240. * Please consider using the same method from the MeshBuilder class instead.
  33241. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33242. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33243. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33244. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33245. */
  33246. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33247. var options = {
  33248. size: size,
  33249. width: size,
  33250. height: size,
  33251. sideOrientation: sideOrientation,
  33252. updatable: updatable
  33253. };
  33254. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33255. };
  33256. /**
  33257. * Creates a ground mesh.
  33258. * Please consider using the same method from the MeshBuilder class instead.
  33259. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33260. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33261. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33262. */
  33263. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33264. var options = {
  33265. width: width,
  33266. height: height,
  33267. subdivisions: subdivisions,
  33268. updatable: updatable
  33269. };
  33270. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33271. };
  33272. /**
  33273. * Creates a tiled ground mesh.
  33274. * Please consider using the same method from the MeshBuilder class instead.
  33275. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33276. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33277. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33278. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33279. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33280. * numbers of subdivisions on the ground width and height of each tile.
  33281. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33282. */
  33283. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33284. var options = {
  33285. xmin: xmin,
  33286. zmin: zmin,
  33287. xmax: xmax,
  33288. zmax: zmax,
  33289. subdivisions: subdivisions,
  33290. precision: precision,
  33291. updatable: updatable
  33292. };
  33293. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33294. };
  33295. /**
  33296. * Creates a ground mesh from a height map.
  33297. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33298. * Please consider using the same method from the MeshBuilder class instead.
  33299. * @param url sets the URL of the height map image resource.
  33300. * @param width (positive float, default 10) set the ground width size.
  33301. * @param height (positive float, default 10) set the ground height size.
  33302. * @param subdivisions (positive integer, default 1) sets the number of subdivision per side.
  33303. * @param minHeight (float, default 0) is the minimum altitude on the ground.
  33304. * @param maxHeight (float, default 1) is the maximum altitude on the ground.
  33305. * @param onReady is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  33306. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible).
  33307. * This function is passed the newly built mesh :
  33308. * ```javascript
  33309. * function(mesh) { // do things
  33310. * return; }
  33311. * ```
  33312. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33313. */
  33314. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33315. var options = {
  33316. width: width,
  33317. height: height,
  33318. subdivisions: subdivisions,
  33319. minHeight: minHeight,
  33320. maxHeight: maxHeight,
  33321. updatable: updatable,
  33322. onReady: onReady,
  33323. alphaFilter: alphaFilter
  33324. };
  33325. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33326. };
  33327. /**
  33328. * Creates a tube mesh.
  33329. * 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.
  33330. * Please consider using the same method from the MeshBuilder class instead.
  33331. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33332. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33333. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33334. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33335. * 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.
  33336. * It must return a radius value (positive float) :
  33337. * ```javascript
  33338. * var radiusFunction = function(i, distance) {
  33339. * // do things
  33340. * return radius; }
  33341. * ```
  33342. * 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
  33343. * 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
  33344. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33345. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33346. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33347. */
  33348. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33349. var options = {
  33350. path: path,
  33351. radius: radius,
  33352. tessellation: tessellation,
  33353. radiusFunction: radiusFunction,
  33354. arc: 1,
  33355. cap: cap,
  33356. updatable: updatable,
  33357. sideOrientation: sideOrientation,
  33358. instance: instance
  33359. };
  33360. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33361. };
  33362. /**
  33363. * Creates a polyhedron mesh.
  33364. * Please consider using the same method from the MeshBuilder class instead.
  33365. * 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
  33366. * to choose the wanted type.
  33367. * The parameter `size` (positive float, default 1) sets the polygon size.
  33368. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33369. * 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`.
  33370. * 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
  33371. * 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)`).
  33372. * 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
  33373. * 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.
  33374. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33375. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33376. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33377. */
  33378. Mesh.CreatePolyhedron = function (name, options, scene) {
  33379. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33380. };
  33381. /**
  33382. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33383. * Please consider using the same method from the MeshBuilder class instead.
  33384. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33385. * 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`).
  33386. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33387. * 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.
  33388. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33389. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33390. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33391. */
  33392. Mesh.CreateIcoSphere = function (name, options, scene) {
  33393. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33394. };
  33395. /**
  33396. * Creates a decal mesh.
  33397. * Please consider using the same method from the MeshBuilder class instead.
  33398. * 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.
  33399. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33400. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33401. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33402. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33403. */
  33404. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33405. var options = {
  33406. position: position,
  33407. normal: normal,
  33408. size: size,
  33409. angle: angle
  33410. };
  33411. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33412. };
  33413. // Skeletons
  33414. /**
  33415. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33416. */
  33417. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33418. if (!this._sourcePositions) {
  33419. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33420. if (!source) {
  33421. return this._sourcePositions;
  33422. }
  33423. this._sourcePositions = new Float32Array(source);
  33424. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33425. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33426. }
  33427. }
  33428. return this._sourcePositions;
  33429. };
  33430. /**
  33431. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33432. */
  33433. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33434. if (!this._sourceNormals) {
  33435. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33436. if (!source) {
  33437. return this._sourceNormals;
  33438. }
  33439. this._sourceNormals = new Float32Array(source);
  33440. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33441. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33442. }
  33443. }
  33444. return this._sourceNormals;
  33445. };
  33446. /**
  33447. * Updates the vertex buffer by applying transformation from the bones.
  33448. * Returns the Mesh.
  33449. *
  33450. * @param {skeleton} skeleton to apply
  33451. */
  33452. Mesh.prototype.applySkeleton = function (skeleton) {
  33453. if (!this.geometry) {
  33454. return this;
  33455. }
  33456. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33457. return this;
  33458. }
  33459. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33460. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33461. return this;
  33462. }
  33463. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33464. return this;
  33465. }
  33466. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33467. return this;
  33468. }
  33469. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33470. return this;
  33471. }
  33472. if (!this._sourcePositions) {
  33473. var submeshes = this.subMeshes.slice();
  33474. this.setPositionsForCPUSkinning();
  33475. this.subMeshes = submeshes;
  33476. }
  33477. if (!this._sourceNormals) {
  33478. this.setNormalsForCPUSkinning();
  33479. }
  33480. // positionsData checks for not being Float32Array will only pass at most once
  33481. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33482. if (!positionsData) {
  33483. return this;
  33484. }
  33485. if (!(positionsData instanceof Float32Array)) {
  33486. positionsData = new Float32Array(positionsData);
  33487. }
  33488. // normalsData checks for not being Float32Array will only pass at most once
  33489. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33490. if (!normalsData) {
  33491. return this;
  33492. }
  33493. if (!(normalsData instanceof Float32Array)) {
  33494. normalsData = new Float32Array(normalsData);
  33495. }
  33496. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33497. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33498. if (!matricesWeightsData || !matricesIndicesData) {
  33499. return this;
  33500. }
  33501. var needExtras = this.numBoneInfluencers > 4;
  33502. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33503. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33504. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33505. var tempVector3 = BABYLON.Vector3.Zero();
  33506. var finalMatrix = new BABYLON.Matrix();
  33507. var tempMatrix = new BABYLON.Matrix();
  33508. var matWeightIdx = 0;
  33509. var inf;
  33510. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33511. var weight;
  33512. for (inf = 0; inf < 4; inf++) {
  33513. weight = matricesWeightsData[matWeightIdx + inf];
  33514. if (weight > 0) {
  33515. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33516. finalMatrix.addToSelf(tempMatrix);
  33517. }
  33518. }
  33519. if (needExtras) {
  33520. for (inf = 0; inf < 4; inf++) {
  33521. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33522. if (weight > 0) {
  33523. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33524. finalMatrix.addToSelf(tempMatrix);
  33525. }
  33526. }
  33527. }
  33528. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33529. tempVector3.toArray(positionsData, index);
  33530. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33531. tempVector3.toArray(normalsData, index);
  33532. finalMatrix.reset();
  33533. }
  33534. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33535. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33536. return this;
  33537. };
  33538. // Tools
  33539. /**
  33540. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33541. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33542. */
  33543. Mesh.MinMax = function (meshes) {
  33544. var minVector = null;
  33545. var maxVector = null;
  33546. meshes.forEach(function (mesh, index, array) {
  33547. var boundingInfo = mesh.getBoundingInfo();
  33548. var boundingBox = boundingInfo.boundingBox;
  33549. if (!minVector || !maxVector) {
  33550. minVector = boundingBox.minimumWorld;
  33551. maxVector = boundingBox.maximumWorld;
  33552. }
  33553. else {
  33554. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33555. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33556. }
  33557. });
  33558. if (!minVector || !maxVector) {
  33559. return {
  33560. min: BABYLON.Vector3.Zero(),
  33561. max: BABYLON.Vector3.Zero()
  33562. };
  33563. }
  33564. return {
  33565. min: minVector,
  33566. max: maxVector
  33567. };
  33568. };
  33569. /**
  33570. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33571. */
  33572. Mesh.Center = function (meshesOrMinMaxVector) {
  33573. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33574. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33575. };
  33576. /**
  33577. * Merge the array of meshes into a single mesh for performance reasons.
  33578. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  33579. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  33580. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33581. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33582. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33583. */
  33584. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33585. if (disposeSource === void 0) { disposeSource = true; }
  33586. var index;
  33587. if (!allow32BitsIndices) {
  33588. var totalVertices = 0;
  33589. // Counting vertices
  33590. for (index = 0; index < meshes.length; index++) {
  33591. if (meshes[index]) {
  33592. totalVertices += meshes[index].getTotalVertices();
  33593. if (totalVertices > 65536) {
  33594. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33595. return null;
  33596. }
  33597. }
  33598. }
  33599. }
  33600. // Merge
  33601. var vertexData = null;
  33602. var otherVertexData;
  33603. var indiceArray = new Array();
  33604. var source = null;
  33605. for (index = 0; index < meshes.length; index++) {
  33606. if (meshes[index]) {
  33607. var wm = meshes[index].computeWorldMatrix(true);
  33608. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33609. otherVertexData.transform(wm);
  33610. if (vertexData) {
  33611. vertexData.merge(otherVertexData, allow32BitsIndices);
  33612. }
  33613. else {
  33614. vertexData = otherVertexData;
  33615. source = meshes[index];
  33616. }
  33617. if (subdivideWithSubMeshes) {
  33618. indiceArray.push(meshes[index].getTotalIndices());
  33619. }
  33620. }
  33621. }
  33622. source = source;
  33623. if (!meshSubclass) {
  33624. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33625. }
  33626. vertexData.applyToMesh(meshSubclass);
  33627. // Setting properties
  33628. meshSubclass.material = source.material;
  33629. meshSubclass.checkCollisions = source.checkCollisions;
  33630. // Cleaning
  33631. if (disposeSource) {
  33632. for (index = 0; index < meshes.length; index++) {
  33633. if (meshes[index]) {
  33634. meshes[index].dispose();
  33635. }
  33636. }
  33637. }
  33638. // Subdivide
  33639. if (subdivideWithSubMeshes) {
  33640. //-- removal of global submesh
  33641. meshSubclass.releaseSubMeshes();
  33642. index = 0;
  33643. var offset = 0;
  33644. //-- apply subdivision according to index table
  33645. while (index < indiceArray.length) {
  33646. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33647. offset += indiceArray[index];
  33648. index++;
  33649. }
  33650. }
  33651. return meshSubclass;
  33652. };
  33653. // Consts
  33654. Mesh._FRONTSIDE = 0;
  33655. Mesh._BACKSIDE = 1;
  33656. Mesh._DOUBLESIDE = 2;
  33657. Mesh._DEFAULTSIDE = 0;
  33658. Mesh._NO_CAP = 0;
  33659. Mesh._CAP_START = 1;
  33660. Mesh._CAP_END = 2;
  33661. Mesh._CAP_ALL = 3;
  33662. return Mesh;
  33663. }(BABYLON.AbstractMesh));
  33664. BABYLON.Mesh = Mesh;
  33665. })(BABYLON || (BABYLON = {}));
  33666. //# sourceMappingURL=babylon.mesh.js.map
  33667. var BABYLON;
  33668. (function (BABYLON) {
  33669. var BaseSubMesh = /** @class */ (function () {
  33670. function BaseSubMesh() {
  33671. }
  33672. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33673. get: function () {
  33674. return this._materialEffect;
  33675. },
  33676. enumerable: true,
  33677. configurable: true
  33678. });
  33679. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33680. if (defines === void 0) { defines = null; }
  33681. if (this._materialEffect === effect) {
  33682. if (!effect) {
  33683. this._materialDefines = null;
  33684. }
  33685. return;
  33686. }
  33687. this._materialDefines = defines;
  33688. this._materialEffect = effect;
  33689. };
  33690. return BaseSubMesh;
  33691. }());
  33692. BABYLON.BaseSubMesh = BaseSubMesh;
  33693. var SubMesh = /** @class */ (function (_super) {
  33694. __extends(SubMesh, _super);
  33695. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33696. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33697. var _this = _super.call(this) || this;
  33698. _this.materialIndex = materialIndex;
  33699. _this.verticesStart = verticesStart;
  33700. _this.verticesCount = verticesCount;
  33701. _this.indexStart = indexStart;
  33702. _this.indexCount = indexCount;
  33703. /** @hidden */
  33704. _this._renderId = 0;
  33705. _this._mesh = mesh;
  33706. _this._renderingMesh = renderingMesh || mesh;
  33707. mesh.subMeshes.push(_this);
  33708. _this._trianglePlanes = [];
  33709. _this._id = mesh.subMeshes.length - 1;
  33710. if (createBoundingBox) {
  33711. _this.refreshBoundingInfo();
  33712. mesh.computeWorldMatrix(true);
  33713. }
  33714. return _this;
  33715. }
  33716. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33717. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33718. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33719. };
  33720. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33721. get: function () {
  33722. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  33723. },
  33724. enumerable: true,
  33725. configurable: true
  33726. });
  33727. /**
  33728. * Returns the submesh BoudingInfo object.
  33729. */
  33730. SubMesh.prototype.getBoundingInfo = function () {
  33731. if (this.IsGlobal) {
  33732. return this._mesh.getBoundingInfo();
  33733. }
  33734. return this._boundingInfo;
  33735. };
  33736. /**
  33737. * Sets the submesh BoundingInfo.
  33738. * Return the SubMesh.
  33739. */
  33740. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33741. this._boundingInfo = boundingInfo;
  33742. return this;
  33743. };
  33744. /**
  33745. * Returns the mesh of the current submesh.
  33746. */
  33747. SubMesh.prototype.getMesh = function () {
  33748. return this._mesh;
  33749. };
  33750. /**
  33751. * Returns the rendering mesh of the submesh.
  33752. */
  33753. SubMesh.prototype.getRenderingMesh = function () {
  33754. return this._renderingMesh;
  33755. };
  33756. /**
  33757. * Returns the submesh material.
  33758. */
  33759. SubMesh.prototype.getMaterial = function () {
  33760. var rootMaterial = this._renderingMesh.material;
  33761. if (rootMaterial === null || rootMaterial === undefined) {
  33762. return this._mesh.getScene().defaultMaterial;
  33763. }
  33764. else if (rootMaterial.getSubMaterial) {
  33765. var multiMaterial = rootMaterial;
  33766. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33767. if (this._currentMaterial !== effectiveMaterial) {
  33768. this._currentMaterial = effectiveMaterial;
  33769. this._materialDefines = null;
  33770. }
  33771. return effectiveMaterial;
  33772. }
  33773. return rootMaterial;
  33774. };
  33775. // Methods
  33776. /**
  33777. * Sets a new updated BoundingInfo object to the submesh.
  33778. * Returns the SubMesh.
  33779. */
  33780. SubMesh.prototype.refreshBoundingInfo = function () {
  33781. this._lastColliderWorldVertices = null;
  33782. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33783. return this;
  33784. }
  33785. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33786. if (!data) {
  33787. this._boundingInfo = this._mesh.getBoundingInfo();
  33788. return this;
  33789. }
  33790. var indices = this._renderingMesh.getIndices();
  33791. var extend;
  33792. //is this the only submesh?
  33793. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33794. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33795. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33796. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33797. }
  33798. else {
  33799. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33800. }
  33801. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33802. return this;
  33803. };
  33804. /** @hidden */
  33805. SubMesh.prototype._checkCollision = function (collider) {
  33806. var boundingInfo = this.getBoundingInfo();
  33807. return boundingInfo._checkCollision(collider);
  33808. };
  33809. /**
  33810. * Updates the submesh BoundingInfo.
  33811. * Returns the Submesh.
  33812. */
  33813. SubMesh.prototype.updateBoundingInfo = function (world) {
  33814. var boundingInfo = this.getBoundingInfo();
  33815. if (!boundingInfo) {
  33816. this.refreshBoundingInfo();
  33817. boundingInfo = this.getBoundingInfo();
  33818. }
  33819. boundingInfo.update(world);
  33820. return this;
  33821. };
  33822. /**
  33823. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33824. * Boolean returned.
  33825. */
  33826. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33827. var boundingInfo = this.getBoundingInfo();
  33828. if (!boundingInfo) {
  33829. return false;
  33830. }
  33831. return boundingInfo.isInFrustum(frustumPlanes);
  33832. };
  33833. /**
  33834. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33835. * Boolean returned.
  33836. */
  33837. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33838. var boundingInfo = this.getBoundingInfo();
  33839. if (!boundingInfo) {
  33840. return false;
  33841. }
  33842. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33843. };
  33844. /**
  33845. * Renders the submesh.
  33846. * Returns it.
  33847. */
  33848. SubMesh.prototype.render = function (enableAlphaMode) {
  33849. this._renderingMesh.render(this, enableAlphaMode);
  33850. return this;
  33851. };
  33852. /**
  33853. * Returns a new Index Buffer.
  33854. * Type returned : WebGLBuffer.
  33855. */
  33856. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33857. if (!this._linesIndexBuffer) {
  33858. var linesIndices = [];
  33859. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33860. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33861. }
  33862. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33863. this.linesIndexCount = linesIndices.length;
  33864. }
  33865. return this._linesIndexBuffer;
  33866. };
  33867. /**
  33868. * True is the passed Ray intersects the submesh bounding box.
  33869. * Boolean returned.
  33870. */
  33871. SubMesh.prototype.canIntersects = function (ray) {
  33872. var boundingInfo = this.getBoundingInfo();
  33873. if (!boundingInfo) {
  33874. return false;
  33875. }
  33876. return ray.intersectsBox(boundingInfo.boundingBox);
  33877. };
  33878. /**
  33879. * Returns an object IntersectionInfo.
  33880. */
  33881. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33882. var intersectInfo = null;
  33883. var material = this.getMaterial();
  33884. if (!material) {
  33885. return null;
  33886. }
  33887. switch (material.fillMode) {
  33888. case BABYLON.Material.PointListDrawMode:
  33889. case BABYLON.Material.LineListDrawMode:
  33890. case BABYLON.Material.LineLoopDrawMode:
  33891. case BABYLON.Material.LineStripDrawMode:
  33892. case BABYLON.Material.TriangleFanDrawMode:
  33893. case BABYLON.Material.TriangleStripDrawMode:
  33894. return null;
  33895. }
  33896. // LineMesh first as it's also a Mesh...
  33897. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33898. var lineMesh = this._mesh;
  33899. // Line test
  33900. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33901. var p0 = positions[indices[index]];
  33902. var p1 = positions[indices[index + 1]];
  33903. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33904. if (length < 0) {
  33905. continue;
  33906. }
  33907. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33908. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33909. if (fastCheck) {
  33910. break;
  33911. }
  33912. }
  33913. }
  33914. }
  33915. else {
  33916. // Triangles test
  33917. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33918. var p0 = positions[indices[index]];
  33919. var p1 = positions[indices[index + 1]];
  33920. var p2 = positions[indices[index + 2]];
  33921. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33922. if (currentIntersectInfo) {
  33923. if (currentIntersectInfo.distance < 0) {
  33924. continue;
  33925. }
  33926. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33927. intersectInfo = currentIntersectInfo;
  33928. intersectInfo.faceId = index / 3;
  33929. if (fastCheck) {
  33930. break;
  33931. }
  33932. }
  33933. }
  33934. }
  33935. }
  33936. return intersectInfo;
  33937. };
  33938. /** @hidden */
  33939. SubMesh.prototype._rebuild = function () {
  33940. if (this._linesIndexBuffer) {
  33941. this._linesIndexBuffer = null;
  33942. }
  33943. };
  33944. // Clone
  33945. /**
  33946. * Creates a new Submesh from the passed Mesh.
  33947. */
  33948. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33949. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33950. if (!this.IsGlobal) {
  33951. var boundingInfo = this.getBoundingInfo();
  33952. if (!boundingInfo) {
  33953. return result;
  33954. }
  33955. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33956. }
  33957. return result;
  33958. };
  33959. // Dispose
  33960. /**
  33961. * Disposes the Submesh.
  33962. * Returns nothing.
  33963. */
  33964. SubMesh.prototype.dispose = function () {
  33965. if (this._linesIndexBuffer) {
  33966. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33967. this._linesIndexBuffer = null;
  33968. }
  33969. // Remove from mesh
  33970. var index = this._mesh.subMeshes.indexOf(this);
  33971. this._mesh.subMeshes.splice(index, 1);
  33972. };
  33973. // Statics
  33974. /**
  33975. * Creates a new Submesh from the passed parameters :
  33976. * - materialIndex (integer) : the index of the main mesh material.
  33977. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33978. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33979. * - mesh (Mesh) : the main mesh to create the submesh from.
  33980. * - renderingMesh (optional Mesh) : rendering mesh.
  33981. */
  33982. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33983. var minVertexIndex = Number.MAX_VALUE;
  33984. var maxVertexIndex = -Number.MAX_VALUE;
  33985. renderingMesh = (renderingMesh || mesh);
  33986. var indices = renderingMesh.getIndices();
  33987. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33988. var vertexIndex = indices[index];
  33989. if (vertexIndex < minVertexIndex)
  33990. minVertexIndex = vertexIndex;
  33991. if (vertexIndex > maxVertexIndex)
  33992. maxVertexIndex = vertexIndex;
  33993. }
  33994. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33995. };
  33996. return SubMesh;
  33997. }(BaseSubMesh));
  33998. BABYLON.SubMesh = SubMesh;
  33999. })(BABYLON || (BABYLON = {}));
  34000. //# sourceMappingURL=babylon.subMesh.js.map
  34001. var __assign = (this && this.__assign) || function () {
  34002. __assign = Object.assign || function(t) {
  34003. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34004. s = arguments[i];
  34005. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34006. t[p] = s[p];
  34007. }
  34008. return t;
  34009. };
  34010. return __assign.apply(this, arguments);
  34011. };
  34012. var BABYLON;
  34013. (function (BABYLON) {
  34014. /**
  34015. * Manages the defines for the Material
  34016. */
  34017. var MaterialDefines = /** @class */ (function () {
  34018. function MaterialDefines() {
  34019. this._isDirty = true;
  34020. /** @hidden */
  34021. this._areLightsDirty = true;
  34022. /** @hidden */
  34023. this._areAttributesDirty = true;
  34024. /** @hidden */
  34025. this._areTexturesDirty = true;
  34026. /** @hidden */
  34027. this._areFresnelDirty = true;
  34028. /** @hidden */
  34029. this._areMiscDirty = true;
  34030. /** @hidden */
  34031. this._areImageProcessingDirty = true;
  34032. /** @hidden */
  34033. this._normals = false;
  34034. /** @hidden */
  34035. this._uvs = false;
  34036. /** @hidden */
  34037. this._needNormals = false;
  34038. /** @hidden */
  34039. this._needUVs = false;
  34040. }
  34041. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34042. /**
  34043. * Specifies if the material needs to be re-calculated
  34044. */
  34045. get: function () {
  34046. return this._isDirty;
  34047. },
  34048. enumerable: true,
  34049. configurable: true
  34050. });
  34051. /**
  34052. * Marks the material to indicate that it has been re-calculated
  34053. */
  34054. MaterialDefines.prototype.markAsProcessed = function () {
  34055. this._isDirty = false;
  34056. this._areAttributesDirty = false;
  34057. this._areTexturesDirty = false;
  34058. this._areFresnelDirty = false;
  34059. this._areLightsDirty = false;
  34060. this._areMiscDirty = false;
  34061. this._areImageProcessingDirty = false;
  34062. };
  34063. /**
  34064. * Marks the material to indicate that it needs to be re-calculated
  34065. */
  34066. MaterialDefines.prototype.markAsUnprocessed = function () {
  34067. this._isDirty = true;
  34068. };
  34069. /**
  34070. * Marks the material to indicate all of its defines need to be re-calculated
  34071. */
  34072. MaterialDefines.prototype.markAllAsDirty = function () {
  34073. this._areTexturesDirty = true;
  34074. this._areAttributesDirty = true;
  34075. this._areLightsDirty = true;
  34076. this._areFresnelDirty = true;
  34077. this._areMiscDirty = true;
  34078. this._areImageProcessingDirty = true;
  34079. this._isDirty = true;
  34080. };
  34081. /**
  34082. * Marks the material to indicate that image processing needs to be re-calculated
  34083. */
  34084. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34085. this._areImageProcessingDirty = true;
  34086. this._isDirty = true;
  34087. };
  34088. /**
  34089. * Marks the material to indicate the lights need to be re-calculated
  34090. */
  34091. MaterialDefines.prototype.markAsLightDirty = function () {
  34092. this._areLightsDirty = true;
  34093. this._isDirty = true;
  34094. };
  34095. /**
  34096. * Marks the attribute state as changed
  34097. */
  34098. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34099. this._areAttributesDirty = true;
  34100. this._isDirty = true;
  34101. };
  34102. /**
  34103. * Marks the texture state as changed
  34104. */
  34105. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34106. this._areTexturesDirty = true;
  34107. this._isDirty = true;
  34108. };
  34109. /**
  34110. * Marks the fresnel state as changed
  34111. */
  34112. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34113. this._areFresnelDirty = true;
  34114. this._isDirty = true;
  34115. };
  34116. /**
  34117. * Marks the misc state as changed
  34118. */
  34119. MaterialDefines.prototype.markAsMiscDirty = function () {
  34120. this._areMiscDirty = true;
  34121. this._isDirty = true;
  34122. };
  34123. /**
  34124. * Rebuilds the material defines
  34125. */
  34126. MaterialDefines.prototype.rebuild = function () {
  34127. if (this._keys) {
  34128. delete this._keys;
  34129. }
  34130. this._keys = [];
  34131. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34132. var key = _a[_i];
  34133. if (key[0] === "_") {
  34134. continue;
  34135. }
  34136. this._keys.push(key);
  34137. }
  34138. };
  34139. /**
  34140. * Specifies if two material defines are equal
  34141. * @param other - A material define instance to compare to
  34142. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34143. */
  34144. MaterialDefines.prototype.isEqual = function (other) {
  34145. if (this._keys.length !== other._keys.length) {
  34146. return false;
  34147. }
  34148. for (var index = 0; index < this._keys.length; index++) {
  34149. var prop = this._keys[index];
  34150. if (this[prop] !== other[prop]) {
  34151. return false;
  34152. }
  34153. }
  34154. return true;
  34155. };
  34156. /**
  34157. * Clones this instance's defines to another instance
  34158. * @param other - material defines to clone values to
  34159. */
  34160. MaterialDefines.prototype.cloneTo = function (other) {
  34161. if (this._keys.length !== other._keys.length) {
  34162. other._keys = this._keys.slice(0);
  34163. }
  34164. for (var index = 0; index < this._keys.length; index++) {
  34165. var prop = this._keys[index];
  34166. other[prop] = this[prop];
  34167. }
  34168. };
  34169. /**
  34170. * Resets the material define values
  34171. */
  34172. MaterialDefines.prototype.reset = function () {
  34173. for (var index = 0; index < this._keys.length; index++) {
  34174. var prop = this._keys[index];
  34175. var type = typeof this[prop];
  34176. switch (type) {
  34177. case "number":
  34178. this[prop] = 0;
  34179. break;
  34180. case "string":
  34181. this[prop] = "";
  34182. break;
  34183. default:
  34184. this[prop] = false;
  34185. break;
  34186. }
  34187. }
  34188. };
  34189. /**
  34190. * Converts the material define values to a string
  34191. * @returns - String of material define information
  34192. */
  34193. MaterialDefines.prototype.toString = function () {
  34194. var result = "";
  34195. for (var index = 0; index < this._keys.length; index++) {
  34196. var prop = this._keys[index];
  34197. var value = this[prop];
  34198. var type = typeof value;
  34199. switch (type) {
  34200. case "number":
  34201. case "string":
  34202. result += "#define " + prop + " " + value + "\n";
  34203. break;
  34204. default:
  34205. if (value) {
  34206. result += "#define " + prop + "\n";
  34207. }
  34208. break;
  34209. }
  34210. }
  34211. return result;
  34212. };
  34213. return MaterialDefines;
  34214. }());
  34215. BABYLON.MaterialDefines = MaterialDefines;
  34216. /**
  34217. * Base class for the main features of a material in Babylon.js
  34218. */
  34219. var Material = /** @class */ (function () {
  34220. /**
  34221. * Creates a material instance
  34222. * @param name defines the name of the material
  34223. * @param scene defines the scene to reference
  34224. * @param doNotAdd specifies if the material should be added to the scene
  34225. */
  34226. function Material(name, scene, doNotAdd) {
  34227. /**
  34228. * Specifies if the ready state should be checked on each call
  34229. */
  34230. this.checkReadyOnEveryCall = false;
  34231. /**
  34232. * Specifies if the ready state should be checked once
  34233. */
  34234. this.checkReadyOnlyOnce = false;
  34235. /**
  34236. * The state of the material
  34237. */
  34238. this.state = "";
  34239. /**
  34240. * The alpha value of the material
  34241. */
  34242. this._alpha = 1.0;
  34243. /**
  34244. * Specifies if back face culling is enabled
  34245. */
  34246. this._backFaceCulling = true;
  34247. /**
  34248. * Gets a boolean indicating that current material needs to register RTT
  34249. */
  34250. this.hasRenderTargetTextures = false;
  34251. /**
  34252. * Specifies if the material should be serialized
  34253. */
  34254. this.doNotSerialize = false;
  34255. /**
  34256. * Specifies if the effect should be stored on sub meshes
  34257. */
  34258. this.storeEffectOnSubMeshes = false;
  34259. /**
  34260. * An event triggered when the material is disposed
  34261. */
  34262. this.onDisposeObservable = new BABYLON.Observable();
  34263. /**
  34264. * Stores the value of the alpha mode
  34265. */
  34266. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34267. /**
  34268. * Stores the state of the need depth pre-pass value
  34269. */
  34270. this._needDepthPrePass = false;
  34271. /**
  34272. * Specifies if depth writing should be disabled
  34273. */
  34274. this.disableDepthWrite = false;
  34275. /**
  34276. * Specifies if depth writing should be forced
  34277. */
  34278. this.forceDepthWrite = false;
  34279. /**
  34280. * Specifies if there should be a separate pass for culling
  34281. */
  34282. this.separateCullingPass = false;
  34283. /**
  34284. * Stores the state specifing if fog should be enabled
  34285. */
  34286. this._fogEnabled = true;
  34287. /**
  34288. * Stores the size of points
  34289. */
  34290. this.pointSize = 1.0;
  34291. /**
  34292. * Stores the z offset value
  34293. */
  34294. this.zOffset = 0;
  34295. /**
  34296. * @hidden
  34297. * Specifies if the material was previously ready
  34298. */
  34299. this._wasPreviouslyReady = false;
  34300. /**
  34301. * Stores the fill mode state
  34302. */
  34303. this._fillMode = Material.TriangleFillMode;
  34304. this.name = name;
  34305. this.id = name || BABYLON.Tools.RandomId();
  34306. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34307. this.uniqueId = this._scene.getUniqueId();
  34308. if (this._scene.useRightHandedSystem) {
  34309. this.sideOrientation = Material.ClockWiseSideOrientation;
  34310. }
  34311. else {
  34312. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34313. }
  34314. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34315. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34316. if (!doNotAdd) {
  34317. this._scene.materials.push(this);
  34318. }
  34319. }
  34320. Object.defineProperty(Material, "TriangleFillMode", {
  34321. /**
  34322. * Returns the triangle fill mode
  34323. */
  34324. get: function () {
  34325. return Material._TriangleFillMode;
  34326. },
  34327. enumerable: true,
  34328. configurable: true
  34329. });
  34330. Object.defineProperty(Material, "WireFrameFillMode", {
  34331. /**
  34332. * Returns the wireframe mode
  34333. */
  34334. get: function () {
  34335. return Material._WireFrameFillMode;
  34336. },
  34337. enumerable: true,
  34338. configurable: true
  34339. });
  34340. Object.defineProperty(Material, "PointFillMode", {
  34341. /**
  34342. * Returns the point fill mode
  34343. */
  34344. get: function () {
  34345. return Material._PointFillMode;
  34346. },
  34347. enumerable: true,
  34348. configurable: true
  34349. });
  34350. Object.defineProperty(Material, "PointListDrawMode", {
  34351. /**
  34352. * Returns the point list draw mode
  34353. */
  34354. get: function () {
  34355. return Material._PointListDrawMode;
  34356. },
  34357. enumerable: true,
  34358. configurable: true
  34359. });
  34360. Object.defineProperty(Material, "LineListDrawMode", {
  34361. /**
  34362. * Returns the line list draw mode
  34363. */
  34364. get: function () {
  34365. return Material._LineListDrawMode;
  34366. },
  34367. enumerable: true,
  34368. configurable: true
  34369. });
  34370. Object.defineProperty(Material, "LineLoopDrawMode", {
  34371. /**
  34372. * Returns the line loop draw mode
  34373. */
  34374. get: function () {
  34375. return Material._LineLoopDrawMode;
  34376. },
  34377. enumerable: true,
  34378. configurable: true
  34379. });
  34380. Object.defineProperty(Material, "LineStripDrawMode", {
  34381. /**
  34382. * Returns the line strip draw mode
  34383. */
  34384. get: function () {
  34385. return Material._LineStripDrawMode;
  34386. },
  34387. enumerable: true,
  34388. configurable: true
  34389. });
  34390. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34391. /**
  34392. * Returns the triangle strip draw mode
  34393. */
  34394. get: function () {
  34395. return Material._TriangleStripDrawMode;
  34396. },
  34397. enumerable: true,
  34398. configurable: true
  34399. });
  34400. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34401. /**
  34402. * Returns the triangle fan draw mode
  34403. */
  34404. get: function () {
  34405. return Material._TriangleFanDrawMode;
  34406. },
  34407. enumerable: true,
  34408. configurable: true
  34409. });
  34410. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34411. /**
  34412. * Returns the clock-wise side orientation
  34413. */
  34414. get: function () {
  34415. return Material._ClockWiseSideOrientation;
  34416. },
  34417. enumerable: true,
  34418. configurable: true
  34419. });
  34420. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34421. /**
  34422. * Returns the counter clock-wise side orientation
  34423. */
  34424. get: function () {
  34425. return Material._CounterClockWiseSideOrientation;
  34426. },
  34427. enumerable: true,
  34428. configurable: true
  34429. });
  34430. Object.defineProperty(Material, "TextureDirtyFlag", {
  34431. /**
  34432. * Returns the dirty texture flag value
  34433. */
  34434. get: function () {
  34435. return Material._TextureDirtyFlag;
  34436. },
  34437. enumerable: true,
  34438. configurable: true
  34439. });
  34440. Object.defineProperty(Material, "LightDirtyFlag", {
  34441. /**
  34442. * Returns the dirty light flag value
  34443. */
  34444. get: function () {
  34445. return Material._LightDirtyFlag;
  34446. },
  34447. enumerable: true,
  34448. configurable: true
  34449. });
  34450. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34451. /**
  34452. * Returns the dirty fresnel flag value
  34453. */
  34454. get: function () {
  34455. return Material._FresnelDirtyFlag;
  34456. },
  34457. enumerable: true,
  34458. configurable: true
  34459. });
  34460. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34461. /**
  34462. * Returns the dirty attributes flag value
  34463. */
  34464. get: function () {
  34465. return Material._AttributesDirtyFlag;
  34466. },
  34467. enumerable: true,
  34468. configurable: true
  34469. });
  34470. Object.defineProperty(Material, "MiscDirtyFlag", {
  34471. /**
  34472. * Returns the dirty misc flag value
  34473. */
  34474. get: function () {
  34475. return Material._MiscDirtyFlag;
  34476. },
  34477. enumerable: true,
  34478. configurable: true
  34479. });
  34480. Object.defineProperty(Material.prototype, "alpha", {
  34481. /**
  34482. * Gets the alpha value of the material
  34483. */
  34484. get: function () {
  34485. return this._alpha;
  34486. },
  34487. /**
  34488. * Sets the alpha value of the material
  34489. */
  34490. set: function (value) {
  34491. if (this._alpha === value) {
  34492. return;
  34493. }
  34494. this._alpha = value;
  34495. this.markAsDirty(Material.MiscDirtyFlag);
  34496. },
  34497. enumerable: true,
  34498. configurable: true
  34499. });
  34500. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34501. /**
  34502. * Gets the back-face culling state
  34503. */
  34504. get: function () {
  34505. return this._backFaceCulling;
  34506. },
  34507. /**
  34508. * Sets the back-face culling state
  34509. */
  34510. set: function (value) {
  34511. if (this._backFaceCulling === value) {
  34512. return;
  34513. }
  34514. this._backFaceCulling = value;
  34515. this.markAsDirty(Material.TextureDirtyFlag);
  34516. },
  34517. enumerable: true,
  34518. configurable: true
  34519. });
  34520. Object.defineProperty(Material.prototype, "onDispose", {
  34521. /**
  34522. * Called during a dispose event
  34523. */
  34524. set: function (callback) {
  34525. if (this._onDisposeObserver) {
  34526. this.onDisposeObservable.remove(this._onDisposeObserver);
  34527. }
  34528. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34529. },
  34530. enumerable: true,
  34531. configurable: true
  34532. });
  34533. Object.defineProperty(Material.prototype, "onBindObservable", {
  34534. /**
  34535. * An event triggered when the material is bound
  34536. */
  34537. get: function () {
  34538. if (!this._onBindObservable) {
  34539. this._onBindObservable = new BABYLON.Observable();
  34540. }
  34541. return this._onBindObservable;
  34542. },
  34543. enumerable: true,
  34544. configurable: true
  34545. });
  34546. Object.defineProperty(Material.prototype, "onBind", {
  34547. /**
  34548. * Called during a bind event
  34549. */
  34550. set: function (callback) {
  34551. if (this._onBindObserver) {
  34552. this.onBindObservable.remove(this._onBindObserver);
  34553. }
  34554. this._onBindObserver = this.onBindObservable.add(callback);
  34555. },
  34556. enumerable: true,
  34557. configurable: true
  34558. });
  34559. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34560. /**
  34561. * An event triggered when the material is unbound
  34562. */
  34563. get: function () {
  34564. if (!this._onUnBindObservable) {
  34565. this._onUnBindObservable = new BABYLON.Observable();
  34566. }
  34567. return this._onUnBindObservable;
  34568. },
  34569. enumerable: true,
  34570. configurable: true
  34571. });
  34572. Object.defineProperty(Material.prototype, "alphaMode", {
  34573. /**
  34574. * Gets the value of the alpha mode
  34575. */
  34576. get: function () {
  34577. return this._alphaMode;
  34578. },
  34579. /**
  34580. * Sets the value of the alpha mode.
  34581. *
  34582. * | Value | Type | Description |
  34583. * | --- | --- | --- |
  34584. * | 0 | ALPHA_DISABLE | |
  34585. * | 1 | ALPHA_ADD | |
  34586. * | 2 | ALPHA_COMBINE | |
  34587. * | 3 | ALPHA_SUBTRACT | |
  34588. * | 4 | ALPHA_MULTIPLY | |
  34589. * | 5 | ALPHA_MAXIMIZED | |
  34590. * | 6 | ALPHA_ONEONE | |
  34591. * | 7 | ALPHA_PREMULTIPLIED | |
  34592. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34593. * | 9 | ALPHA_INTERPOLATE | |
  34594. * | 10 | ALPHA_SCREENMODE | |
  34595. *
  34596. */
  34597. set: function (value) {
  34598. if (this._alphaMode === value) {
  34599. return;
  34600. }
  34601. this._alphaMode = value;
  34602. this.markAsDirty(Material.TextureDirtyFlag);
  34603. },
  34604. enumerable: true,
  34605. configurable: true
  34606. });
  34607. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34608. /**
  34609. * Gets the depth pre-pass value
  34610. */
  34611. get: function () {
  34612. return this._needDepthPrePass;
  34613. },
  34614. /**
  34615. * Sets the need depth pre-pass value
  34616. */
  34617. set: function (value) {
  34618. if (this._needDepthPrePass === value) {
  34619. return;
  34620. }
  34621. this._needDepthPrePass = value;
  34622. if (this._needDepthPrePass) {
  34623. this.checkReadyOnEveryCall = true;
  34624. }
  34625. },
  34626. enumerable: true,
  34627. configurable: true
  34628. });
  34629. Object.defineProperty(Material.prototype, "fogEnabled", {
  34630. /**
  34631. * Gets the value of the fog enabled state
  34632. */
  34633. get: function () {
  34634. return this._fogEnabled;
  34635. },
  34636. /**
  34637. * Sets the state for enabling fog
  34638. */
  34639. set: function (value) {
  34640. if (this._fogEnabled === value) {
  34641. return;
  34642. }
  34643. this._fogEnabled = value;
  34644. this.markAsDirty(Material.MiscDirtyFlag);
  34645. },
  34646. enumerable: true,
  34647. configurable: true
  34648. });
  34649. Object.defineProperty(Material.prototype, "wireframe", {
  34650. /**
  34651. * Gets a value specifying if wireframe mode is enabled
  34652. */
  34653. get: function () {
  34654. switch (this._fillMode) {
  34655. case Material.WireFrameFillMode:
  34656. case Material.LineListDrawMode:
  34657. case Material.LineLoopDrawMode:
  34658. case Material.LineStripDrawMode:
  34659. return true;
  34660. }
  34661. return this._scene.forceWireframe;
  34662. },
  34663. /**
  34664. * Sets the state of wireframe mode
  34665. */
  34666. set: function (value) {
  34667. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34668. },
  34669. enumerable: true,
  34670. configurable: true
  34671. });
  34672. Object.defineProperty(Material.prototype, "pointsCloud", {
  34673. /**
  34674. * Gets the value specifying if point clouds are enabled
  34675. */
  34676. get: function () {
  34677. switch (this._fillMode) {
  34678. case Material.PointFillMode:
  34679. case Material.PointListDrawMode:
  34680. return true;
  34681. }
  34682. return this._scene.forcePointsCloud;
  34683. },
  34684. /**
  34685. * Sets the state of point cloud mode
  34686. */
  34687. set: function (value) {
  34688. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34689. },
  34690. enumerable: true,
  34691. configurable: true
  34692. });
  34693. Object.defineProperty(Material.prototype, "fillMode", {
  34694. /**
  34695. * Gets the material fill mode
  34696. */
  34697. get: function () {
  34698. return this._fillMode;
  34699. },
  34700. /**
  34701. * Sets the material fill mode
  34702. */
  34703. set: function (value) {
  34704. if (this._fillMode === value) {
  34705. return;
  34706. }
  34707. this._fillMode = value;
  34708. this.markAsDirty(Material.MiscDirtyFlag);
  34709. },
  34710. enumerable: true,
  34711. configurable: true
  34712. });
  34713. /**
  34714. * Returns a string representation of the current material
  34715. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34716. * @returns a string with material information
  34717. */
  34718. Material.prototype.toString = function (fullDetails) {
  34719. var ret = "Name: " + this.name;
  34720. if (fullDetails) {
  34721. }
  34722. return ret;
  34723. };
  34724. /**
  34725. * Gets the class name of the material
  34726. * @returns a string with the class name of the material
  34727. */
  34728. Material.prototype.getClassName = function () {
  34729. return "Material";
  34730. };
  34731. Object.defineProperty(Material.prototype, "isFrozen", {
  34732. /**
  34733. * Specifies if updates for the material been locked
  34734. */
  34735. get: function () {
  34736. return this.checkReadyOnlyOnce;
  34737. },
  34738. enumerable: true,
  34739. configurable: true
  34740. });
  34741. /**
  34742. * Locks updates for the material
  34743. */
  34744. Material.prototype.freeze = function () {
  34745. this.checkReadyOnlyOnce = true;
  34746. };
  34747. /**
  34748. * Unlocks updates for the material
  34749. */
  34750. Material.prototype.unfreeze = function () {
  34751. this.checkReadyOnlyOnce = false;
  34752. };
  34753. /**
  34754. * Specifies if the material is ready to be used
  34755. * @param mesh defines the mesh to check
  34756. * @param useInstances specifies if instances should be used
  34757. * @returns a boolean indicating if the material is ready to be used
  34758. */
  34759. Material.prototype.isReady = function (mesh, useInstances) {
  34760. return true;
  34761. };
  34762. /**
  34763. * Specifies that the submesh is ready to be used
  34764. * @param mesh defines the mesh to check
  34765. * @param subMesh defines which submesh to check
  34766. * @param useInstances specifies that instances should be used
  34767. * @returns a boolean indicating that the submesh is ready or not
  34768. */
  34769. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34770. return false;
  34771. };
  34772. /**
  34773. * Returns the material effect
  34774. * @returns the effect associated with the material
  34775. */
  34776. Material.prototype.getEffect = function () {
  34777. return this._effect;
  34778. };
  34779. /**
  34780. * Returns the current scene
  34781. * @returns a Scene
  34782. */
  34783. Material.prototype.getScene = function () {
  34784. return this._scene;
  34785. };
  34786. /**
  34787. * Specifies if the material will require alpha blending
  34788. * @returns a boolean specifying if alpha blending is needed
  34789. */
  34790. Material.prototype.needAlphaBlending = function () {
  34791. return (this.alpha < 1.0);
  34792. };
  34793. /**
  34794. * Specifies if the mesh will require alpha blending
  34795. * @param mesh defines the mesh to check
  34796. * @returns a boolean specifying if alpha blending is needed for the mesh
  34797. */
  34798. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34799. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34800. };
  34801. /**
  34802. * Specifies if this material should be rendered in alpha test mode
  34803. * @returns a boolean specifying if an alpha test is needed.
  34804. */
  34805. Material.prototype.needAlphaTesting = function () {
  34806. return false;
  34807. };
  34808. /**
  34809. * Gets the texture used for the alpha test
  34810. * @returns the texture to use for alpha testing
  34811. */
  34812. Material.prototype.getAlphaTestTexture = function () {
  34813. return null;
  34814. };
  34815. /**
  34816. * Marks the material to indicate that it needs to be re-calculated
  34817. */
  34818. Material.prototype.markDirty = function () {
  34819. this._wasPreviouslyReady = false;
  34820. };
  34821. /** @hidden */
  34822. Material.prototype._preBind = function (effect, overrideOrientation) {
  34823. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34824. var engine = this._scene.getEngine();
  34825. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34826. var reverse = orientation === Material.ClockWiseSideOrientation;
  34827. engine.enableEffect(effect ? effect : this._effect);
  34828. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34829. return reverse;
  34830. };
  34831. /**
  34832. * Binds the material to the mesh
  34833. * @param world defines the world transformation matrix
  34834. * @param mesh defines the mesh to bind the material to
  34835. */
  34836. Material.prototype.bind = function (world, mesh) {
  34837. };
  34838. /**
  34839. * Binds the submesh to the material
  34840. * @param world defines the world transformation matrix
  34841. * @param mesh defines the mesh containing the submesh
  34842. * @param subMesh defines the submesh to bind the material to
  34843. */
  34844. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34845. };
  34846. /**
  34847. * Binds the world matrix to the material
  34848. * @param world defines the world transformation matrix
  34849. */
  34850. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34851. };
  34852. /**
  34853. * Binds the scene's uniform buffer to the effect.
  34854. * @param effect defines the effect to bind to the scene uniform buffer
  34855. * @param sceneUbo defines the uniform buffer storing scene data
  34856. */
  34857. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34858. sceneUbo.bindToEffect(effect, "Scene");
  34859. };
  34860. /**
  34861. * Binds the view matrix to the effect
  34862. * @param effect defines the effect to bind the view matrix to
  34863. */
  34864. Material.prototype.bindView = function (effect) {
  34865. if (!this._useUBO) {
  34866. effect.setMatrix("view", this.getScene().getViewMatrix());
  34867. }
  34868. else {
  34869. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34870. }
  34871. };
  34872. /**
  34873. * Binds the view projection matrix to the effect
  34874. * @param effect defines the effect to bind the view projection matrix to
  34875. */
  34876. Material.prototype.bindViewProjection = function (effect) {
  34877. if (!this._useUBO) {
  34878. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34879. }
  34880. else {
  34881. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34882. }
  34883. };
  34884. /**
  34885. * Specifies if material alpha testing should be turned on for the mesh
  34886. * @param mesh defines the mesh to check
  34887. */
  34888. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34889. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34890. };
  34891. /**
  34892. * Processes to execute after binding the material to a mesh
  34893. * @param mesh defines the rendered mesh
  34894. */
  34895. Material.prototype._afterBind = function (mesh) {
  34896. this._scene._cachedMaterial = this;
  34897. if (mesh) {
  34898. this._scene._cachedVisibility = mesh.visibility;
  34899. }
  34900. else {
  34901. this._scene._cachedVisibility = 1;
  34902. }
  34903. if (this._onBindObservable && mesh) {
  34904. this._onBindObservable.notifyObservers(mesh);
  34905. }
  34906. if (this.disableDepthWrite) {
  34907. var engine = this._scene.getEngine();
  34908. this._cachedDepthWriteState = engine.getDepthWrite();
  34909. engine.setDepthWrite(false);
  34910. }
  34911. };
  34912. /**
  34913. * Unbinds the material from the mesh
  34914. */
  34915. Material.prototype.unbind = function () {
  34916. if (this._onUnBindObservable) {
  34917. this._onUnBindObservable.notifyObservers(this);
  34918. }
  34919. if (this.disableDepthWrite) {
  34920. var engine = this._scene.getEngine();
  34921. engine.setDepthWrite(this._cachedDepthWriteState);
  34922. }
  34923. };
  34924. /**
  34925. * Gets the active textures from the material
  34926. * @returns an array of textures
  34927. */
  34928. Material.prototype.getActiveTextures = function () {
  34929. return [];
  34930. };
  34931. /**
  34932. * Specifies if the material uses a texture
  34933. * @param texture defines the texture to check against the material
  34934. * @returns a boolean specifying if the material uses the texture
  34935. */
  34936. Material.prototype.hasTexture = function (texture) {
  34937. return false;
  34938. };
  34939. /**
  34940. * Makes a duplicate of the material, and gives it a new name
  34941. * @param name defines the new name for the duplicated material
  34942. * @returns the cloned material
  34943. */
  34944. Material.prototype.clone = function (name) {
  34945. return null;
  34946. };
  34947. /**
  34948. * Gets the meshes bound to the material
  34949. * @returns an array of meshes bound to the material
  34950. */
  34951. Material.prototype.getBindedMeshes = function () {
  34952. var result = new Array();
  34953. for (var index = 0; index < this._scene.meshes.length; index++) {
  34954. var mesh = this._scene.meshes[index];
  34955. if (mesh.material === this) {
  34956. result.push(mesh);
  34957. }
  34958. }
  34959. return result;
  34960. };
  34961. /**
  34962. * Force shader compilation
  34963. * @param mesh defines the mesh associated with this material
  34964. * @param onCompiled defines a function to execute once the material is compiled
  34965. * @param options defines the options to configure the compilation
  34966. */
  34967. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34968. var _this = this;
  34969. var localOptions = __assign({ clipPlane: false }, options);
  34970. var subMesh = new BABYLON.BaseSubMesh();
  34971. var scene = this.getScene();
  34972. var checkReady = function () {
  34973. if (!_this._scene || !_this._scene.getEngine()) {
  34974. return;
  34975. }
  34976. if (subMesh._materialDefines) {
  34977. subMesh._materialDefines._renderId = -1;
  34978. }
  34979. var clipPlaneState = scene.clipPlane;
  34980. if (localOptions.clipPlane) {
  34981. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34982. }
  34983. if (_this.storeEffectOnSubMeshes) {
  34984. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34985. if (onCompiled) {
  34986. onCompiled(_this);
  34987. }
  34988. }
  34989. else {
  34990. setTimeout(checkReady, 16);
  34991. }
  34992. }
  34993. else {
  34994. if (_this.isReady(mesh)) {
  34995. if (onCompiled) {
  34996. onCompiled(_this);
  34997. }
  34998. }
  34999. else {
  35000. setTimeout(checkReady, 16);
  35001. }
  35002. }
  35003. if (localOptions.clipPlane) {
  35004. scene.clipPlane = clipPlaneState;
  35005. }
  35006. };
  35007. checkReady();
  35008. };
  35009. /**
  35010. * Force shader compilation
  35011. * @param mesh defines the mesh that will use this material
  35012. * @param options defines additional options for compiling the shaders
  35013. * @returns a promise that resolves when the compilation completes
  35014. */
  35015. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35016. var _this = this;
  35017. return new Promise(function (resolve) {
  35018. _this.forceCompilation(mesh, function () {
  35019. resolve();
  35020. }, options);
  35021. });
  35022. };
  35023. /**
  35024. * Marks a define in the material to indicate that it needs to be re-computed
  35025. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35026. */
  35027. Material.prototype.markAsDirty = function (flag) {
  35028. if (flag & Material.TextureDirtyFlag) {
  35029. this._markAllSubMeshesAsTexturesDirty();
  35030. }
  35031. if (flag & Material.LightDirtyFlag) {
  35032. this._markAllSubMeshesAsLightsDirty();
  35033. }
  35034. if (flag & Material.FresnelDirtyFlag) {
  35035. this._markAllSubMeshesAsFresnelDirty();
  35036. }
  35037. if (flag & Material.AttributesDirtyFlag) {
  35038. this._markAllSubMeshesAsAttributesDirty();
  35039. }
  35040. if (flag & Material.MiscDirtyFlag) {
  35041. this._markAllSubMeshesAsMiscDirty();
  35042. }
  35043. this.getScene().resetCachedMaterial();
  35044. };
  35045. /**
  35046. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35047. * @param func defines a function which checks material defines against the submeshes
  35048. */
  35049. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35050. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35051. var mesh = _a[_i];
  35052. if (!mesh.subMeshes) {
  35053. continue;
  35054. }
  35055. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35056. var subMesh = _c[_b];
  35057. if (subMesh.getMaterial() !== this) {
  35058. continue;
  35059. }
  35060. if (!subMesh._materialDefines) {
  35061. continue;
  35062. }
  35063. func(subMesh._materialDefines);
  35064. }
  35065. }
  35066. };
  35067. /**
  35068. * Indicates that image processing needs to be re-calculated for all submeshes
  35069. */
  35070. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35071. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35072. };
  35073. /**
  35074. * Indicates that textures need to be re-calculated for all submeshes
  35075. */
  35076. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35077. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35078. };
  35079. /**
  35080. * Indicates that fresnel needs to be re-calculated for all submeshes
  35081. */
  35082. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35083. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35084. };
  35085. /**
  35086. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35087. */
  35088. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35089. this._markAllSubMeshesAsDirty(function (defines) {
  35090. defines.markAsFresnelDirty();
  35091. defines.markAsMiscDirty();
  35092. });
  35093. };
  35094. /**
  35095. * Indicates that lights need to be re-calculated for all submeshes
  35096. */
  35097. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35098. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35099. };
  35100. /**
  35101. * Indicates that attributes need to be re-calculated for all submeshes
  35102. */
  35103. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35104. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35105. };
  35106. /**
  35107. * Indicates that misc needs to be re-calculated for all submeshes
  35108. */
  35109. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35110. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35111. };
  35112. /**
  35113. * Indicates that textures and misc need to be re-calculated for all submeshes
  35114. */
  35115. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35116. this._markAllSubMeshesAsDirty(function (defines) {
  35117. defines.markAsTexturesDirty();
  35118. defines.markAsMiscDirty();
  35119. });
  35120. };
  35121. /**
  35122. * Disposes the material
  35123. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35124. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35125. */
  35126. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35127. // Animations
  35128. this.getScene().stopAnimation(this);
  35129. this.getScene().freeProcessedMaterials();
  35130. // Remove from scene
  35131. var index = this._scene.materials.indexOf(this);
  35132. if (index >= 0) {
  35133. this._scene.materials.splice(index, 1);
  35134. }
  35135. // Remove from meshes
  35136. for (index = 0; index < this._scene.meshes.length; index++) {
  35137. var mesh = this._scene.meshes[index];
  35138. if (mesh.material === this) {
  35139. mesh.material = null;
  35140. if (mesh.geometry) {
  35141. var geometry = (mesh.geometry);
  35142. if (this.storeEffectOnSubMeshes) {
  35143. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35144. var subMesh = _a[_i];
  35145. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35146. if (forceDisposeEffect && subMesh._materialEffect) {
  35147. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35148. }
  35149. }
  35150. }
  35151. else {
  35152. geometry._releaseVertexArrayObject(this._effect);
  35153. }
  35154. }
  35155. }
  35156. }
  35157. this._uniformBuffer.dispose();
  35158. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35159. if (forceDisposeEffect && this._effect) {
  35160. if (!this.storeEffectOnSubMeshes) {
  35161. this._scene.getEngine()._releaseEffect(this._effect);
  35162. }
  35163. this._effect = null;
  35164. }
  35165. // Callback
  35166. this.onDisposeObservable.notifyObservers(this);
  35167. this.onDisposeObservable.clear();
  35168. if (this._onBindObservable) {
  35169. this._onBindObservable.clear();
  35170. }
  35171. if (this._onUnBindObservable) {
  35172. this._onUnBindObservable.clear();
  35173. }
  35174. };
  35175. /**
  35176. * Serializes this material
  35177. * @returns the serialized material object
  35178. */
  35179. Material.prototype.serialize = function () {
  35180. return BABYLON.SerializationHelper.Serialize(this);
  35181. };
  35182. /**
  35183. * Creates a MultiMaterial from parsed MultiMaterial data.
  35184. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35185. * @param scene defines the hosting scene
  35186. * @returns a new MultiMaterial
  35187. */
  35188. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35189. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35190. multiMaterial.id = parsedMultiMaterial.id;
  35191. if (BABYLON.Tags) {
  35192. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35193. }
  35194. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35195. var subMatId = parsedMultiMaterial.materials[matIndex];
  35196. if (subMatId) {
  35197. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35198. }
  35199. else {
  35200. multiMaterial.subMaterials.push(null);
  35201. }
  35202. }
  35203. return multiMaterial;
  35204. };
  35205. /**
  35206. * Creates a material from parsed material data
  35207. * @param parsedMaterial defines parsed material data
  35208. * @param scene defines the hosting scene
  35209. * @param rootUrl defines the root URL to use to load textures
  35210. * @returns a new material
  35211. */
  35212. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35213. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35214. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35215. }
  35216. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35217. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35218. if (!BABYLON.LegacyPBRMaterial) {
  35219. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35220. return;
  35221. }
  35222. }
  35223. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35224. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35225. };
  35226. // Triangle views
  35227. Material._TriangleFillMode = 0;
  35228. Material._WireFrameFillMode = 1;
  35229. Material._PointFillMode = 2;
  35230. // Draw modes
  35231. Material._PointListDrawMode = 3;
  35232. Material._LineListDrawMode = 4;
  35233. Material._LineLoopDrawMode = 5;
  35234. Material._LineStripDrawMode = 6;
  35235. Material._TriangleStripDrawMode = 7;
  35236. Material._TriangleFanDrawMode = 8;
  35237. /**
  35238. * Stores the clock-wise side orientation
  35239. */
  35240. Material._ClockWiseSideOrientation = 0;
  35241. /**
  35242. * Stores the counter clock-wise side orientation
  35243. */
  35244. Material._CounterClockWiseSideOrientation = 1;
  35245. /**
  35246. * The dirty texture flag value
  35247. */
  35248. Material._TextureDirtyFlag = 1;
  35249. /**
  35250. * The dirty light flag value
  35251. */
  35252. Material._LightDirtyFlag = 2;
  35253. /**
  35254. * The dirty fresnel flag value
  35255. */
  35256. Material._FresnelDirtyFlag = 4;
  35257. /**
  35258. * The dirty attribute flag value
  35259. */
  35260. Material._AttributesDirtyFlag = 8;
  35261. /**
  35262. * The dirty misc flag value
  35263. */
  35264. Material._MiscDirtyFlag = 16;
  35265. __decorate([
  35266. BABYLON.serialize()
  35267. ], Material.prototype, "id", void 0);
  35268. __decorate([
  35269. BABYLON.serialize()
  35270. ], Material.prototype, "uniqueId", void 0);
  35271. __decorate([
  35272. BABYLON.serialize()
  35273. ], Material.prototype, "name", void 0);
  35274. __decorate([
  35275. BABYLON.serialize()
  35276. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35277. __decorate([
  35278. BABYLON.serialize()
  35279. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35280. __decorate([
  35281. BABYLON.serialize()
  35282. ], Material.prototype, "state", void 0);
  35283. __decorate([
  35284. BABYLON.serialize("alpha")
  35285. ], Material.prototype, "_alpha", void 0);
  35286. __decorate([
  35287. BABYLON.serialize("backFaceCulling")
  35288. ], Material.prototype, "_backFaceCulling", void 0);
  35289. __decorate([
  35290. BABYLON.serialize()
  35291. ], Material.prototype, "sideOrientation", void 0);
  35292. __decorate([
  35293. BABYLON.serialize("alphaMode")
  35294. ], Material.prototype, "_alphaMode", void 0);
  35295. __decorate([
  35296. BABYLON.serialize()
  35297. ], Material.prototype, "_needDepthPrePass", void 0);
  35298. __decorate([
  35299. BABYLON.serialize()
  35300. ], Material.prototype, "disableDepthWrite", void 0);
  35301. __decorate([
  35302. BABYLON.serialize()
  35303. ], Material.prototype, "forceDepthWrite", void 0);
  35304. __decorate([
  35305. BABYLON.serialize()
  35306. ], Material.prototype, "separateCullingPass", void 0);
  35307. __decorate([
  35308. BABYLON.serialize("fogEnabled")
  35309. ], Material.prototype, "_fogEnabled", void 0);
  35310. __decorate([
  35311. BABYLON.serialize()
  35312. ], Material.prototype, "pointSize", void 0);
  35313. __decorate([
  35314. BABYLON.serialize()
  35315. ], Material.prototype, "zOffset", void 0);
  35316. __decorate([
  35317. BABYLON.serialize()
  35318. ], Material.prototype, "wireframe", null);
  35319. __decorate([
  35320. BABYLON.serialize()
  35321. ], Material.prototype, "pointsCloud", null);
  35322. __decorate([
  35323. BABYLON.serialize()
  35324. ], Material.prototype, "fillMode", null);
  35325. return Material;
  35326. }());
  35327. BABYLON.Material = Material;
  35328. })(BABYLON || (BABYLON = {}));
  35329. //# sourceMappingURL=babylon.material.js.map
  35330. var BABYLON;
  35331. (function (BABYLON) {
  35332. var UniformBuffer = /** @class */ (function () {
  35333. /**
  35334. * Uniform buffer objects.
  35335. *
  35336. * Handles blocks of uniform on the GPU.
  35337. *
  35338. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35339. *
  35340. * For more information, please refer to :
  35341. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35342. */
  35343. function UniformBuffer(engine, data, dynamic) {
  35344. this._engine = engine;
  35345. this._noUBO = !engine.supportsUniformBuffers;
  35346. this._dynamic = dynamic;
  35347. this._data = data || [];
  35348. this._uniformLocations = {};
  35349. this._uniformSizes = {};
  35350. this._uniformLocationPointer = 0;
  35351. this._needSync = false;
  35352. if (this._noUBO) {
  35353. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35354. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35355. this.updateFloat = this._updateFloatForEffect;
  35356. this.updateFloat2 = this._updateFloat2ForEffect;
  35357. this.updateFloat3 = this._updateFloat3ForEffect;
  35358. this.updateFloat4 = this._updateFloat4ForEffect;
  35359. this.updateMatrix = this._updateMatrixForEffect;
  35360. this.updateVector3 = this._updateVector3ForEffect;
  35361. this.updateVector4 = this._updateVector4ForEffect;
  35362. this.updateColor3 = this._updateColor3ForEffect;
  35363. this.updateColor4 = this._updateColor4ForEffect;
  35364. }
  35365. else {
  35366. this._engine._uniformBuffers.push(this);
  35367. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35368. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35369. this.updateFloat = this._updateFloatForUniform;
  35370. this.updateFloat2 = this._updateFloat2ForUniform;
  35371. this.updateFloat3 = this._updateFloat3ForUniform;
  35372. this.updateFloat4 = this._updateFloat4ForUniform;
  35373. this.updateMatrix = this._updateMatrixForUniform;
  35374. this.updateVector3 = this._updateVector3ForUniform;
  35375. this.updateVector4 = this._updateVector4ForUniform;
  35376. this.updateColor3 = this._updateColor3ForUniform;
  35377. this.updateColor4 = this._updateColor4ForUniform;
  35378. }
  35379. }
  35380. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35381. // Properties
  35382. /**
  35383. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35384. * or just falling back on setUniformXXX calls.
  35385. */
  35386. get: function () {
  35387. return !this._noUBO;
  35388. },
  35389. enumerable: true,
  35390. configurable: true
  35391. });
  35392. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35393. /**
  35394. * Indicates if the WebGL underlying uniform buffer is in sync
  35395. * with the javascript cache data.
  35396. */
  35397. get: function () {
  35398. return !this._needSync;
  35399. },
  35400. enumerable: true,
  35401. configurable: true
  35402. });
  35403. /**
  35404. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35405. * Also, a dynamic UniformBuffer will disable cache verification and always
  35406. * update the underlying WebGL uniform buffer to the GPU.
  35407. */
  35408. UniformBuffer.prototype.isDynamic = function () {
  35409. return this._dynamic !== undefined;
  35410. };
  35411. /**
  35412. * The data cache on JS side.
  35413. */
  35414. UniformBuffer.prototype.getData = function () {
  35415. return this._bufferData;
  35416. };
  35417. /**
  35418. * The underlying WebGL Uniform buffer.
  35419. */
  35420. UniformBuffer.prototype.getBuffer = function () {
  35421. return this._buffer;
  35422. };
  35423. /**
  35424. * std140 layout specifies how to align data within an UBO structure.
  35425. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35426. * for specs.
  35427. */
  35428. UniformBuffer.prototype._fillAlignment = function (size) {
  35429. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35430. // and 4x4 matrices
  35431. // TODO : change if other types are used
  35432. var alignment;
  35433. if (size <= 2) {
  35434. alignment = size;
  35435. }
  35436. else {
  35437. alignment = 4;
  35438. }
  35439. if ((this._uniformLocationPointer % alignment) !== 0) {
  35440. var oldPointer = this._uniformLocationPointer;
  35441. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35442. var diff = this._uniformLocationPointer - oldPointer;
  35443. for (var i = 0; i < diff; i++) {
  35444. this._data.push(0);
  35445. }
  35446. }
  35447. };
  35448. /**
  35449. * Adds an uniform in the buffer.
  35450. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35451. * for the layout to be correct !
  35452. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35453. * @param {number|number[]} size Data size, or data directly.
  35454. */
  35455. UniformBuffer.prototype.addUniform = function (name, size) {
  35456. if (this._noUBO) {
  35457. return;
  35458. }
  35459. if (this._uniformLocations[name] !== undefined) {
  35460. // Already existing uniform
  35461. return;
  35462. }
  35463. // This function must be called in the order of the shader layout !
  35464. // size can be the size of the uniform, or data directly
  35465. var data;
  35466. if (size instanceof Array) {
  35467. data = size;
  35468. size = data.length;
  35469. }
  35470. else {
  35471. size = size;
  35472. data = [];
  35473. // Fill with zeros
  35474. for (var i = 0; i < size; i++) {
  35475. data.push(0);
  35476. }
  35477. }
  35478. this._fillAlignment(size);
  35479. this._uniformSizes[name] = size;
  35480. this._uniformLocations[name] = this._uniformLocationPointer;
  35481. this._uniformLocationPointer += size;
  35482. for (var i = 0; i < size; i++) {
  35483. this._data.push(data[i]);
  35484. }
  35485. this._needSync = true;
  35486. };
  35487. /**
  35488. * Wrapper for addUniform.
  35489. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35490. * @param {Matrix} mat A 4x4 matrix.
  35491. */
  35492. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35493. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35494. };
  35495. /**
  35496. * Wrapper for addUniform.
  35497. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35498. * @param {number} x
  35499. * @param {number} y
  35500. */
  35501. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35502. var temp = [x, y];
  35503. this.addUniform(name, temp);
  35504. };
  35505. /**
  35506. * Wrapper for addUniform.
  35507. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35508. * @param {number} x
  35509. * @param {number} y
  35510. * @param {number} z
  35511. */
  35512. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35513. var temp = [x, y, z];
  35514. this.addUniform(name, temp);
  35515. };
  35516. /**
  35517. * Wrapper for addUniform.
  35518. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35519. * @param {Color3} color
  35520. */
  35521. UniformBuffer.prototype.addColor3 = function (name, color) {
  35522. var temp = new Array();
  35523. color.toArray(temp);
  35524. this.addUniform(name, temp);
  35525. };
  35526. /**
  35527. * Wrapper for addUniform.
  35528. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35529. * @param {Color3} color
  35530. * @param {number} alpha
  35531. */
  35532. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35533. var temp = new Array();
  35534. color.toArray(temp);
  35535. temp.push(alpha);
  35536. this.addUniform(name, temp);
  35537. };
  35538. /**
  35539. * Wrapper for addUniform.
  35540. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35541. * @param {Vector3} vector
  35542. */
  35543. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35544. var temp = new Array();
  35545. vector.toArray(temp);
  35546. this.addUniform(name, temp);
  35547. };
  35548. /**
  35549. * Wrapper for addUniform.
  35550. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35551. */
  35552. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35553. this.addUniform(name, 12);
  35554. };
  35555. /**
  35556. * Wrapper for addUniform.
  35557. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35558. */
  35559. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35560. this.addUniform(name, 8);
  35561. };
  35562. /**
  35563. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35564. */
  35565. UniformBuffer.prototype.create = function () {
  35566. if (this._noUBO) {
  35567. return;
  35568. }
  35569. if (this._buffer) {
  35570. return; // nothing to do
  35571. }
  35572. // See spec, alignment must be filled as a vec4
  35573. this._fillAlignment(4);
  35574. this._bufferData = new Float32Array(this._data);
  35575. this._rebuild();
  35576. this._needSync = true;
  35577. };
  35578. /** @hidden */
  35579. UniformBuffer.prototype._rebuild = function () {
  35580. if (this._noUBO) {
  35581. return;
  35582. }
  35583. if (this._dynamic) {
  35584. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35585. }
  35586. else {
  35587. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35588. }
  35589. };
  35590. /**
  35591. * Updates the WebGL Uniform Buffer on the GPU.
  35592. * If the `dynamic` flag is set to true, no cache comparison is done.
  35593. * Otherwise, the buffer will be updated only if the cache differs.
  35594. */
  35595. UniformBuffer.prototype.update = function () {
  35596. if (!this._buffer) {
  35597. this.create();
  35598. return;
  35599. }
  35600. if (!this._dynamic && !this._needSync) {
  35601. return;
  35602. }
  35603. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35604. this._needSync = false;
  35605. };
  35606. /**
  35607. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35608. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35609. * @param {number[]|Float32Array} data Flattened data
  35610. * @param {number} size Size of the data.
  35611. */
  35612. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35613. var location = this._uniformLocations[uniformName];
  35614. if (location === undefined) {
  35615. if (this._buffer) {
  35616. // Cannot add an uniform if the buffer is already created
  35617. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35618. return;
  35619. }
  35620. this.addUniform(uniformName, size);
  35621. location = this._uniformLocations[uniformName];
  35622. }
  35623. if (!this._buffer) {
  35624. this.create();
  35625. }
  35626. if (!this._dynamic) {
  35627. // Cache for static uniform buffers
  35628. var changed = false;
  35629. for (var i = 0; i < size; i++) {
  35630. if (this._bufferData[location + i] !== data[i]) {
  35631. changed = true;
  35632. this._bufferData[location + i] = data[i];
  35633. }
  35634. }
  35635. this._needSync = this._needSync || changed;
  35636. }
  35637. else {
  35638. // No cache for dynamic
  35639. for (var i = 0; i < size; i++) {
  35640. this._bufferData[location + i] = data[i];
  35641. }
  35642. }
  35643. };
  35644. // Update methods
  35645. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35646. // To match std140, matrix must be realigned
  35647. for (var i = 0; i < 3; i++) {
  35648. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35649. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35650. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35651. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35652. }
  35653. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35654. };
  35655. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35656. this._currentEffect.setMatrix3x3(name, matrix);
  35657. };
  35658. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35659. this._currentEffect.setMatrix2x2(name, matrix);
  35660. };
  35661. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35662. // To match std140, matrix must be realigned
  35663. for (var i = 0; i < 2; i++) {
  35664. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35665. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35666. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35667. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35668. }
  35669. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35670. };
  35671. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35672. this._currentEffect.setFloat(name, x);
  35673. };
  35674. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35675. UniformBuffer._tempBuffer[0] = x;
  35676. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35677. };
  35678. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35679. if (suffix === void 0) { suffix = ""; }
  35680. this._currentEffect.setFloat2(name + suffix, x, y);
  35681. };
  35682. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35683. if (suffix === void 0) { suffix = ""; }
  35684. UniformBuffer._tempBuffer[0] = x;
  35685. UniformBuffer._tempBuffer[1] = y;
  35686. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35687. };
  35688. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35689. if (suffix === void 0) { suffix = ""; }
  35690. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35691. };
  35692. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35693. if (suffix === void 0) { suffix = ""; }
  35694. UniformBuffer._tempBuffer[0] = x;
  35695. UniformBuffer._tempBuffer[1] = y;
  35696. UniformBuffer._tempBuffer[2] = z;
  35697. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35698. };
  35699. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35700. if (suffix === void 0) { suffix = ""; }
  35701. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35702. };
  35703. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35704. if (suffix === void 0) { suffix = ""; }
  35705. UniformBuffer._tempBuffer[0] = x;
  35706. UniformBuffer._tempBuffer[1] = y;
  35707. UniformBuffer._tempBuffer[2] = z;
  35708. UniformBuffer._tempBuffer[3] = w;
  35709. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35710. };
  35711. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35712. this._currentEffect.setMatrix(name, mat);
  35713. };
  35714. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35715. this.updateUniform(name, mat.toArray(), 16);
  35716. };
  35717. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35718. this._currentEffect.setVector3(name, vector);
  35719. };
  35720. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35721. vector.toArray(UniformBuffer._tempBuffer);
  35722. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35723. };
  35724. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35725. this._currentEffect.setVector4(name, vector);
  35726. };
  35727. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35728. vector.toArray(UniformBuffer._tempBuffer);
  35729. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35730. };
  35731. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35732. if (suffix === void 0) { suffix = ""; }
  35733. this._currentEffect.setColor3(name + suffix, color);
  35734. };
  35735. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35736. if (suffix === void 0) { suffix = ""; }
  35737. color.toArray(UniformBuffer._tempBuffer);
  35738. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35739. };
  35740. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35741. if (suffix === void 0) { suffix = ""; }
  35742. this._currentEffect.setColor4(name + suffix, color, alpha);
  35743. };
  35744. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35745. if (suffix === void 0) { suffix = ""; }
  35746. color.toArray(UniformBuffer._tempBuffer);
  35747. UniformBuffer._tempBuffer[3] = alpha;
  35748. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35749. };
  35750. /**
  35751. * Sets a sampler uniform on the effect.
  35752. * @param {string} name Name of the sampler.
  35753. * @param {Texture} texture
  35754. */
  35755. UniformBuffer.prototype.setTexture = function (name, texture) {
  35756. this._currentEffect.setTexture(name, texture);
  35757. };
  35758. /**
  35759. * Directly updates the value of the uniform in the cache AND on the GPU.
  35760. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35761. * @param {number[]|Float32Array} data Flattened data
  35762. */
  35763. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35764. this.updateUniform(uniformName, data, data.length);
  35765. this.update();
  35766. };
  35767. /**
  35768. * Binds this uniform buffer to an effect.
  35769. * @param {Effect} effect
  35770. * @param {string} name Name of the uniform block in the shader.
  35771. */
  35772. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35773. this._currentEffect = effect;
  35774. if (this._noUBO || !this._buffer) {
  35775. return;
  35776. }
  35777. effect.bindUniformBuffer(this._buffer, name);
  35778. };
  35779. /**
  35780. * Disposes the uniform buffer.
  35781. */
  35782. UniformBuffer.prototype.dispose = function () {
  35783. if (this._noUBO) {
  35784. return;
  35785. }
  35786. var index = this._engine._uniformBuffers.indexOf(this);
  35787. if (index !== -1) {
  35788. this._engine._uniformBuffers.splice(index, 1);
  35789. }
  35790. if (!this._buffer) {
  35791. return;
  35792. }
  35793. if (this._engine._releaseBuffer(this._buffer)) {
  35794. this._buffer = null;
  35795. }
  35796. };
  35797. // Pool for avoiding memory leaks
  35798. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35799. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35800. return UniformBuffer;
  35801. }());
  35802. BABYLON.UniformBuffer = UniformBuffer;
  35803. })(BABYLON || (BABYLON = {}));
  35804. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35805. var BABYLON;
  35806. (function (BABYLON) {
  35807. /**
  35808. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35809. */
  35810. var VertexData = /** @class */ (function () {
  35811. function VertexData() {
  35812. }
  35813. /**
  35814. * Uses the passed data array to set the set the values for the specified kind of data
  35815. * @param data a linear array of floating numbers
  35816. * @param kind the type of data that is being set, eg positions, colors etc
  35817. */
  35818. VertexData.prototype.set = function (data, kind) {
  35819. switch (kind) {
  35820. case BABYLON.VertexBuffer.PositionKind:
  35821. this.positions = data;
  35822. break;
  35823. case BABYLON.VertexBuffer.NormalKind:
  35824. this.normals = data;
  35825. break;
  35826. case BABYLON.VertexBuffer.TangentKind:
  35827. this.tangents = data;
  35828. break;
  35829. case BABYLON.VertexBuffer.UVKind:
  35830. this.uvs = data;
  35831. break;
  35832. case BABYLON.VertexBuffer.UV2Kind:
  35833. this.uvs2 = data;
  35834. break;
  35835. case BABYLON.VertexBuffer.UV3Kind:
  35836. this.uvs3 = data;
  35837. break;
  35838. case BABYLON.VertexBuffer.UV4Kind:
  35839. this.uvs4 = data;
  35840. break;
  35841. case BABYLON.VertexBuffer.UV5Kind:
  35842. this.uvs5 = data;
  35843. break;
  35844. case BABYLON.VertexBuffer.UV6Kind:
  35845. this.uvs6 = data;
  35846. break;
  35847. case BABYLON.VertexBuffer.ColorKind:
  35848. this.colors = data;
  35849. break;
  35850. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35851. this.matricesIndices = data;
  35852. break;
  35853. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35854. this.matricesWeights = data;
  35855. break;
  35856. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35857. this.matricesIndicesExtra = data;
  35858. break;
  35859. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35860. this.matricesWeightsExtra = data;
  35861. break;
  35862. }
  35863. };
  35864. /**
  35865. * Associates the vertexData to the passed Mesh.
  35866. * Sets it as updatable or not (default `false`)
  35867. * @param mesh the mesh the vertexData is applied to
  35868. * @param updatable when used and having the value true allows new data to update the vertexData
  35869. * @returns the VertexData
  35870. */
  35871. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35872. this._applyTo(mesh, updatable);
  35873. return this;
  35874. };
  35875. /**
  35876. * Associates the vertexData to the passed Geometry.
  35877. * Sets it as updatable or not (default `false`)
  35878. * @param geometry the geometry the vertexData is applied to
  35879. * @param updatable when used and having the value true allows new data to update the vertexData
  35880. * @returns VertexData
  35881. */
  35882. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35883. this._applyTo(geometry, updatable);
  35884. return this;
  35885. };
  35886. /**
  35887. * Updates the associated mesh
  35888. * @param mesh the mesh to be updated
  35889. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35890. * @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
  35891. * @returns VertexData
  35892. */
  35893. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35894. this._update(mesh);
  35895. return this;
  35896. };
  35897. /**
  35898. * Updates the associated geometry
  35899. * @param geometry the geometry to be updated
  35900. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35901. * @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
  35902. * @returns VertexData.
  35903. */
  35904. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35905. this._update(geometry);
  35906. return this;
  35907. };
  35908. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35909. if (updatable === void 0) { updatable = false; }
  35910. if (this.positions) {
  35911. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35912. }
  35913. if (this.normals) {
  35914. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35915. }
  35916. if (this.tangents) {
  35917. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35918. }
  35919. if (this.uvs) {
  35920. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35921. }
  35922. if (this.uvs2) {
  35923. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35924. }
  35925. if (this.uvs3) {
  35926. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35927. }
  35928. if (this.uvs4) {
  35929. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35930. }
  35931. if (this.uvs5) {
  35932. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35933. }
  35934. if (this.uvs6) {
  35935. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35936. }
  35937. if (this.colors) {
  35938. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35939. }
  35940. if (this.matricesIndices) {
  35941. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35942. }
  35943. if (this.matricesWeights) {
  35944. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35945. }
  35946. if (this.matricesIndicesExtra) {
  35947. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35948. }
  35949. if (this.matricesWeightsExtra) {
  35950. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35951. }
  35952. if (this.indices) {
  35953. meshOrGeometry.setIndices(this.indices, null, updatable);
  35954. }
  35955. else {
  35956. meshOrGeometry.setIndices([], null);
  35957. }
  35958. return this;
  35959. };
  35960. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35961. if (this.positions) {
  35962. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35963. }
  35964. if (this.normals) {
  35965. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35966. }
  35967. if (this.tangents) {
  35968. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35969. }
  35970. if (this.uvs) {
  35971. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35972. }
  35973. if (this.uvs2) {
  35974. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35975. }
  35976. if (this.uvs3) {
  35977. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35978. }
  35979. if (this.uvs4) {
  35980. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35981. }
  35982. if (this.uvs5) {
  35983. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35984. }
  35985. if (this.uvs6) {
  35986. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35987. }
  35988. if (this.colors) {
  35989. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35990. }
  35991. if (this.matricesIndices) {
  35992. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35993. }
  35994. if (this.matricesWeights) {
  35995. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35996. }
  35997. if (this.matricesIndicesExtra) {
  35998. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35999. }
  36000. if (this.matricesWeightsExtra) {
  36001. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36002. }
  36003. if (this.indices) {
  36004. meshOrGeometry.setIndices(this.indices, null);
  36005. }
  36006. return this;
  36007. };
  36008. /**
  36009. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36010. * @param matrix the transforming matrix
  36011. * @returns the VertexData
  36012. */
  36013. VertexData.prototype.transform = function (matrix) {
  36014. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36015. var transformed = BABYLON.Vector3.Zero();
  36016. var index;
  36017. if (this.positions) {
  36018. var position = BABYLON.Vector3.Zero();
  36019. for (index = 0; index < this.positions.length; index += 3) {
  36020. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36021. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36022. this.positions[index] = transformed.x;
  36023. this.positions[index + 1] = transformed.y;
  36024. this.positions[index + 2] = transformed.z;
  36025. }
  36026. }
  36027. if (this.normals) {
  36028. var normal = BABYLON.Vector3.Zero();
  36029. for (index = 0; index < this.normals.length; index += 3) {
  36030. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36031. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36032. this.normals[index] = transformed.x;
  36033. this.normals[index + 1] = transformed.y;
  36034. this.normals[index + 2] = transformed.z;
  36035. }
  36036. }
  36037. if (this.tangents) {
  36038. var tangent = BABYLON.Vector4.Zero();
  36039. var tangentTransformed = BABYLON.Vector4.Zero();
  36040. for (index = 0; index < this.tangents.length; index += 4) {
  36041. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36042. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36043. this.tangents[index] = tangentTransformed.x;
  36044. this.tangents[index + 1] = tangentTransformed.y;
  36045. this.tangents[index + 2] = tangentTransformed.z;
  36046. this.tangents[index + 3] = tangentTransformed.w;
  36047. }
  36048. }
  36049. if (flip && this.indices) {
  36050. for (index = 0; index < this.indices.length; index += 3) {
  36051. var tmp = this.indices[index + 1];
  36052. this.indices[index + 1] = this.indices[index + 2];
  36053. this.indices[index + 2] = tmp;
  36054. }
  36055. }
  36056. return this;
  36057. };
  36058. /**
  36059. * Merges the passed VertexData into the current one
  36060. * @param other the VertexData to be merged into the current one
  36061. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36062. * @returns the modified VertexData
  36063. */
  36064. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36065. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36066. this._validate();
  36067. other._validate();
  36068. if (!this.normals !== !other.normals ||
  36069. !this.tangents !== !other.tangents ||
  36070. !this.uvs !== !other.uvs ||
  36071. !this.uvs2 !== !other.uvs2 ||
  36072. !this.uvs3 !== !other.uvs3 ||
  36073. !this.uvs4 !== !other.uvs4 ||
  36074. !this.uvs5 !== !other.uvs5 ||
  36075. !this.uvs6 !== !other.uvs6 ||
  36076. !this.colors !== !other.colors ||
  36077. !this.matricesIndices !== !other.matricesIndices ||
  36078. !this.matricesWeights !== !other.matricesWeights ||
  36079. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36080. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36081. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36082. }
  36083. if (other.indices) {
  36084. if (!this.indices) {
  36085. this.indices = [];
  36086. }
  36087. var offset = this.positions ? this.positions.length / 3 : 0;
  36088. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36089. if (isSrcTypedArray) {
  36090. var len = this.indices.length + other.indices.length;
  36091. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36092. temp.set(this.indices);
  36093. var decal = this.indices.length;
  36094. for (var index = 0; index < other.indices.length; index++) {
  36095. temp[decal + index] = other.indices[index] + offset;
  36096. }
  36097. this.indices = temp;
  36098. }
  36099. else {
  36100. for (var index = 0; index < other.indices.length; index++) {
  36101. this.indices.push(other.indices[index] + offset);
  36102. }
  36103. }
  36104. }
  36105. this.positions = this._mergeElement(this.positions, other.positions);
  36106. this.normals = this._mergeElement(this.normals, other.normals);
  36107. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36108. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36109. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36110. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36111. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36112. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36113. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36114. this.colors = this._mergeElement(this.colors, other.colors);
  36115. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36116. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36117. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36118. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36119. return this;
  36120. };
  36121. VertexData.prototype._mergeElement = function (source, other) {
  36122. if (!source) {
  36123. return other;
  36124. }
  36125. if (!other) {
  36126. return source;
  36127. }
  36128. var len = other.length + source.length;
  36129. var isSrcTypedArray = source instanceof Float32Array;
  36130. var isOthTypedArray = other instanceof Float32Array;
  36131. // use non-loop method when the source is Float32Array
  36132. if (isSrcTypedArray) {
  36133. var ret32 = new Float32Array(len);
  36134. ret32.set(source);
  36135. ret32.set(other, source.length);
  36136. return ret32;
  36137. // source is number[], when other is also use concat
  36138. }
  36139. else if (!isOthTypedArray) {
  36140. return source.concat(other);
  36141. // source is a number[], but other is a Float32Array, loop required
  36142. }
  36143. else {
  36144. var ret = source.slice(0); // copy source to a separate array
  36145. for (var i = 0, len = other.length; i < len; i++) {
  36146. ret.push(other[i]);
  36147. }
  36148. return ret;
  36149. }
  36150. };
  36151. VertexData.prototype._validate = function () {
  36152. if (!this.positions) {
  36153. throw new Error("Positions are required");
  36154. }
  36155. var getElementCount = function (kind, values) {
  36156. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36157. if ((values.length % stride) !== 0) {
  36158. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36159. }
  36160. return values.length / stride;
  36161. };
  36162. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36163. var validateElementCount = function (kind, values) {
  36164. var elementCount = getElementCount(kind, values);
  36165. if (elementCount !== positionsElementCount) {
  36166. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36167. }
  36168. };
  36169. if (this.normals)
  36170. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36171. if (this.tangents)
  36172. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36173. if (this.uvs)
  36174. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36175. if (this.uvs2)
  36176. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36177. if (this.uvs3)
  36178. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36179. if (this.uvs4)
  36180. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36181. if (this.uvs5)
  36182. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36183. if (this.uvs6)
  36184. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36185. if (this.colors)
  36186. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36187. if (this.matricesIndices)
  36188. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36189. if (this.matricesWeights)
  36190. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36191. if (this.matricesIndicesExtra)
  36192. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36193. if (this.matricesWeightsExtra)
  36194. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36195. };
  36196. /**
  36197. * Serializes the VertexData
  36198. * @returns a serialized object
  36199. */
  36200. VertexData.prototype.serialize = function () {
  36201. var serializationObject = this.serialize();
  36202. if (this.positions) {
  36203. serializationObject.positions = this.positions;
  36204. }
  36205. if (this.normals) {
  36206. serializationObject.normals = this.normals;
  36207. }
  36208. if (this.tangents) {
  36209. serializationObject.tangents = this.tangents;
  36210. }
  36211. if (this.uvs) {
  36212. serializationObject.uvs = this.uvs;
  36213. }
  36214. if (this.uvs2) {
  36215. serializationObject.uvs2 = this.uvs2;
  36216. }
  36217. if (this.uvs3) {
  36218. serializationObject.uvs3 = this.uvs3;
  36219. }
  36220. if (this.uvs4) {
  36221. serializationObject.uvs4 = this.uvs4;
  36222. }
  36223. if (this.uvs5) {
  36224. serializationObject.uvs5 = this.uvs5;
  36225. }
  36226. if (this.uvs6) {
  36227. serializationObject.uvs6 = this.uvs6;
  36228. }
  36229. if (this.colors) {
  36230. serializationObject.colors = this.colors;
  36231. }
  36232. if (this.matricesIndices) {
  36233. serializationObject.matricesIndices = this.matricesIndices;
  36234. serializationObject.matricesIndices._isExpanded = true;
  36235. }
  36236. if (this.matricesWeights) {
  36237. serializationObject.matricesWeights = this.matricesWeights;
  36238. }
  36239. if (this.matricesIndicesExtra) {
  36240. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36241. serializationObject.matricesIndicesExtra._isExpanded = true;
  36242. }
  36243. if (this.matricesWeightsExtra) {
  36244. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36245. }
  36246. serializationObject.indices = this.indices;
  36247. return serializationObject;
  36248. };
  36249. // Statics
  36250. /**
  36251. * Extracts the vertexData from a mesh
  36252. * @param mesh the mesh from which to extract the VertexData
  36253. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36254. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36255. * @returns the object VertexData associated to the passed mesh
  36256. */
  36257. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36258. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36259. };
  36260. /**
  36261. * Extracts the vertexData from the geometry
  36262. * @param geometry the geometry from which to extract the VertexData
  36263. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36264. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36265. * @returns the object VertexData associated to the passed mesh
  36266. */
  36267. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36268. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36269. };
  36270. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36271. var result = new VertexData();
  36272. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36273. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36274. }
  36275. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36276. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36277. }
  36278. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36279. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36280. }
  36281. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36282. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36283. }
  36284. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36285. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36286. }
  36287. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36288. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36289. }
  36290. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36291. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36292. }
  36293. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36294. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36295. }
  36296. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36297. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36298. }
  36299. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36300. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36301. }
  36302. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36303. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36304. }
  36305. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36306. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36307. }
  36308. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36309. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36310. }
  36311. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36312. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36313. }
  36314. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36315. return result;
  36316. };
  36317. /**
  36318. * Creates the VertexData for a Ribbon
  36319. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36320. * * pathArray array of paths, each of which an array of successive Vector3
  36321. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36322. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36323. * * 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
  36324. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36325. * * 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)
  36326. * * 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)
  36327. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36328. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36329. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36330. * @returns the VertexData of the ribbon
  36331. */
  36332. VertexData.CreateRibbon = function (options) {
  36333. var pathArray = options.pathArray;
  36334. var closeArray = options.closeArray || false;
  36335. var closePath = options.closePath || false;
  36336. var invertUV = options.invertUV || false;
  36337. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36338. var offset = options.offset || defaultOffset;
  36339. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36340. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36341. var customUV = options.uvs;
  36342. var customColors = options.colors;
  36343. var positions = [];
  36344. var indices = [];
  36345. var normals = [];
  36346. var uvs = [];
  36347. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36348. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36349. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36350. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36351. var minlg; // minimal length among all paths from pathArray
  36352. var lg = []; // array of path lengths : nb of vertex per path
  36353. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36354. var p; // path iterator
  36355. var i; // point iterator
  36356. var j; // point iterator
  36357. // if single path in pathArray
  36358. if (pathArray.length < 2) {
  36359. var ar1 = [];
  36360. var ar2 = [];
  36361. for (i = 0; i < pathArray[0].length - offset; i++) {
  36362. ar1.push(pathArray[0][i]);
  36363. ar2.push(pathArray[0][i + offset]);
  36364. }
  36365. pathArray = [ar1, ar2];
  36366. }
  36367. // positions and horizontal distances (u)
  36368. var idc = 0;
  36369. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36370. var path;
  36371. var l;
  36372. minlg = pathArray[0].length;
  36373. var vectlg;
  36374. var dist;
  36375. for (p = 0; p < pathArray.length; p++) {
  36376. uTotalDistance[p] = 0;
  36377. us[p] = [0];
  36378. path = pathArray[p];
  36379. l = path.length;
  36380. minlg = (minlg < l) ? minlg : l;
  36381. j = 0;
  36382. while (j < l) {
  36383. positions.push(path[j].x, path[j].y, path[j].z);
  36384. if (j > 0) {
  36385. vectlg = path[j].subtract(path[j - 1]).length();
  36386. dist = vectlg + uTotalDistance[p];
  36387. us[p].push(dist);
  36388. uTotalDistance[p] = dist;
  36389. }
  36390. j++;
  36391. }
  36392. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36393. j--;
  36394. positions.push(path[0].x, path[0].y, path[0].z);
  36395. vectlg = path[j].subtract(path[0]).length();
  36396. dist = vectlg + uTotalDistance[p];
  36397. us[p].push(dist);
  36398. uTotalDistance[p] = dist;
  36399. }
  36400. lg[p] = l + closePathCorr;
  36401. idx[p] = idc;
  36402. idc += (l + closePathCorr);
  36403. }
  36404. // vertical distances (v)
  36405. var path1;
  36406. var path2;
  36407. var vertex1 = null;
  36408. var vertex2 = null;
  36409. for (i = 0; i < minlg + closePathCorr; i++) {
  36410. vTotalDistance[i] = 0;
  36411. vs[i] = [0];
  36412. for (p = 0; p < pathArray.length - 1; p++) {
  36413. path1 = pathArray[p];
  36414. path2 = pathArray[p + 1];
  36415. if (i === minlg) { // closePath
  36416. vertex1 = path1[0];
  36417. vertex2 = path2[0];
  36418. }
  36419. else {
  36420. vertex1 = path1[i];
  36421. vertex2 = path2[i];
  36422. }
  36423. vectlg = vertex2.subtract(vertex1).length();
  36424. dist = vectlg + vTotalDistance[i];
  36425. vs[i].push(dist);
  36426. vTotalDistance[i] = dist;
  36427. }
  36428. if (closeArray && vertex2 && vertex1) {
  36429. path1 = pathArray[p];
  36430. path2 = pathArray[0];
  36431. if (i === minlg) { // closePath
  36432. vertex2 = path2[0];
  36433. }
  36434. vectlg = vertex2.subtract(vertex1).length();
  36435. dist = vectlg + vTotalDistance[i];
  36436. vTotalDistance[i] = dist;
  36437. }
  36438. }
  36439. // uvs
  36440. var u;
  36441. var v;
  36442. if (customUV) {
  36443. for (p = 0; p < customUV.length; p++) {
  36444. uvs.push(customUV[p].x, customUV[p].y);
  36445. }
  36446. }
  36447. else {
  36448. for (p = 0; p < pathArray.length; p++) {
  36449. for (i = 0; i < minlg + closePathCorr; i++) {
  36450. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36451. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36452. if (invertUV) {
  36453. uvs.push(v, u);
  36454. }
  36455. else {
  36456. uvs.push(u, v);
  36457. }
  36458. }
  36459. }
  36460. }
  36461. // indices
  36462. p = 0; // path index
  36463. var pi = 0; // positions array index
  36464. var l1 = lg[p] - 1; // path1 length
  36465. var l2 = lg[p + 1] - 1; // path2 length
  36466. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36467. var shft = idx[1] - idx[0]; // shift
  36468. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36469. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36470. // 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
  36471. indices.push(pi, pi + shft, pi + 1);
  36472. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36473. pi += 1;
  36474. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36475. p++;
  36476. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36477. shft = idx[0] - idx[p];
  36478. l1 = lg[p] - 1;
  36479. l2 = lg[0] - 1;
  36480. }
  36481. else {
  36482. shft = idx[p + 1] - idx[p];
  36483. l1 = lg[p] - 1;
  36484. l2 = lg[p + 1] - 1;
  36485. }
  36486. pi = idx[p];
  36487. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36488. }
  36489. }
  36490. // normals
  36491. VertexData.ComputeNormals(positions, indices, normals);
  36492. if (closePath) { // update both the first and last vertex normals to their average value
  36493. var indexFirst = 0;
  36494. var indexLast = 0;
  36495. for (p = 0; p < pathArray.length; p++) {
  36496. indexFirst = idx[p] * 3;
  36497. if (p + 1 < pathArray.length) {
  36498. indexLast = (idx[p + 1] - 1) * 3;
  36499. }
  36500. else {
  36501. indexLast = normals.length - 3;
  36502. }
  36503. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36504. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36505. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36506. normals[indexLast] = normals[indexFirst];
  36507. normals[indexLast + 1] = normals[indexFirst + 1];
  36508. normals[indexLast + 2] = normals[indexFirst + 2];
  36509. }
  36510. }
  36511. // sides
  36512. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36513. // Colors
  36514. var colors = null;
  36515. if (customColors) {
  36516. colors = new Float32Array(customColors.length * 4);
  36517. for (var c = 0; c < customColors.length; c++) {
  36518. colors[c * 4] = customColors[c].r;
  36519. colors[c * 4 + 1] = customColors[c].g;
  36520. colors[c * 4 + 2] = customColors[c].b;
  36521. colors[c * 4 + 3] = customColors[c].a;
  36522. }
  36523. }
  36524. // Result
  36525. var vertexData = new VertexData();
  36526. var positions32 = new Float32Array(positions);
  36527. var normals32 = new Float32Array(normals);
  36528. var uvs32 = new Float32Array(uvs);
  36529. vertexData.indices = indices;
  36530. vertexData.positions = positions32;
  36531. vertexData.normals = normals32;
  36532. vertexData.uvs = uvs32;
  36533. if (colors) {
  36534. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36535. }
  36536. if (closePath) {
  36537. vertexData._idx = idx;
  36538. }
  36539. return vertexData;
  36540. };
  36541. /**
  36542. * Creates the VertexData for a box
  36543. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36544. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36545. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36546. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36547. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36548. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36549. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36550. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36551. * * 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)
  36552. * * 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)
  36553. * @returns the VertexData of the box
  36554. */
  36555. VertexData.CreateBox = function (options) {
  36556. var normalsSource = [
  36557. new BABYLON.Vector3(0, 0, 1),
  36558. new BABYLON.Vector3(0, 0, -1),
  36559. new BABYLON.Vector3(1, 0, 0),
  36560. new BABYLON.Vector3(-1, 0, 0),
  36561. new BABYLON.Vector3(0, 1, 0),
  36562. new BABYLON.Vector3(0, -1, 0)
  36563. ];
  36564. var indices = [];
  36565. var positions = [];
  36566. var normals = [];
  36567. var uvs = [];
  36568. var width = options.width || options.size || 1;
  36569. var height = options.height || options.size || 1;
  36570. var depth = options.depth || options.size || 1;
  36571. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36572. var faceUV = options.faceUV || new Array(6);
  36573. var faceColors = options.faceColors;
  36574. var colors = [];
  36575. // default face colors and UV if undefined
  36576. for (var f = 0; f < 6; f++) {
  36577. if (faceUV[f] === undefined) {
  36578. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36579. }
  36580. if (faceColors && faceColors[f] === undefined) {
  36581. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36582. }
  36583. }
  36584. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36585. // Create each face in turn.
  36586. for (var index = 0; index < normalsSource.length; index++) {
  36587. var normal = normalsSource[index];
  36588. // Get two vectors perpendicular to the face normal and to each other.
  36589. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36590. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36591. // Six indices (two triangles) per face.
  36592. var verticesLength = positions.length / 3;
  36593. indices.push(verticesLength);
  36594. indices.push(verticesLength + 1);
  36595. indices.push(verticesLength + 2);
  36596. indices.push(verticesLength);
  36597. indices.push(verticesLength + 2);
  36598. indices.push(verticesLength + 3);
  36599. // Four vertices per face.
  36600. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36601. positions.push(vertex.x, vertex.y, vertex.z);
  36602. normals.push(normal.x, normal.y, normal.z);
  36603. uvs.push(faceUV[index].z, faceUV[index].w);
  36604. if (faceColors) {
  36605. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36606. }
  36607. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36608. positions.push(vertex.x, vertex.y, vertex.z);
  36609. normals.push(normal.x, normal.y, normal.z);
  36610. uvs.push(faceUV[index].x, faceUV[index].w);
  36611. if (faceColors) {
  36612. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36613. }
  36614. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36615. positions.push(vertex.x, vertex.y, vertex.z);
  36616. normals.push(normal.x, normal.y, normal.z);
  36617. uvs.push(faceUV[index].x, faceUV[index].y);
  36618. if (faceColors) {
  36619. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36620. }
  36621. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36622. positions.push(vertex.x, vertex.y, vertex.z);
  36623. normals.push(normal.x, normal.y, normal.z);
  36624. uvs.push(faceUV[index].z, faceUV[index].y);
  36625. if (faceColors) {
  36626. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36627. }
  36628. }
  36629. // sides
  36630. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36631. // Result
  36632. var vertexData = new VertexData();
  36633. vertexData.indices = indices;
  36634. vertexData.positions = positions;
  36635. vertexData.normals = normals;
  36636. vertexData.uvs = uvs;
  36637. if (faceColors) {
  36638. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36639. vertexData.colors = totalColors;
  36640. }
  36641. return vertexData;
  36642. };
  36643. /**
  36644. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36645. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36646. * * segments sets the number of horizontal strips optional, default 32
  36647. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36648. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36649. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36650. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36651. * * 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
  36652. * * 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
  36653. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36654. * * 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)
  36655. * * 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)
  36656. * @returns the VertexData of the ellipsoid
  36657. */
  36658. VertexData.CreateSphere = function (options) {
  36659. var segments = options.segments || 32;
  36660. var diameterX = options.diameterX || options.diameter || 1;
  36661. var diameterY = options.diameterY || options.diameter || 1;
  36662. var diameterZ = options.diameterZ || options.diameter || 1;
  36663. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36664. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36665. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36666. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36667. var totalZRotationSteps = 2 + segments;
  36668. var totalYRotationSteps = 2 * totalZRotationSteps;
  36669. var indices = [];
  36670. var positions = [];
  36671. var normals = [];
  36672. var uvs = [];
  36673. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36674. var normalizedZ = zRotationStep / totalZRotationSteps;
  36675. var angleZ = normalizedZ * Math.PI * slice;
  36676. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36677. var normalizedY = yRotationStep / totalYRotationSteps;
  36678. var angleY = normalizedY * Math.PI * 2 * arc;
  36679. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36680. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36681. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36682. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36683. var vertex = complete.multiply(radius);
  36684. var normal = complete.divide(radius).normalize();
  36685. positions.push(vertex.x, vertex.y, vertex.z);
  36686. normals.push(normal.x, normal.y, normal.z);
  36687. uvs.push(normalizedY, normalizedZ);
  36688. }
  36689. if (zRotationStep > 0) {
  36690. var verticesCount = positions.length / 3;
  36691. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36692. indices.push((firstIndex));
  36693. indices.push((firstIndex + 1));
  36694. indices.push(firstIndex + totalYRotationSteps + 1);
  36695. indices.push((firstIndex + totalYRotationSteps + 1));
  36696. indices.push((firstIndex + 1));
  36697. indices.push((firstIndex + totalYRotationSteps + 2));
  36698. }
  36699. }
  36700. }
  36701. // Sides
  36702. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36703. // Result
  36704. var vertexData = new VertexData();
  36705. vertexData.indices = indices;
  36706. vertexData.positions = positions;
  36707. vertexData.normals = normals;
  36708. vertexData.uvs = uvs;
  36709. return vertexData;
  36710. };
  36711. /**
  36712. * Creates the VertexData for a cylinder, cone or prism
  36713. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36714. * * height sets the height (y direction) of the cylinder, optional, default 2
  36715. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36716. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36717. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36718. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36719. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36720. * * 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
  36721. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36722. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36723. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36724. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36725. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36726. * * 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)
  36727. * * 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)
  36728. * @returns the VertexData of the cylinder, cone or prism
  36729. */
  36730. VertexData.CreateCylinder = function (options) {
  36731. var height = options.height || 2;
  36732. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36733. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36734. var tessellation = options.tessellation || 24;
  36735. var subdivisions = options.subdivisions || 1;
  36736. var hasRings = options.hasRings ? true : false;
  36737. var enclose = options.enclose ? true : false;
  36738. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36739. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36740. var faceUV = options.faceUV || new Array(3);
  36741. var faceColors = options.faceColors;
  36742. // default face colors and UV if undefined
  36743. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36744. var ringNb = (hasRings) ? subdivisions : 1;
  36745. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36746. var f;
  36747. for (f = 0; f < surfaceNb; f++) {
  36748. if (faceColors && faceColors[f] === undefined) {
  36749. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36750. }
  36751. }
  36752. for (f = 0; f < surfaceNb; f++) {
  36753. if (faceUV && faceUV[f] === undefined) {
  36754. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36755. }
  36756. }
  36757. var indices = new Array();
  36758. var positions = new Array();
  36759. var normals = new Array();
  36760. var uvs = new Array();
  36761. var colors = new Array();
  36762. var angle_step = Math.PI * 2 * arc / tessellation;
  36763. var angle;
  36764. var h;
  36765. var radius;
  36766. var tan = (diameterBottom - diameterTop) / 2 / height;
  36767. var ringVertex = BABYLON.Vector3.Zero();
  36768. var ringNormal = BABYLON.Vector3.Zero();
  36769. var ringFirstVertex = BABYLON.Vector3.Zero();
  36770. var ringFirstNormal = BABYLON.Vector3.Zero();
  36771. var quadNormal = BABYLON.Vector3.Zero();
  36772. var Y = BABYLON.Axis.Y;
  36773. // positions, normals, uvs
  36774. var i;
  36775. var j;
  36776. var r;
  36777. var ringIdx = 1;
  36778. var s = 1; // surface index
  36779. var cs = 0;
  36780. var v = 0;
  36781. for (i = 0; i <= subdivisions; i++) {
  36782. h = i / subdivisions;
  36783. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36784. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36785. for (r = 0; r < ringIdx; r++) {
  36786. if (hasRings) {
  36787. s += r;
  36788. }
  36789. if (enclose) {
  36790. s += 2 * r;
  36791. }
  36792. for (j = 0; j <= tessellation; j++) {
  36793. angle = j * angle_step;
  36794. // position
  36795. ringVertex.x = Math.cos(-angle) * radius;
  36796. ringVertex.y = -height / 2 + h * height;
  36797. ringVertex.z = Math.sin(-angle) * radius;
  36798. // normal
  36799. if (diameterTop === 0 && i === subdivisions) {
  36800. // if no top cap, reuse former normals
  36801. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36802. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36803. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36804. }
  36805. else {
  36806. ringNormal.x = ringVertex.x;
  36807. ringNormal.z = ringVertex.z;
  36808. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36809. ringNormal.normalize();
  36810. }
  36811. // keep first ring vertex values for enclose
  36812. if (j === 0) {
  36813. ringFirstVertex.copyFrom(ringVertex);
  36814. ringFirstNormal.copyFrom(ringNormal);
  36815. }
  36816. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36817. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36818. if (hasRings) {
  36819. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36820. }
  36821. else {
  36822. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36823. }
  36824. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36825. if (faceColors) {
  36826. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36827. }
  36828. }
  36829. // if enclose, add four vertices and their dedicated normals
  36830. if (arc !== 1 && enclose) {
  36831. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36832. positions.push(0, ringVertex.y, 0);
  36833. positions.push(0, ringVertex.y, 0);
  36834. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36835. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36836. quadNormal.normalize();
  36837. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36838. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36839. quadNormal.normalize();
  36840. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36841. if (hasRings) {
  36842. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36843. }
  36844. else {
  36845. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36846. }
  36847. uvs.push(faceUV[s + 1].x, v);
  36848. uvs.push(faceUV[s + 1].z, v);
  36849. if (hasRings) {
  36850. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36851. }
  36852. else {
  36853. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36854. }
  36855. uvs.push(faceUV[s + 2].x, v);
  36856. uvs.push(faceUV[s + 2].z, v);
  36857. if (faceColors) {
  36858. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36859. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36860. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36861. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36862. }
  36863. }
  36864. if (cs !== s) {
  36865. cs = s;
  36866. }
  36867. }
  36868. }
  36869. // indices
  36870. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36871. var s;
  36872. i = 0;
  36873. for (s = 0; s < subdivisions; s++) {
  36874. var i0 = 0;
  36875. var i1 = 0;
  36876. var i2 = 0;
  36877. var i3 = 0;
  36878. for (j = 0; j < tessellation; j++) {
  36879. i0 = i * (e + 1) + j;
  36880. i1 = (i + 1) * (e + 1) + j;
  36881. i2 = i * (e + 1) + (j + 1);
  36882. i3 = (i + 1) * (e + 1) + (j + 1);
  36883. indices.push(i0, i1, i2);
  36884. indices.push(i3, i2, i1);
  36885. }
  36886. if (arc !== 1 && enclose) { // if enclose, add two quads
  36887. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36888. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36889. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36890. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36891. }
  36892. i = (hasRings) ? (i + 2) : (i + 1);
  36893. }
  36894. // Caps
  36895. var createCylinderCap = function (isTop) {
  36896. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36897. if (radius === 0) {
  36898. return;
  36899. }
  36900. // Cap positions, normals & uvs
  36901. var angle;
  36902. var circleVector;
  36903. var i;
  36904. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36905. var c = null;
  36906. if (faceColors) {
  36907. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36908. }
  36909. // cap center
  36910. var vbase = positions.length / 3;
  36911. var offset = isTop ? height / 2 : -height / 2;
  36912. var center = new BABYLON.Vector3(0, offset, 0);
  36913. positions.push(center.x, center.y, center.z);
  36914. normals.push(0, isTop ? 1 : -1, 0);
  36915. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36916. if (c) {
  36917. colors.push(c.r, c.g, c.b, c.a);
  36918. }
  36919. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36920. for (i = 0; i <= tessellation; i++) {
  36921. angle = Math.PI * 2 * i * arc / tessellation;
  36922. var cos = Math.cos(-angle);
  36923. var sin = Math.sin(-angle);
  36924. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36925. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36926. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36927. normals.push(0, isTop ? 1 : -1, 0);
  36928. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36929. if (c) {
  36930. colors.push(c.r, c.g, c.b, c.a);
  36931. }
  36932. }
  36933. // Cap indices
  36934. for (i = 0; i < tessellation; i++) {
  36935. if (!isTop) {
  36936. indices.push(vbase);
  36937. indices.push(vbase + (i + 1));
  36938. indices.push(vbase + (i + 2));
  36939. }
  36940. else {
  36941. indices.push(vbase);
  36942. indices.push(vbase + (i + 2));
  36943. indices.push(vbase + (i + 1));
  36944. }
  36945. }
  36946. };
  36947. // add caps to geometry
  36948. createCylinderCap(false);
  36949. createCylinderCap(true);
  36950. // Sides
  36951. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36952. var vertexData = new VertexData();
  36953. vertexData.indices = indices;
  36954. vertexData.positions = positions;
  36955. vertexData.normals = normals;
  36956. vertexData.uvs = uvs;
  36957. if (faceColors) {
  36958. vertexData.colors = colors;
  36959. }
  36960. return vertexData;
  36961. };
  36962. /**
  36963. * Creates the VertexData for a torus
  36964. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36965. * * diameter the diameter of the torus, optional default 1
  36966. * * thickness the diameter of the tube forming the torus, optional default 0.5
  36967. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36968. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36969. * * 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)
  36970. * * 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)
  36971. * @returns the VertexData of the torus
  36972. */
  36973. VertexData.CreateTorus = function (options) {
  36974. var indices = [];
  36975. var positions = [];
  36976. var normals = [];
  36977. var uvs = [];
  36978. var diameter = options.diameter || 1;
  36979. var thickness = options.thickness || 0.5;
  36980. var tessellation = options.tessellation || 16;
  36981. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36982. var stride = tessellation + 1;
  36983. for (var i = 0; i <= tessellation; i++) {
  36984. var u = i / tessellation;
  36985. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36986. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36987. for (var j = 0; j <= tessellation; j++) {
  36988. var v = 1 - j / tessellation;
  36989. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36990. var dx = Math.cos(innerAngle);
  36991. var dy = Math.sin(innerAngle);
  36992. // Create a vertex.
  36993. var normal = new BABYLON.Vector3(dx, dy, 0);
  36994. var position = normal.scale(thickness / 2);
  36995. var textureCoordinate = new BABYLON.Vector2(u, v);
  36996. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36997. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36998. positions.push(position.x, position.y, position.z);
  36999. normals.push(normal.x, normal.y, normal.z);
  37000. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37001. // And create indices for two triangles.
  37002. var nextI = (i + 1) % stride;
  37003. var nextJ = (j + 1) % stride;
  37004. indices.push(i * stride + j);
  37005. indices.push(i * stride + nextJ);
  37006. indices.push(nextI * stride + j);
  37007. indices.push(i * stride + nextJ);
  37008. indices.push(nextI * stride + nextJ);
  37009. indices.push(nextI * stride + j);
  37010. }
  37011. }
  37012. // Sides
  37013. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37014. // Result
  37015. var vertexData = new VertexData();
  37016. vertexData.indices = indices;
  37017. vertexData.positions = positions;
  37018. vertexData.normals = normals;
  37019. vertexData.uvs = uvs;
  37020. return vertexData;
  37021. };
  37022. /**
  37023. * Creates the VertexData of the LineSystem
  37024. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37025. * - lines an array of lines, each line being an array of successive Vector3
  37026. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37027. * @returns the VertexData of the LineSystem
  37028. */
  37029. VertexData.CreateLineSystem = function (options) {
  37030. var indices = [];
  37031. var positions = [];
  37032. var lines = options.lines;
  37033. var colors = options.colors;
  37034. var vertexColors = [];
  37035. var idx = 0;
  37036. for (var l = 0; l < lines.length; l++) {
  37037. var points = lines[l];
  37038. for (var index = 0; index < points.length; index++) {
  37039. positions.push(points[index].x, points[index].y, points[index].z);
  37040. if (colors) {
  37041. var color = colors[l];
  37042. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37043. }
  37044. if (index > 0) {
  37045. indices.push(idx - 1);
  37046. indices.push(idx);
  37047. }
  37048. idx++;
  37049. }
  37050. }
  37051. var vertexData = new VertexData();
  37052. vertexData.indices = indices;
  37053. vertexData.positions = positions;
  37054. if (colors) {
  37055. vertexData.colors = vertexColors;
  37056. }
  37057. return vertexData;
  37058. };
  37059. /**
  37060. * Create the VertexData for a DashedLines
  37061. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37062. * - points an array successive Vector3
  37063. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37064. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37065. * - dashNb the intended total number of dashes, optional, default 200
  37066. * @returns the VertexData for the DashedLines
  37067. */
  37068. VertexData.CreateDashedLines = function (options) {
  37069. var dashSize = options.dashSize || 3;
  37070. var gapSize = options.gapSize || 1;
  37071. var dashNb = options.dashNb || 200;
  37072. var points = options.points;
  37073. var positions = new Array();
  37074. var indices = new Array();
  37075. var curvect = BABYLON.Vector3.Zero();
  37076. var lg = 0;
  37077. var nb = 0;
  37078. var shft = 0;
  37079. var dashshft = 0;
  37080. var curshft = 0;
  37081. var idx = 0;
  37082. var i = 0;
  37083. for (i = 0; i < points.length - 1; i++) {
  37084. points[i + 1].subtractToRef(points[i], curvect);
  37085. lg += curvect.length();
  37086. }
  37087. shft = lg / dashNb;
  37088. dashshft = dashSize * shft / (dashSize + gapSize);
  37089. for (i = 0; i < points.length - 1; i++) {
  37090. points[i + 1].subtractToRef(points[i], curvect);
  37091. nb = Math.floor(curvect.length() / shft);
  37092. curvect.normalize();
  37093. for (var j = 0; j < nb; j++) {
  37094. curshft = shft * j;
  37095. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37096. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37097. indices.push(idx, idx + 1);
  37098. idx += 2;
  37099. }
  37100. }
  37101. // Result
  37102. var vertexData = new VertexData();
  37103. vertexData.positions = positions;
  37104. vertexData.indices = indices;
  37105. return vertexData;
  37106. };
  37107. /**
  37108. * Creates the VertexData for a Ground
  37109. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37110. * - width the width (x direction) of the ground, optional, default 1
  37111. * - height the height (z direction) of the ground, optional, default 1
  37112. * - subdivisions the number of subdivisions per side, optional, default 1
  37113. * @returns the VertexData of the Ground
  37114. */
  37115. VertexData.CreateGround = function (options) {
  37116. var indices = [];
  37117. var positions = [];
  37118. var normals = [];
  37119. var uvs = [];
  37120. var row, col;
  37121. var width = options.width || 1;
  37122. var height = options.height || 1;
  37123. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37124. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37125. for (row = 0; row <= subdivisionsY; row++) {
  37126. for (col = 0; col <= subdivisionsX; col++) {
  37127. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37128. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37129. positions.push(position.x, position.y, position.z);
  37130. normals.push(normal.x, normal.y, normal.z);
  37131. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37132. }
  37133. }
  37134. for (row = 0; row < subdivisionsY; row++) {
  37135. for (col = 0; col < subdivisionsX; col++) {
  37136. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37137. indices.push(col + 1 + row * (subdivisionsX + 1));
  37138. indices.push(col + row * (subdivisionsX + 1));
  37139. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37140. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37141. indices.push(col + row * (subdivisionsX + 1));
  37142. }
  37143. }
  37144. // Result
  37145. var vertexData = new VertexData();
  37146. vertexData.indices = indices;
  37147. vertexData.positions = positions;
  37148. vertexData.normals = normals;
  37149. vertexData.uvs = uvs;
  37150. return vertexData;
  37151. };
  37152. /**
  37153. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37154. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37155. * * xmin the ground minimum X coordinate, optional, default -1
  37156. * * zmin the ground minimum Z coordinate, optional, default -1
  37157. * * xmax the ground maximum X coordinate, optional, default 1
  37158. * * zmax the ground maximum Z coordinate, optional, default 1
  37159. * * 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}
  37160. * * 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}
  37161. * @returns the VertexData of the TiledGround
  37162. */
  37163. VertexData.CreateTiledGround = function (options) {
  37164. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37165. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37166. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37167. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37168. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37169. var precision = options.precision || { w: 1, h: 1 };
  37170. var indices = new Array();
  37171. var positions = new Array();
  37172. var normals = new Array();
  37173. var uvs = new Array();
  37174. var row, col, tileRow, tileCol;
  37175. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37176. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37177. precision.w = (precision.w < 1) ? 1 : precision.w;
  37178. precision.h = (precision.h < 1) ? 1 : precision.h;
  37179. var tileSize = {
  37180. 'w': (xmax - xmin) / subdivisions.w,
  37181. 'h': (zmax - zmin) / subdivisions.h
  37182. };
  37183. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37184. // Indices
  37185. var base = positions.length / 3;
  37186. var rowLength = precision.w + 1;
  37187. for (row = 0; row < precision.h; row++) {
  37188. for (col = 0; col < precision.w; col++) {
  37189. var square = [
  37190. base + col + row * rowLength,
  37191. base + (col + 1) + row * rowLength,
  37192. base + (col + 1) + (row + 1) * rowLength,
  37193. base + col + (row + 1) * rowLength
  37194. ];
  37195. indices.push(square[1]);
  37196. indices.push(square[2]);
  37197. indices.push(square[3]);
  37198. indices.push(square[0]);
  37199. indices.push(square[1]);
  37200. indices.push(square[3]);
  37201. }
  37202. }
  37203. // Position, normals and uvs
  37204. var position = BABYLON.Vector3.Zero();
  37205. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37206. for (row = 0; row <= precision.h; row++) {
  37207. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37208. for (col = 0; col <= precision.w; col++) {
  37209. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37210. position.y = 0;
  37211. positions.push(position.x, position.y, position.z);
  37212. normals.push(normal.x, normal.y, normal.z);
  37213. uvs.push(col / precision.w, row / precision.h);
  37214. }
  37215. }
  37216. }
  37217. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37218. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37219. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37220. }
  37221. }
  37222. // Result
  37223. var vertexData = new VertexData();
  37224. vertexData.indices = indices;
  37225. vertexData.positions = positions;
  37226. vertexData.normals = normals;
  37227. vertexData.uvs = uvs;
  37228. return vertexData;
  37229. };
  37230. /**
  37231. * Creates the VertexData of the Ground designed from a heightmap
  37232. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37233. * * width the width (x direction) of the ground
  37234. * * height the height (z direction) of the ground
  37235. * * subdivisions the number of subdivisions per side
  37236. * * minHeight the minimum altitude on the ground, optional, default 0
  37237. * * maxHeight the maximum altitude on the ground, optional default 1
  37238. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37239. * * buffer the array holding the image color data
  37240. * * bufferWidth the width of image
  37241. * * bufferHeight the height of image
  37242. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37243. * @returns the VertexData of the Ground designed from a heightmap
  37244. */
  37245. VertexData.CreateGroundFromHeightMap = function (options) {
  37246. var indices = [];
  37247. var positions = [];
  37248. var normals = [];
  37249. var uvs = [];
  37250. var row, col;
  37251. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37252. var alphaFilter = options.alphaFilter || 0.0;
  37253. // Vertices
  37254. for (row = 0; row <= options.subdivisions; row++) {
  37255. for (col = 0; col <= options.subdivisions; col++) {
  37256. 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));
  37257. // Compute height
  37258. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37259. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37260. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37261. var r = options.buffer[pos] / 255.0;
  37262. var g = options.buffer[pos + 1] / 255.0;
  37263. var b = options.buffer[pos + 2] / 255.0;
  37264. var a = options.buffer[pos + 3] / 255.0;
  37265. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37266. // If our alpha channel is not within our filter then we will assign a 'special' height
  37267. // Then when building the indices, we will ignore any vertex that is using the special height
  37268. if (a >= alphaFilter)
  37269. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37270. else {
  37271. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  37272. }
  37273. // Add vertex
  37274. positions.push(position.x, position.y, position.z);
  37275. normals.push(0, 0, 0);
  37276. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37277. }
  37278. }
  37279. // Indices
  37280. for (row = 0; row < options.subdivisions; row++) {
  37281. for (col = 0; col < options.subdivisions; col++) {
  37282. // Calculate Indices
  37283. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  37284. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  37285. var idx3 = (col + row * (options.subdivisions + 1));
  37286. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  37287. // Check that all indices are visible (based on our special height)
  37288. // Only display the vertex if all Indices are visible
  37289. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  37290. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  37291. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  37292. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  37293. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  37294. indices.push(idx1);
  37295. indices.push(idx2);
  37296. indices.push(idx3);
  37297. }
  37298. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  37299. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  37300. indices.push(idx4);
  37301. indices.push(idx1);
  37302. indices.push(idx3);
  37303. }
  37304. }
  37305. }
  37306. // Normals
  37307. VertexData.ComputeNormals(positions, indices, normals);
  37308. // Result
  37309. var vertexData = new VertexData();
  37310. vertexData.indices = indices;
  37311. vertexData.positions = positions;
  37312. vertexData.normals = normals;
  37313. vertexData.uvs = uvs;
  37314. return vertexData;
  37315. };
  37316. /**
  37317. * Creates the VertexData for a Plane
  37318. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37319. * * size sets the width and height of the plane to the value of size, optional default 1
  37320. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37321. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37322. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37323. * * 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)
  37324. * * 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)
  37325. * @returns the VertexData of the box
  37326. */
  37327. VertexData.CreatePlane = function (options) {
  37328. var indices = [];
  37329. var positions = [];
  37330. var normals = [];
  37331. var uvs = [];
  37332. var width = options.width || options.size || 1;
  37333. var height = options.height || options.size || 1;
  37334. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37335. // Vertices
  37336. var halfWidth = width / 2.0;
  37337. var halfHeight = height / 2.0;
  37338. positions.push(-halfWidth, -halfHeight, 0);
  37339. normals.push(0, 0, -1.0);
  37340. uvs.push(0.0, 0.0);
  37341. positions.push(halfWidth, -halfHeight, 0);
  37342. normals.push(0, 0, -1.0);
  37343. uvs.push(1.0, 0.0);
  37344. positions.push(halfWidth, halfHeight, 0);
  37345. normals.push(0, 0, -1.0);
  37346. uvs.push(1.0, 1.0);
  37347. positions.push(-halfWidth, halfHeight, 0);
  37348. normals.push(0, 0, -1.0);
  37349. uvs.push(0.0, 1.0);
  37350. // Indices
  37351. indices.push(0);
  37352. indices.push(1);
  37353. indices.push(2);
  37354. indices.push(0);
  37355. indices.push(2);
  37356. indices.push(3);
  37357. // Sides
  37358. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37359. // Result
  37360. var vertexData = new VertexData();
  37361. vertexData.indices = indices;
  37362. vertexData.positions = positions;
  37363. vertexData.normals = normals;
  37364. vertexData.uvs = uvs;
  37365. return vertexData;
  37366. };
  37367. /**
  37368. * Creates the VertexData of the Disc or regular Polygon
  37369. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37370. * * radius the radius of the disc, optional default 0.5
  37371. * * tessellation the number of polygon sides, optional, default 64
  37372. * * 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
  37373. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37374. * * 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)
  37375. * * 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)
  37376. * @returns the VertexData of the box
  37377. */
  37378. VertexData.CreateDisc = function (options) {
  37379. var positions = new Array();
  37380. var indices = new Array();
  37381. var normals = new Array();
  37382. var uvs = new Array();
  37383. var radius = options.radius || 0.5;
  37384. var tessellation = options.tessellation || 64;
  37385. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37386. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37387. // positions and uvs
  37388. positions.push(0, 0, 0); // disc center first
  37389. uvs.push(0.5, 0.5);
  37390. var theta = Math.PI * 2 * arc;
  37391. var step = theta / tessellation;
  37392. for (var a = 0; a < theta; a += step) {
  37393. var x = Math.cos(a);
  37394. var y = Math.sin(a);
  37395. var u = (x + 1) / 2;
  37396. var v = (1 - y) / 2;
  37397. positions.push(radius * x, radius * y, 0);
  37398. uvs.push(u, v);
  37399. }
  37400. if (arc === 1) {
  37401. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37402. uvs.push(uvs[2], uvs[3]);
  37403. }
  37404. //indices
  37405. var vertexNb = positions.length / 3;
  37406. for (var i = 1; i < vertexNb - 1; i++) {
  37407. indices.push(i + 1, 0, i);
  37408. }
  37409. // result
  37410. VertexData.ComputeNormals(positions, indices, normals);
  37411. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37412. var vertexData = new VertexData();
  37413. vertexData.indices = indices;
  37414. vertexData.positions = positions;
  37415. vertexData.normals = normals;
  37416. vertexData.uvs = uvs;
  37417. return vertexData;
  37418. };
  37419. /**
  37420. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37421. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37422. * @param polygon a mesh built from polygonTriangulation.build()
  37423. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37424. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37425. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37426. * @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)
  37427. * @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)
  37428. * @returns the VertexData of the Polygon
  37429. */
  37430. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37431. var faceUV = fUV || new Array(3);
  37432. var faceColors = fColors;
  37433. var colors = [];
  37434. // default face colors and UV if undefined
  37435. for (var f = 0; f < 3; f++) {
  37436. if (faceUV[f] === undefined) {
  37437. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37438. }
  37439. if (faceColors && faceColors[f] === undefined) {
  37440. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37441. }
  37442. }
  37443. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37444. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37445. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37446. var indices = polygon.getIndices();
  37447. // set face colours and textures
  37448. var idx = 0;
  37449. var face = 0;
  37450. for (var index = 0; index < normals.length; index += 3) {
  37451. //Edge Face no. 1
  37452. if (Math.abs(normals[index + 1]) < 0.001) {
  37453. face = 1;
  37454. }
  37455. //Top Face no. 0
  37456. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37457. face = 0;
  37458. }
  37459. //Bottom Face no. 2
  37460. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37461. face = 2;
  37462. }
  37463. idx = index / 3;
  37464. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37465. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37466. if (faceColors) {
  37467. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37468. }
  37469. }
  37470. // sides
  37471. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37472. // Result
  37473. var vertexData = new VertexData();
  37474. vertexData.indices = indices;
  37475. vertexData.positions = positions;
  37476. vertexData.normals = normals;
  37477. vertexData.uvs = uvs;
  37478. if (faceColors) {
  37479. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37480. vertexData.colors = totalColors;
  37481. }
  37482. return vertexData;
  37483. };
  37484. /**
  37485. * Creates the VertexData of the IcoSphere
  37486. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37487. * * radius the radius of the IcoSphere, optional default 1
  37488. * * radiusX allows stretching in the x direction, optional, default radius
  37489. * * radiusY allows stretching in the y direction, optional, default radius
  37490. * * radiusZ allows stretching in the z direction, optional, default radius
  37491. * * flat when true creates a flat shaded mesh, optional, default true
  37492. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37493. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37494. * * 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)
  37495. * * 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)
  37496. * @returns the VertexData of the IcoSphere
  37497. */
  37498. VertexData.CreateIcoSphere = function (options) {
  37499. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37500. var radius = options.radius || 1;
  37501. var flat = (options.flat === undefined) ? true : options.flat;
  37502. var subdivisions = options.subdivisions || 4;
  37503. var radiusX = options.radiusX || radius;
  37504. var radiusY = options.radiusY || radius;
  37505. var radiusZ = options.radiusZ || radius;
  37506. var t = (1 + Math.sqrt(5)) / 2;
  37507. // 12 vertex x,y,z
  37508. var ico_vertices = [
  37509. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37510. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37511. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37512. ];
  37513. // index of 3 vertex makes a face of icopshere
  37514. var ico_indices = [
  37515. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37516. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37517. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37518. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37519. ];
  37520. // vertex for uv have aliased position, not for UV
  37521. var vertices_unalias_id = [
  37522. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37523. // vertex alias
  37524. 0,
  37525. 2,
  37526. 3,
  37527. 3,
  37528. 3,
  37529. 4,
  37530. 7,
  37531. 8,
  37532. 9,
  37533. 9,
  37534. 10,
  37535. 11 // 23: B + 12
  37536. ];
  37537. // uv as integer step (not pixels !)
  37538. var ico_vertexuv = [
  37539. 5, 1, 3, 1, 6, 4, 0, 0,
  37540. 5, 3, 4, 2, 2, 2, 4, 0,
  37541. 2, 0, 1, 1, 6, 0, 6, 2,
  37542. // vertex alias (for same vertex on different faces)
  37543. 0, 4,
  37544. 3, 3,
  37545. 4, 4,
  37546. 3, 1,
  37547. 4, 2,
  37548. 4, 4,
  37549. 0, 2,
  37550. 1, 1,
  37551. 2, 2,
  37552. 3, 3,
  37553. 1, 3,
  37554. 2, 4 // 23: B + 12
  37555. ];
  37556. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37557. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37558. // First island of uv mapping
  37559. // v = 4h 3+ 2
  37560. // v = 3h 9+ 4
  37561. // v = 2h 9+ 5 B
  37562. // v = 1h 9 1 0
  37563. // v = 0h 3 8 7 A
  37564. // u = 0 1 2 3 4 5 6 *a
  37565. // Second island of uv mapping
  37566. // v = 4h 0+ B+ 4+
  37567. // v = 3h A+ 2+
  37568. // v = 2h 7+ 6 3+
  37569. // v = 1h 8+ 3+
  37570. // v = 0h
  37571. // u = 0 1 2 3 4 5 6 *a
  37572. // Face layout on texture UV mapping
  37573. // ============
  37574. // \ 4 /\ 16 / ======
  37575. // \ / \ / /\ 11 /
  37576. // \/ 7 \/ / \ /
  37577. // ======= / 10 \/
  37578. // /\ 17 /\ =======
  37579. // / \ / \ \ 15 /\
  37580. // / 8 \/ 12 \ \ / \
  37581. // ============ \/ 6 \
  37582. // \ 18 /\ ============
  37583. // \ / \ \ 5 /\ 0 /
  37584. // \/ 13 \ \ / \ /
  37585. // ======= \/ 1 \/
  37586. // =============
  37587. // /\ 19 /\ 2 /\
  37588. // / \ / \ / \
  37589. // / 14 \/ 9 \/ 3 \
  37590. // ===================
  37591. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37592. var ustep = 138 / 1024;
  37593. var vstep = 239 / 1024;
  37594. var uoffset = 60 / 1024;
  37595. var voffset = 26 / 1024;
  37596. // Second island should have margin, not to touch the first island
  37597. // avoid any borderline artefact in pixel rounding
  37598. var island_u_offset = -40 / 1024;
  37599. var island_v_offset = +20 / 1024;
  37600. // face is either island 0 or 1 :
  37601. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37602. var island = [
  37603. 0, 0, 0, 0, 1,
  37604. 0, 0, 1, 1, 0,
  37605. 0, 0, 1, 1, 0,
  37606. 0, 1, 1, 1, 0 // 15 - 19
  37607. ];
  37608. var indices = new Array();
  37609. var positions = new Array();
  37610. var normals = new Array();
  37611. var uvs = new Array();
  37612. var current_indice = 0;
  37613. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37614. var face_vertex_pos = new Array(3);
  37615. var face_vertex_uv = new Array(3);
  37616. var v012;
  37617. for (v012 = 0; v012 < 3; v012++) {
  37618. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37619. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37620. }
  37621. // create all with normals
  37622. for (var face = 0; face < 20; face++) {
  37623. // 3 vertex per face
  37624. for (v012 = 0; v012 < 3; v012++) {
  37625. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37626. var v_id = ico_indices[3 * face + v012];
  37627. // vertex have 3D position (x,y,z)
  37628. 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]);
  37629. // Normalize to get normal, then scale to radius
  37630. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37631. // uv Coordinates from vertex ID
  37632. 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);
  37633. }
  37634. // Subdivide the face (interpolate pos, norm, uv)
  37635. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37636. // - norm is linear interpolation of vertex corner normal
  37637. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37638. // - uv is linear interpolation
  37639. //
  37640. // Topology is as below for sub-divide by 2
  37641. // vertex shown as v0,v1,v2
  37642. // interp index is i1 to progress in range [v0,v1[
  37643. // interp index is i2 to progress in range [v0,v2[
  37644. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37645. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37646. //
  37647. //
  37648. // i2 v2
  37649. // ^ ^
  37650. // / / \
  37651. // / / \
  37652. // / / \
  37653. // / / (0,1) \
  37654. // / #---------\
  37655. // / / \ (0,0)'/ \
  37656. // / / \ / \
  37657. // / / \ / \
  37658. // / / (0,0) \ / (1,0) \
  37659. // / #---------#---------\
  37660. // v0 v1
  37661. //
  37662. // --------------------> i1
  37663. //
  37664. // interp of (i1,i2):
  37665. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37666. // along i1 : lerp(x0,x1, i1/(S-i2))
  37667. //
  37668. // centroid of triangle is needed to get help normal computation
  37669. // (c1,c2) are used for centroid location
  37670. var interp_vertex = function (i1, i2, c1, c2) {
  37671. // vertex is interpolated from
  37672. // - face_vertex_pos[0..2]
  37673. // - face_vertex_uv[0..2]
  37674. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37675. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37676. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37677. pos_interp.normalize();
  37678. var vertex_normal;
  37679. if (flat) {
  37680. // in flat mode, recalculate normal as face centroid normal
  37681. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37682. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37683. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37684. }
  37685. else {
  37686. // in smooth mode, recalculate normal from each single vertex position
  37687. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37688. }
  37689. // Vertex normal need correction due to X,Y,Z radius scaling
  37690. vertex_normal.x /= radiusX;
  37691. vertex_normal.y /= radiusY;
  37692. vertex_normal.z /= radiusZ;
  37693. vertex_normal.normalize();
  37694. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37695. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37696. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37697. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37698. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37699. uvs.push(uv_interp.x, uv_interp.y);
  37700. // push each vertex has member of a face
  37701. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37702. indices.push(current_indice);
  37703. current_indice++;
  37704. };
  37705. for (var i2 = 0; i2 < subdivisions; i2++) {
  37706. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37707. // face : (i1,i2) for /\ :
  37708. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37709. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37710. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37711. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37712. if (i1 + i2 + 1 < subdivisions) {
  37713. // face : (i1,i2)' for \/ :
  37714. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37715. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37716. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37717. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37718. }
  37719. }
  37720. }
  37721. }
  37722. // Sides
  37723. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37724. // Result
  37725. var vertexData = new VertexData();
  37726. vertexData.indices = indices;
  37727. vertexData.positions = positions;
  37728. vertexData.normals = normals;
  37729. vertexData.uvs = uvs;
  37730. return vertexData;
  37731. };
  37732. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37733. /**
  37734. * Creates the VertexData for a Polyhedron
  37735. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37736. * * type provided types are:
  37737. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37738. * * 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)
  37739. * * size the size of the IcoSphere, optional default 1
  37740. * * sizeX allows stretching in the x direction, optional, default size
  37741. * * sizeY allows stretching in the y direction, optional, default size
  37742. * * sizeZ allows stretching in the z direction, optional, default size
  37743. * * 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
  37744. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37745. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37746. * * flat when true creates a flat shaded mesh, optional, default true
  37747. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37748. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37749. * * 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)
  37750. * * 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)
  37751. * @returns the VertexData of the Polyhedron
  37752. */
  37753. VertexData.CreatePolyhedron = function (options) {
  37754. // provided polyhedron types :
  37755. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37756. // 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)
  37757. var polyhedra = [];
  37758. 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]] };
  37759. 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]] };
  37760. polyhedra[2] = {
  37761. 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]],
  37762. 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]]
  37763. };
  37764. polyhedra[3] = {
  37765. 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]],
  37766. 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]]
  37767. };
  37768. polyhedra[4] = {
  37769. 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]],
  37770. 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]]
  37771. };
  37772. 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]] };
  37773. 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]] };
  37774. 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]] };
  37775. 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]] };
  37776. 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]] };
  37777. 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]] };
  37778. 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]] };
  37779. 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]] };
  37780. 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]] };
  37781. polyhedra[14] = {
  37782. 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]],
  37783. 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]]
  37784. };
  37785. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37786. var size = options.size;
  37787. var sizeX = options.sizeX || size || 1;
  37788. var sizeY = options.sizeY || size || 1;
  37789. var sizeZ = options.sizeZ || size || 1;
  37790. var data = options.custom || polyhedra[type];
  37791. var nbfaces = data.face.length;
  37792. var faceUV = options.faceUV || new Array(nbfaces);
  37793. var faceColors = options.faceColors;
  37794. var flat = (options.flat === undefined) ? true : options.flat;
  37795. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37796. var positions = new Array();
  37797. var indices = new Array();
  37798. var normals = new Array();
  37799. var uvs = new Array();
  37800. var colors = new Array();
  37801. var index = 0;
  37802. var faceIdx = 0; // face cursor in the array "indexes"
  37803. var indexes = new Array();
  37804. var i = 0;
  37805. var f = 0;
  37806. var u, v, ang, x, y, tmp;
  37807. // default face colors and UV if undefined
  37808. if (flat) {
  37809. for (f = 0; f < nbfaces; f++) {
  37810. if (faceColors && faceColors[f] === undefined) {
  37811. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37812. }
  37813. if (faceUV && faceUV[f] === undefined) {
  37814. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37815. }
  37816. }
  37817. }
  37818. if (!flat) {
  37819. for (i = 0; i < data.vertex.length; i++) {
  37820. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37821. uvs.push(0, 0);
  37822. }
  37823. for (f = 0; f < nbfaces; f++) {
  37824. for (i = 0; i < data.face[f].length - 2; i++) {
  37825. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37826. }
  37827. }
  37828. }
  37829. else {
  37830. for (f = 0; f < nbfaces; f++) {
  37831. var fl = data.face[f].length; // number of vertices of the current face
  37832. ang = 2 * Math.PI / fl;
  37833. x = 0.5 * Math.tan(ang / 2);
  37834. y = 0.5;
  37835. // positions, uvs, colors
  37836. for (i = 0; i < fl; i++) {
  37837. // positions
  37838. 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);
  37839. indexes.push(index);
  37840. index++;
  37841. // uvs
  37842. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37843. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37844. uvs.push(u, v);
  37845. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37846. y = x * Math.sin(ang) + y * Math.cos(ang);
  37847. x = tmp;
  37848. // colors
  37849. if (faceColors) {
  37850. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37851. }
  37852. }
  37853. // indices from indexes
  37854. for (i = 0; i < fl - 2; i++) {
  37855. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37856. }
  37857. faceIdx += fl;
  37858. }
  37859. }
  37860. VertexData.ComputeNormals(positions, indices, normals);
  37861. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37862. var vertexData = new VertexData();
  37863. vertexData.positions = positions;
  37864. vertexData.indices = indices;
  37865. vertexData.normals = normals;
  37866. vertexData.uvs = uvs;
  37867. if (faceColors && flat) {
  37868. vertexData.colors = colors;
  37869. }
  37870. return vertexData;
  37871. };
  37872. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37873. /**
  37874. * Creates the VertexData for a TorusKnot
  37875. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37876. * * radius the radius of the torus knot, optional, default 2
  37877. * * tube the thickness of the tube, optional, default 0.5
  37878. * * radialSegments the number of sides on each tube segments, optional, default 32
  37879. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37880. * * p the number of windings around the z axis, optional, default 2
  37881. * * q the number of windings around the x axis, optional, default 3
  37882. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37883. * * 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)
  37884. * * 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)
  37885. * @returns the VertexData of the Torus Knot
  37886. */
  37887. VertexData.CreateTorusKnot = function (options) {
  37888. var indices = new Array();
  37889. var positions = new Array();
  37890. var normals = new Array();
  37891. var uvs = new Array();
  37892. var radius = options.radius || 2;
  37893. var tube = options.tube || 0.5;
  37894. var radialSegments = options.radialSegments || 32;
  37895. var tubularSegments = options.tubularSegments || 32;
  37896. var p = options.p || 2;
  37897. var q = options.q || 3;
  37898. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37899. // Helper
  37900. var getPos = function (angle) {
  37901. var cu = Math.cos(angle);
  37902. var su = Math.sin(angle);
  37903. var quOverP = q / p * angle;
  37904. var cs = Math.cos(quOverP);
  37905. var tx = radius * (2 + cs) * 0.5 * cu;
  37906. var ty = radius * (2 + cs) * su * 0.5;
  37907. var tz = radius * Math.sin(quOverP) * 0.5;
  37908. return new BABYLON.Vector3(tx, ty, tz);
  37909. };
  37910. // Vertices
  37911. var i;
  37912. var j;
  37913. for (i = 0; i <= radialSegments; i++) {
  37914. var modI = i % radialSegments;
  37915. var u = modI / radialSegments * 2 * p * Math.PI;
  37916. var p1 = getPos(u);
  37917. var p2 = getPos(u + 0.01);
  37918. var tang = p2.subtract(p1);
  37919. var n = p2.add(p1);
  37920. var bitan = BABYLON.Vector3.Cross(tang, n);
  37921. n = BABYLON.Vector3.Cross(bitan, tang);
  37922. bitan.normalize();
  37923. n.normalize();
  37924. for (j = 0; j < tubularSegments; j++) {
  37925. var modJ = j % tubularSegments;
  37926. var v = modJ / tubularSegments * 2 * Math.PI;
  37927. var cx = -tube * Math.cos(v);
  37928. var cy = tube * Math.sin(v);
  37929. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37930. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37931. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37932. uvs.push(i / radialSegments);
  37933. uvs.push(j / tubularSegments);
  37934. }
  37935. }
  37936. for (i = 0; i < radialSegments; i++) {
  37937. for (j = 0; j < tubularSegments; j++) {
  37938. var jNext = (j + 1) % tubularSegments;
  37939. var a = i * tubularSegments + j;
  37940. var b = (i + 1) * tubularSegments + j;
  37941. var c = (i + 1) * tubularSegments + jNext;
  37942. var d = i * tubularSegments + jNext;
  37943. indices.push(d);
  37944. indices.push(b);
  37945. indices.push(a);
  37946. indices.push(d);
  37947. indices.push(c);
  37948. indices.push(b);
  37949. }
  37950. }
  37951. // Normals
  37952. VertexData.ComputeNormals(positions, indices, normals);
  37953. // Sides
  37954. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37955. // Result
  37956. var vertexData = new VertexData();
  37957. vertexData.indices = indices;
  37958. vertexData.positions = positions;
  37959. vertexData.normals = normals;
  37960. vertexData.uvs = uvs;
  37961. return vertexData;
  37962. };
  37963. // Tools
  37964. /**
  37965. * Compute normals for given positions and indices
  37966. * @param positions an array of vertex positions, [...., x, y, z, ......]
  37967. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  37968. * @param normals an array of vertex normals, [...., x, y, z, ......]
  37969. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  37970. * * facetNormals : optional array of facet normals (vector3)
  37971. * * facetPositions : optional array of facet positions (vector3)
  37972. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37973. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37974. * * bInfo : optional bounding info, required for facetPartitioning computation
  37975. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  37976. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37977. * * useRightHandedSystem: optional boolean to for right handed system computation
  37978. * * depthSort : optional boolean to enable the facet depth sort computation
  37979. * * distanceTo : optional Vector3 to compute the facet depth from this location
  37980. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37981. */
  37982. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37983. // temporary scalar variables
  37984. var index = 0; // facet index
  37985. var p1p2x = 0.0; // p1p2 vector x coordinate
  37986. var p1p2y = 0.0; // p1p2 vector y coordinate
  37987. var p1p2z = 0.0; // p1p2 vector z coordinate
  37988. var p3p2x = 0.0; // p3p2 vector x coordinate
  37989. var p3p2y = 0.0; // p3p2 vector y coordinate
  37990. var p3p2z = 0.0; // p3p2 vector z coordinate
  37991. var faceNormalx = 0.0; // facet normal x coordinate
  37992. var faceNormaly = 0.0; // facet normal y coordinate
  37993. var faceNormalz = 0.0; // facet normal z coordinate
  37994. var length = 0.0; // facet normal length before normalization
  37995. var v1x = 0; // vector1 x index in the positions array
  37996. var v1y = 0; // vector1 y index in the positions array
  37997. var v1z = 0; // vector1 z index in the positions array
  37998. var v2x = 0; // vector2 x index in the positions array
  37999. var v2y = 0; // vector2 y index in the positions array
  38000. var v2z = 0; // vector2 z index in the positions array
  38001. var v3x = 0; // vector3 x index in the positions array
  38002. var v3y = 0; // vector3 y index in the positions array
  38003. var v3z = 0; // vector3 z index in the positions array
  38004. var computeFacetNormals = false;
  38005. var computeFacetPositions = false;
  38006. var computeFacetPartitioning = false;
  38007. var computeDepthSort = false;
  38008. var faceNormalSign = 1;
  38009. var ratio = 0;
  38010. var distanceTo = null;
  38011. if (options) {
  38012. computeFacetNormals = (options.facetNormals) ? true : false;
  38013. computeFacetPositions = (options.facetPositions) ? true : false;
  38014. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38015. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38016. ratio = options.ratio || 0;
  38017. computeDepthSort = (options.depthSort) ? true : false;
  38018. distanceTo = (options.distanceTo);
  38019. if (computeDepthSort) {
  38020. if (distanceTo === undefined) {
  38021. distanceTo = BABYLON.Vector3.Zero();
  38022. }
  38023. var depthSortedFacets = options.depthSortedFacets;
  38024. }
  38025. }
  38026. // facetPartitioning reinit if needed
  38027. var xSubRatio = 0;
  38028. var ySubRatio = 0;
  38029. var zSubRatio = 0;
  38030. var subSq = 0;
  38031. if (computeFacetPartitioning && options && options.bbSize) {
  38032. var ox = 0; // X partitioning index for facet position
  38033. var oy = 0; // Y partinioning index for facet position
  38034. var oz = 0; // Z partinioning index for facet position
  38035. var b1x = 0; // X partitioning index for facet v1 vertex
  38036. var b1y = 0; // Y partitioning index for facet v1 vertex
  38037. var b1z = 0; // z partitioning index for facet v1 vertex
  38038. var b2x = 0; // X partitioning index for facet v2 vertex
  38039. var b2y = 0; // Y partitioning index for facet v2 vertex
  38040. var b2z = 0; // Z partitioning index for facet v2 vertex
  38041. var b3x = 0; // X partitioning index for facet v3 vertex
  38042. var b3y = 0; // Y partitioning index for facet v3 vertex
  38043. var b3z = 0; // Z partitioning index for facet v3 vertex
  38044. var block_idx_o = 0; // facet barycenter block index
  38045. var block_idx_v1 = 0; // v1 vertex block index
  38046. var block_idx_v2 = 0; // v2 vertex block index
  38047. var block_idx_v3 = 0; // v3 vertex block index
  38048. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38049. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38050. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38051. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38052. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38053. subSq = options.subDiv.max * options.subDiv.max;
  38054. options.facetPartitioning.length = 0;
  38055. }
  38056. // reset the normals
  38057. for (index = 0; index < positions.length; index++) {
  38058. normals[index] = 0.0;
  38059. }
  38060. // Loop : 1 indice triplet = 1 facet
  38061. var nbFaces = (indices.length / 3) | 0;
  38062. for (index = 0; index < nbFaces; index++) {
  38063. // get the indexes of the coordinates of each vertex of the facet
  38064. v1x = indices[index * 3] * 3;
  38065. v1y = v1x + 1;
  38066. v1z = v1x + 2;
  38067. v2x = indices[index * 3 + 1] * 3;
  38068. v2y = v2x + 1;
  38069. v2z = v2x + 2;
  38070. v3x = indices[index * 3 + 2] * 3;
  38071. v3y = v3x + 1;
  38072. v3z = v3x + 2;
  38073. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38074. p1p2y = positions[v1y] - positions[v2y];
  38075. p1p2z = positions[v1z] - positions[v2z];
  38076. p3p2x = positions[v3x] - positions[v2x];
  38077. p3p2y = positions[v3y] - positions[v2y];
  38078. p3p2z = positions[v3z] - positions[v2z];
  38079. // compute the face normal with the cross product
  38080. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38081. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38082. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38083. // normalize this normal and store it in the array facetData
  38084. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38085. length = (length === 0) ? 1.0 : length;
  38086. faceNormalx /= length;
  38087. faceNormaly /= length;
  38088. faceNormalz /= length;
  38089. if (computeFacetNormals && options) {
  38090. options.facetNormals[index].x = faceNormalx;
  38091. options.facetNormals[index].y = faceNormaly;
  38092. options.facetNormals[index].z = faceNormalz;
  38093. }
  38094. if (computeFacetPositions && options) {
  38095. // compute and the facet barycenter coordinates in the array facetPositions
  38096. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38097. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38098. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38099. }
  38100. if (computeFacetPartitioning && options) {
  38101. // store the facet indexes in arrays in the main facetPartitioning array :
  38102. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38103. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38104. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38105. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38106. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38107. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38108. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38109. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38110. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38111. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38112. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38113. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38114. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38115. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38116. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38117. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38118. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38119. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38120. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38121. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38122. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38123. // push each facet index in each block containing the vertex
  38124. options.facetPartitioning[block_idx_v1].push(index);
  38125. if (block_idx_v2 != block_idx_v1) {
  38126. options.facetPartitioning[block_idx_v2].push(index);
  38127. }
  38128. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38129. options.facetPartitioning[block_idx_v3].push(index);
  38130. }
  38131. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38132. options.facetPartitioning[block_idx_o].push(index);
  38133. }
  38134. }
  38135. if (computeDepthSort && options && options.facetPositions) {
  38136. var dsf = depthSortedFacets[index];
  38137. dsf.ind = index * 3;
  38138. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38139. }
  38140. // compute the normals anyway
  38141. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38142. normals[v1y] += faceNormaly;
  38143. normals[v1z] += faceNormalz;
  38144. normals[v2x] += faceNormalx;
  38145. normals[v2y] += faceNormaly;
  38146. normals[v2z] += faceNormalz;
  38147. normals[v3x] += faceNormalx;
  38148. normals[v3y] += faceNormaly;
  38149. normals[v3z] += faceNormalz;
  38150. }
  38151. // last normalization of each normal
  38152. for (index = 0; index < normals.length / 3; index++) {
  38153. faceNormalx = normals[index * 3];
  38154. faceNormaly = normals[index * 3 + 1];
  38155. faceNormalz = normals[index * 3 + 2];
  38156. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38157. length = (length === 0) ? 1.0 : length;
  38158. faceNormalx /= length;
  38159. faceNormaly /= length;
  38160. faceNormalz /= length;
  38161. normals[index * 3] = faceNormalx;
  38162. normals[index * 3 + 1] = faceNormaly;
  38163. normals[index * 3 + 2] = faceNormalz;
  38164. }
  38165. };
  38166. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38167. var li = indices.length;
  38168. var ln = normals.length;
  38169. var i;
  38170. var n;
  38171. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38172. switch (sideOrientation) {
  38173. case BABYLON.Mesh.FRONTSIDE:
  38174. // nothing changed
  38175. break;
  38176. case BABYLON.Mesh.BACKSIDE:
  38177. var tmp;
  38178. // indices
  38179. for (i = 0; i < li; i += 3) {
  38180. tmp = indices[i];
  38181. indices[i] = indices[i + 2];
  38182. indices[i + 2] = tmp;
  38183. }
  38184. // normals
  38185. for (n = 0; n < ln; n++) {
  38186. normals[n] = -normals[n];
  38187. }
  38188. break;
  38189. case BABYLON.Mesh.DOUBLESIDE:
  38190. // positions
  38191. var lp = positions.length;
  38192. var l = lp / 3;
  38193. for (var p = 0; p < lp; p++) {
  38194. positions[lp + p] = positions[p];
  38195. }
  38196. // indices
  38197. for (i = 0; i < li; i += 3) {
  38198. indices[i + li] = indices[i + 2] + l;
  38199. indices[i + 1 + li] = indices[i + 1] + l;
  38200. indices[i + 2 + li] = indices[i] + l;
  38201. }
  38202. // normals
  38203. for (n = 0; n < ln; n++) {
  38204. normals[ln + n] = -normals[n];
  38205. }
  38206. // uvs
  38207. var lu = uvs.length;
  38208. var u = 0;
  38209. for (u = 0; u < lu; u++) {
  38210. uvs[u + lu] = uvs[u];
  38211. }
  38212. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38213. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38214. u = 0;
  38215. for (i = 0; i < lu / 2; i++) {
  38216. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38217. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38218. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38219. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38220. u += 2;
  38221. }
  38222. break;
  38223. }
  38224. };
  38225. /**
  38226. * Applies VertexData created from the imported parameters to the geometry
  38227. * @param parsedVertexData the parsed data from an imported file
  38228. * @param geometry the geometry to apply the VertexData to
  38229. */
  38230. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38231. var vertexData = new VertexData();
  38232. // positions
  38233. var positions = parsedVertexData.positions;
  38234. if (positions) {
  38235. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38236. }
  38237. // normals
  38238. var normals = parsedVertexData.normals;
  38239. if (normals) {
  38240. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38241. }
  38242. // tangents
  38243. var tangents = parsedVertexData.tangents;
  38244. if (tangents) {
  38245. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38246. }
  38247. // uvs
  38248. var uvs = parsedVertexData.uvs;
  38249. if (uvs) {
  38250. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38251. }
  38252. // uv2s
  38253. var uv2s = parsedVertexData.uv2s;
  38254. if (uv2s) {
  38255. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38256. }
  38257. // uv3s
  38258. var uv3s = parsedVertexData.uv3s;
  38259. if (uv3s) {
  38260. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38261. }
  38262. // uv4s
  38263. var uv4s = parsedVertexData.uv4s;
  38264. if (uv4s) {
  38265. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38266. }
  38267. // uv5s
  38268. var uv5s = parsedVertexData.uv5s;
  38269. if (uv5s) {
  38270. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38271. }
  38272. // uv6s
  38273. var uv6s = parsedVertexData.uv6s;
  38274. if (uv6s) {
  38275. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38276. }
  38277. // colors
  38278. var colors = parsedVertexData.colors;
  38279. if (colors) {
  38280. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38281. }
  38282. // matricesIndices
  38283. var matricesIndices = parsedVertexData.matricesIndices;
  38284. if (matricesIndices) {
  38285. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38286. }
  38287. // matricesWeights
  38288. var matricesWeights = parsedVertexData.matricesWeights;
  38289. if (matricesWeights) {
  38290. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38291. }
  38292. // indices
  38293. var indices = parsedVertexData.indices;
  38294. if (indices) {
  38295. vertexData.indices = indices;
  38296. }
  38297. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38298. };
  38299. return VertexData;
  38300. }());
  38301. BABYLON.VertexData = VertexData;
  38302. })(BABYLON || (BABYLON = {}));
  38303. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38304. var BABYLON;
  38305. (function (BABYLON) {
  38306. /**
  38307. * Class used to store geometry data (vertex buffers + index buffer)
  38308. */
  38309. var Geometry = /** @class */ (function () {
  38310. /**
  38311. * Creates a new geometry
  38312. * @param id defines the unique ID
  38313. * @param scene defines the hosting scene
  38314. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38315. * @param updatable defines if geometry must be updatable (false by default)
  38316. * @param mesh defines the mesh that will be associated with the geometry
  38317. */
  38318. function Geometry(id, scene, vertexData, updatable, mesh) {
  38319. if (updatable === void 0) { updatable = false; }
  38320. if (mesh === void 0) { mesh = null; }
  38321. /**
  38322. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38323. */
  38324. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38325. this._totalVertices = 0;
  38326. this._isDisposed = false;
  38327. this._indexBufferIsUpdatable = false;
  38328. this.id = id;
  38329. this._engine = scene.getEngine();
  38330. this._meshes = [];
  38331. this._scene = scene;
  38332. //Init vertex buffer cache
  38333. this._vertexBuffers = {};
  38334. this._indices = [];
  38335. this._updatable = updatable;
  38336. // vertexData
  38337. if (vertexData) {
  38338. this.setAllVerticesData(vertexData, updatable);
  38339. }
  38340. else {
  38341. this._totalVertices = 0;
  38342. this._indices = [];
  38343. }
  38344. if (this._engine.getCaps().vertexArrayObject) {
  38345. this._vertexArrayObjects = {};
  38346. }
  38347. // applyToMesh
  38348. if (mesh) {
  38349. if (mesh.getClassName() === "LinesMesh") {
  38350. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38351. this._updateExtend();
  38352. }
  38353. this.applyToMesh(mesh);
  38354. mesh.computeWorldMatrix(true);
  38355. }
  38356. }
  38357. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38358. /**
  38359. * 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
  38360. */
  38361. get: function () {
  38362. return this._boundingBias;
  38363. },
  38364. /**
  38365. * 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
  38366. */
  38367. set: function (value) {
  38368. if (this._boundingBias && this._boundingBias.equals(value)) {
  38369. return;
  38370. }
  38371. this._boundingBias = value.clone();
  38372. this._updateBoundingInfo(true, null);
  38373. },
  38374. enumerable: true,
  38375. configurable: true
  38376. });
  38377. /**
  38378. * Static function used to attach a new empty geometry to a mesh
  38379. * @param mesh defines the mesh to attach the geometry to
  38380. * @returns the new {BABYLON.Geometry}
  38381. */
  38382. Geometry.CreateGeometryForMesh = function (mesh) {
  38383. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38384. geometry.applyToMesh(mesh);
  38385. return geometry;
  38386. };
  38387. Object.defineProperty(Geometry.prototype, "extend", {
  38388. /**
  38389. * Gets the current extend of the geometry
  38390. */
  38391. get: function () {
  38392. return this._extend;
  38393. },
  38394. enumerable: true,
  38395. configurable: true
  38396. });
  38397. /**
  38398. * Gets the hosting scene
  38399. * @returns the hosting {BABYLON.Scene}
  38400. */
  38401. Geometry.prototype.getScene = function () {
  38402. return this._scene;
  38403. };
  38404. /**
  38405. * Gets the hosting engine
  38406. * @returns the hosting {BABYLON.Engine}
  38407. */
  38408. Geometry.prototype.getEngine = function () {
  38409. return this._engine;
  38410. };
  38411. /**
  38412. * Defines if the geometry is ready to use
  38413. * @returns true if the geometry is ready to be used
  38414. */
  38415. Geometry.prototype.isReady = function () {
  38416. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38417. };
  38418. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38419. /**
  38420. * Gets a value indicating that the geometry should not be serialized
  38421. */
  38422. get: function () {
  38423. for (var index = 0; index < this._meshes.length; index++) {
  38424. if (!this._meshes[index].doNotSerialize) {
  38425. return false;
  38426. }
  38427. }
  38428. return true;
  38429. },
  38430. enumerable: true,
  38431. configurable: true
  38432. });
  38433. /** @hidden */
  38434. Geometry.prototype._rebuild = function () {
  38435. if (this._vertexArrayObjects) {
  38436. this._vertexArrayObjects = {};
  38437. }
  38438. // Index buffer
  38439. if (this._meshes.length !== 0 && this._indices) {
  38440. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38441. }
  38442. // Vertex buffers
  38443. for (var key in this._vertexBuffers) {
  38444. var vertexBuffer = this._vertexBuffers[key];
  38445. vertexBuffer._rebuild();
  38446. }
  38447. };
  38448. /**
  38449. * Affects all geometry data in one call
  38450. * @param vertexData defines the geometry data
  38451. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38452. */
  38453. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38454. vertexData.applyToGeometry(this, updatable);
  38455. this.notifyUpdate();
  38456. };
  38457. /**
  38458. * Set specific vertex data
  38459. * @param kind defines the data kind (Position, normal, etc...)
  38460. * @param data defines the vertex data to use
  38461. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38462. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38463. */
  38464. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38465. if (updatable === void 0) { updatable = false; }
  38466. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38467. this.setVerticesBuffer(buffer);
  38468. };
  38469. /**
  38470. * Removes a specific vertex data
  38471. * @param kind defines the data kind (Position, normal, etc...)
  38472. */
  38473. Geometry.prototype.removeVerticesData = function (kind) {
  38474. if (this._vertexBuffers[kind]) {
  38475. this._vertexBuffers[kind].dispose();
  38476. delete this._vertexBuffers[kind];
  38477. }
  38478. };
  38479. /**
  38480. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38481. * @param buffer defines the vertex buffer to use
  38482. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38483. */
  38484. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38485. if (totalVertices === void 0) { totalVertices = null; }
  38486. var kind = buffer.getKind();
  38487. if (this._vertexBuffers[kind]) {
  38488. this._vertexBuffers[kind].dispose();
  38489. }
  38490. this._vertexBuffers[kind] = buffer;
  38491. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38492. var data = buffer.getData();
  38493. if (totalVertices != null) {
  38494. this._totalVertices = totalVertices;
  38495. }
  38496. else {
  38497. if (data != null) {
  38498. this._totalVertices = data.length / (buffer.byteStride / 4);
  38499. }
  38500. }
  38501. this._updateExtend(data);
  38502. this._resetPointsArrayCache();
  38503. var meshes = this._meshes;
  38504. var numOfMeshes = meshes.length;
  38505. for (var index = 0; index < numOfMeshes; index++) {
  38506. var mesh = meshes[index];
  38507. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38508. mesh._createGlobalSubMesh(false);
  38509. mesh.computeWorldMatrix(true);
  38510. }
  38511. }
  38512. this.notifyUpdate(kind);
  38513. if (this._vertexArrayObjects) {
  38514. this._disposeVertexArrayObjects();
  38515. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38516. }
  38517. };
  38518. /**
  38519. * Update a specific vertex buffer
  38520. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38521. * It will do nothing if the buffer is not updatable
  38522. * @param kind defines the data kind (Position, normal, etc...)
  38523. * @param data defines the data to use
  38524. * @param offset defines the offset in the target buffer where to store the data
  38525. * @param useBytes set to true if the offset is in bytes
  38526. */
  38527. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38528. if (useBytes === void 0) { useBytes = false; }
  38529. var vertexBuffer = this.getVertexBuffer(kind);
  38530. if (!vertexBuffer) {
  38531. return;
  38532. }
  38533. vertexBuffer.updateDirectly(data, offset, useBytes);
  38534. this.notifyUpdate(kind);
  38535. };
  38536. /**
  38537. * Update a specific vertex buffer
  38538. * This function will create a new buffer if the current one is not updatable
  38539. * @param kind defines the data kind (Position, normal, etc...)
  38540. * @param data defines the data to use
  38541. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38542. */
  38543. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38544. if (updateExtends === void 0) { updateExtends = false; }
  38545. var vertexBuffer = this.getVertexBuffer(kind);
  38546. if (!vertexBuffer) {
  38547. return;
  38548. }
  38549. vertexBuffer.update(data);
  38550. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38551. this._updateBoundingInfo(updateExtends, data);
  38552. }
  38553. this.notifyUpdate(kind);
  38554. };
  38555. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38556. if (updateExtends) {
  38557. this._updateExtend(data);
  38558. }
  38559. var meshes = this._meshes;
  38560. var numOfMeshes = meshes.length;
  38561. this._resetPointsArrayCache();
  38562. for (var index = 0; index < numOfMeshes; index++) {
  38563. var mesh = meshes[index];
  38564. if (updateExtends) {
  38565. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38566. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38567. var subMesh = mesh.subMeshes[subIndex];
  38568. subMesh.refreshBoundingInfo();
  38569. }
  38570. }
  38571. }
  38572. };
  38573. /** @hidden */
  38574. Geometry.prototype._bind = function (effect, indexToBind) {
  38575. if (!effect) {
  38576. return;
  38577. }
  38578. if (indexToBind === undefined) {
  38579. indexToBind = this._indexBuffer;
  38580. }
  38581. var vbs = this.getVertexBuffers();
  38582. if (!vbs) {
  38583. return;
  38584. }
  38585. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38586. this._engine.bindBuffers(vbs, indexToBind, effect);
  38587. return;
  38588. }
  38589. // Using VAO
  38590. if (!this._vertexArrayObjects[effect.key]) {
  38591. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38592. }
  38593. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38594. };
  38595. /**
  38596. * Gets total number of vertices
  38597. * @returns the total number of vertices
  38598. */
  38599. Geometry.prototype.getTotalVertices = function () {
  38600. if (!this.isReady()) {
  38601. return 0;
  38602. }
  38603. return this._totalVertices;
  38604. };
  38605. /**
  38606. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38607. * @param kind defines the data kind (Position, normal, etc...)
  38608. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38609. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38610. * @returns a float array containing vertex data
  38611. */
  38612. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38613. var vertexBuffer = this.getVertexBuffer(kind);
  38614. if (!vertexBuffer) {
  38615. return null;
  38616. }
  38617. var data = vertexBuffer.getData();
  38618. if (!data) {
  38619. return null;
  38620. }
  38621. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38622. var count = this._totalVertices * vertexBuffer.getSize();
  38623. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38624. var copy_1 = new Array(count);
  38625. vertexBuffer.forEach(count, function (value, index) {
  38626. copy_1[index] = value;
  38627. });
  38628. return copy_1;
  38629. }
  38630. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38631. if (data instanceof Array) {
  38632. var offset = vertexBuffer.byteOffset / 4;
  38633. return BABYLON.Tools.Slice(data, offset, offset + count);
  38634. }
  38635. else if (data instanceof ArrayBuffer) {
  38636. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38637. }
  38638. else {
  38639. var offset = data.byteOffset + vertexBuffer.byteOffset;
  38640. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38641. var result = new Float32Array(count);
  38642. var source = new Float32Array(data.buffer, offset, count);
  38643. result.set(source);
  38644. return result;
  38645. }
  38646. return new Float32Array(data.buffer, offset, count);
  38647. }
  38648. }
  38649. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38650. return BABYLON.Tools.Slice(data);
  38651. }
  38652. return data;
  38653. };
  38654. /**
  38655. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38656. * @param kind defines the data kind (Position, normal, etc...)
  38657. * @returns true if the vertex buffer with the specified kind is updatable
  38658. */
  38659. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38660. var vb = this._vertexBuffers[kind];
  38661. if (!vb) {
  38662. return false;
  38663. }
  38664. return vb.isUpdatable();
  38665. };
  38666. /**
  38667. * Gets a specific vertex buffer
  38668. * @param kind defines the data kind (Position, normal, etc...)
  38669. * @returns a {BABYLON.VertexBuffer}
  38670. */
  38671. Geometry.prototype.getVertexBuffer = function (kind) {
  38672. if (!this.isReady()) {
  38673. return null;
  38674. }
  38675. return this._vertexBuffers[kind];
  38676. };
  38677. /**
  38678. * Returns all vertex buffers
  38679. * @return an object holding all vertex buffers indexed by kind
  38680. */
  38681. Geometry.prototype.getVertexBuffers = function () {
  38682. if (!this.isReady()) {
  38683. return null;
  38684. }
  38685. return this._vertexBuffers;
  38686. };
  38687. /**
  38688. * Gets a boolean indicating if specific vertex buffer is present
  38689. * @param kind defines the data kind (Position, normal, etc...)
  38690. * @returns true if data is present
  38691. */
  38692. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38693. if (!this._vertexBuffers) {
  38694. if (this._delayInfo) {
  38695. return this._delayInfo.indexOf(kind) !== -1;
  38696. }
  38697. return false;
  38698. }
  38699. return this._vertexBuffers[kind] !== undefined;
  38700. };
  38701. /**
  38702. * Gets a list of all attached data kinds (Position, normal, etc...)
  38703. * @returns a list of string containing all kinds
  38704. */
  38705. Geometry.prototype.getVerticesDataKinds = function () {
  38706. var result = [];
  38707. var kind;
  38708. if (!this._vertexBuffers && this._delayInfo) {
  38709. for (kind in this._delayInfo) {
  38710. result.push(kind);
  38711. }
  38712. }
  38713. else {
  38714. for (kind in this._vertexBuffers) {
  38715. result.push(kind);
  38716. }
  38717. }
  38718. return result;
  38719. };
  38720. /**
  38721. * Update index buffer
  38722. * @param indices defines the indices to store in the index buffer
  38723. * @param offset defines the offset in the target buffer where to store the data
  38724. */
  38725. Geometry.prototype.updateIndices = function (indices, offset) {
  38726. if (!this._indexBuffer) {
  38727. return;
  38728. }
  38729. if (!this._indexBufferIsUpdatable) {
  38730. this.setIndices(indices, null, true);
  38731. }
  38732. else {
  38733. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38734. }
  38735. };
  38736. /**
  38737. * Creates a new index buffer
  38738. * @param indices defines the indices to store in the index buffer
  38739. * @param totalVertices defines the total number of vertices (could be null)
  38740. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38741. */
  38742. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38743. if (totalVertices === void 0) { totalVertices = null; }
  38744. if (updatable === void 0) { updatable = false; }
  38745. if (this._indexBuffer) {
  38746. this._engine._releaseBuffer(this._indexBuffer);
  38747. }
  38748. this._disposeVertexArrayObjects();
  38749. this._indices = indices;
  38750. this._indexBufferIsUpdatable = updatable;
  38751. if (this._meshes.length !== 0 && this._indices) {
  38752. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38753. }
  38754. if (totalVertices != undefined) { // including null and undefined
  38755. this._totalVertices = totalVertices;
  38756. }
  38757. var meshes = this._meshes;
  38758. var numOfMeshes = meshes.length;
  38759. for (var index = 0; index < numOfMeshes; index++) {
  38760. meshes[index]._createGlobalSubMesh(true);
  38761. }
  38762. this.notifyUpdate();
  38763. };
  38764. /**
  38765. * Return the total number of indices
  38766. * @returns the total number of indices
  38767. */
  38768. Geometry.prototype.getTotalIndices = function () {
  38769. if (!this.isReady()) {
  38770. return 0;
  38771. }
  38772. return this._indices.length;
  38773. };
  38774. /**
  38775. * Gets the index buffer array
  38776. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38777. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38778. * @returns the index buffer array
  38779. */
  38780. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  38781. if (!this.isReady()) {
  38782. return null;
  38783. }
  38784. var orig = this._indices;
  38785. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  38786. return orig;
  38787. }
  38788. else {
  38789. var len = orig.length;
  38790. var copy = [];
  38791. for (var i = 0; i < len; i++) {
  38792. copy.push(orig[i]);
  38793. }
  38794. return copy;
  38795. }
  38796. };
  38797. /**
  38798. * Gets the index buffer
  38799. * @return the index buffer
  38800. */
  38801. Geometry.prototype.getIndexBuffer = function () {
  38802. if (!this.isReady()) {
  38803. return null;
  38804. }
  38805. return this._indexBuffer;
  38806. };
  38807. /** @hidden */
  38808. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38809. if (effect === void 0) { effect = null; }
  38810. if (!effect || !this._vertexArrayObjects) {
  38811. return;
  38812. }
  38813. if (this._vertexArrayObjects[effect.key]) {
  38814. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38815. delete this._vertexArrayObjects[effect.key];
  38816. }
  38817. };
  38818. /**
  38819. * Release the associated resources for a specific mesh
  38820. * @param mesh defines the source mesh
  38821. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38822. */
  38823. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38824. var meshes = this._meshes;
  38825. var index = meshes.indexOf(mesh);
  38826. if (index === -1) {
  38827. return;
  38828. }
  38829. meshes.splice(index, 1);
  38830. mesh._geometry = null;
  38831. if (meshes.length === 0 && shouldDispose) {
  38832. this.dispose();
  38833. }
  38834. };
  38835. /**
  38836. * Apply current geometry to a given mesh
  38837. * @param mesh defines the mesh to apply geometry to
  38838. */
  38839. Geometry.prototype.applyToMesh = function (mesh) {
  38840. if (mesh._geometry === this) {
  38841. return;
  38842. }
  38843. var previousGeometry = mesh._geometry;
  38844. if (previousGeometry) {
  38845. previousGeometry.releaseForMesh(mesh);
  38846. }
  38847. var meshes = this._meshes;
  38848. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38849. mesh._geometry = this;
  38850. this._scene.pushGeometry(this);
  38851. meshes.push(mesh);
  38852. if (this.isReady()) {
  38853. this._applyToMesh(mesh);
  38854. }
  38855. else {
  38856. mesh._boundingInfo = this._boundingInfo;
  38857. }
  38858. };
  38859. Geometry.prototype._updateExtend = function (data) {
  38860. if (data === void 0) { data = null; }
  38861. if (!data) {
  38862. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38863. }
  38864. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38865. };
  38866. Geometry.prototype._applyToMesh = function (mesh) {
  38867. var numOfMeshes = this._meshes.length;
  38868. // vertexBuffers
  38869. for (var kind in this._vertexBuffers) {
  38870. if (numOfMeshes === 1) {
  38871. this._vertexBuffers[kind].create();
  38872. }
  38873. var buffer = this._vertexBuffers[kind].getBuffer();
  38874. if (buffer)
  38875. buffer.references = numOfMeshes;
  38876. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38877. if (!this._extend) {
  38878. this._updateExtend();
  38879. }
  38880. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38881. mesh._createGlobalSubMesh(false);
  38882. //bounding info was just created again, world matrix should be applied again.
  38883. mesh._updateBoundingInfo();
  38884. }
  38885. }
  38886. // indexBuffer
  38887. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38888. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38889. }
  38890. if (this._indexBuffer) {
  38891. this._indexBuffer.references = numOfMeshes;
  38892. }
  38893. };
  38894. Geometry.prototype.notifyUpdate = function (kind) {
  38895. if (this.onGeometryUpdated) {
  38896. this.onGeometryUpdated(this, kind);
  38897. }
  38898. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38899. var mesh = _a[_i];
  38900. mesh._markSubMeshesAsAttributesDirty();
  38901. }
  38902. };
  38903. /**
  38904. * Load the geometry if it was flagged as delay loaded
  38905. * @param scene defines the hosting scene
  38906. * @param onLoaded defines a callback called when the geometry is loaded
  38907. */
  38908. Geometry.prototype.load = function (scene, onLoaded) {
  38909. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38910. return;
  38911. }
  38912. if (this.isReady()) {
  38913. if (onLoaded) {
  38914. onLoaded();
  38915. }
  38916. return;
  38917. }
  38918. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38919. this._queueLoad(scene, onLoaded);
  38920. };
  38921. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38922. var _this = this;
  38923. if (!this.delayLoadingFile) {
  38924. return;
  38925. }
  38926. scene._addPendingData(this);
  38927. scene._loadFile(this.delayLoadingFile, function (data) {
  38928. if (!_this._delayLoadingFunction) {
  38929. return;
  38930. }
  38931. _this._delayLoadingFunction(JSON.parse(data), _this);
  38932. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38933. _this._delayInfo = [];
  38934. scene._removePendingData(_this);
  38935. var meshes = _this._meshes;
  38936. var numOfMeshes = meshes.length;
  38937. for (var index = 0; index < numOfMeshes; index++) {
  38938. _this._applyToMesh(meshes[index]);
  38939. }
  38940. if (onLoaded) {
  38941. onLoaded();
  38942. }
  38943. }, undefined, true);
  38944. };
  38945. /**
  38946. * Invert the geometry to move from a right handed system to a left handed one.
  38947. */
  38948. Geometry.prototype.toLeftHanded = function () {
  38949. // Flip faces
  38950. var tIndices = this.getIndices(false);
  38951. if (tIndices != null && tIndices.length > 0) {
  38952. for (var i = 0; i < tIndices.length; i += 3) {
  38953. var tTemp = tIndices[i + 0];
  38954. tIndices[i + 0] = tIndices[i + 2];
  38955. tIndices[i + 2] = tTemp;
  38956. }
  38957. this.setIndices(tIndices);
  38958. }
  38959. // Negate position.z
  38960. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38961. if (tPositions != null && tPositions.length > 0) {
  38962. for (var i = 0; i < tPositions.length; i += 3) {
  38963. tPositions[i + 2] = -tPositions[i + 2];
  38964. }
  38965. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38966. }
  38967. // Negate normal.z
  38968. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38969. if (tNormals != null && tNormals.length > 0) {
  38970. for (var i = 0; i < tNormals.length; i += 3) {
  38971. tNormals[i + 2] = -tNormals[i + 2];
  38972. }
  38973. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38974. }
  38975. };
  38976. // Cache
  38977. /** @hidden */
  38978. Geometry.prototype._resetPointsArrayCache = function () {
  38979. this._positions = null;
  38980. };
  38981. /** @hidden */
  38982. Geometry.prototype._generatePointsArray = function () {
  38983. if (this._positions)
  38984. return true;
  38985. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38986. if (!data || data.length === 0) {
  38987. return false;
  38988. }
  38989. this._positions = [];
  38990. for (var index = 0; index < data.length; index += 3) {
  38991. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38992. }
  38993. return true;
  38994. };
  38995. /**
  38996. * Gets a value indicating if the geometry is disposed
  38997. * @returns true if the geometry was disposed
  38998. */
  38999. Geometry.prototype.isDisposed = function () {
  39000. return this._isDisposed;
  39001. };
  39002. Geometry.prototype._disposeVertexArrayObjects = function () {
  39003. if (this._vertexArrayObjects) {
  39004. for (var kind in this._vertexArrayObjects) {
  39005. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39006. }
  39007. this._vertexArrayObjects = {};
  39008. }
  39009. };
  39010. /**
  39011. * Free all associated resources
  39012. */
  39013. Geometry.prototype.dispose = function () {
  39014. var meshes = this._meshes;
  39015. var numOfMeshes = meshes.length;
  39016. var index;
  39017. for (index = 0; index < numOfMeshes; index++) {
  39018. this.releaseForMesh(meshes[index]);
  39019. }
  39020. this._meshes = [];
  39021. this._disposeVertexArrayObjects();
  39022. for (var kind in this._vertexBuffers) {
  39023. this._vertexBuffers[kind].dispose();
  39024. }
  39025. this._vertexBuffers = {};
  39026. this._totalVertices = 0;
  39027. if (this._indexBuffer) {
  39028. this._engine._releaseBuffer(this._indexBuffer);
  39029. }
  39030. this._indexBuffer = null;
  39031. this._indices = [];
  39032. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39033. this.delayLoadingFile = null;
  39034. this._delayLoadingFunction = null;
  39035. this._delayInfo = [];
  39036. this._boundingInfo = null;
  39037. this._scene.removeGeometry(this);
  39038. this._isDisposed = true;
  39039. };
  39040. /**
  39041. * Clone the current geometry into a new geometry
  39042. * @param id defines the unique ID of the new geometry
  39043. * @returns a new geometry object
  39044. */
  39045. Geometry.prototype.copy = function (id) {
  39046. var vertexData = new BABYLON.VertexData();
  39047. vertexData.indices = [];
  39048. var indices = this.getIndices();
  39049. if (indices) {
  39050. for (var index = 0; index < indices.length; index++) {
  39051. vertexData.indices.push(indices[index]);
  39052. }
  39053. }
  39054. var updatable = false;
  39055. var stopChecking = false;
  39056. var kind;
  39057. for (kind in this._vertexBuffers) {
  39058. // using slice() to make a copy of the array and not just reference it
  39059. var data = this.getVerticesData(kind);
  39060. if (data instanceof Float32Array) {
  39061. vertexData.set(new Float32Array(data), kind);
  39062. }
  39063. else {
  39064. vertexData.set(data.slice(0), kind);
  39065. }
  39066. if (!stopChecking) {
  39067. var vb = this.getVertexBuffer(kind);
  39068. if (vb) {
  39069. updatable = vb.isUpdatable();
  39070. stopChecking = !updatable;
  39071. }
  39072. }
  39073. }
  39074. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39075. geometry.delayLoadState = this.delayLoadState;
  39076. geometry.delayLoadingFile = this.delayLoadingFile;
  39077. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39078. for (kind in this._delayInfo) {
  39079. geometry._delayInfo = geometry._delayInfo || [];
  39080. geometry._delayInfo.push(kind);
  39081. }
  39082. // Bounding info
  39083. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39084. return geometry;
  39085. };
  39086. /**
  39087. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39088. * @return a JSON representation of the current geometry data (without the vertices data)
  39089. */
  39090. Geometry.prototype.serialize = function () {
  39091. var serializationObject = {};
  39092. serializationObject.id = this.id;
  39093. serializationObject.updatable = this._updatable;
  39094. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39095. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39096. }
  39097. return serializationObject;
  39098. };
  39099. Geometry.prototype.toNumberArray = function (origin) {
  39100. if (Array.isArray(origin)) {
  39101. return origin;
  39102. }
  39103. else {
  39104. return Array.prototype.slice.call(origin);
  39105. }
  39106. };
  39107. /**
  39108. * Serialize all vertices data into a JSON oject
  39109. * @returns a JSON representation of the current geometry data
  39110. */
  39111. Geometry.prototype.serializeVerticeData = function () {
  39112. var serializationObject = this.serialize();
  39113. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39114. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39115. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39116. serializationObject.positions._updatable = true;
  39117. }
  39118. }
  39119. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39120. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39121. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39122. serializationObject.normals._updatable = true;
  39123. }
  39124. }
  39125. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39126. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39127. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39128. serializationObject.tangets._updatable = true;
  39129. }
  39130. }
  39131. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39132. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39133. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39134. serializationObject.uvs._updatable = true;
  39135. }
  39136. }
  39137. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39138. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39139. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39140. serializationObject.uv2s._updatable = true;
  39141. }
  39142. }
  39143. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39144. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39145. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39146. serializationObject.uv3s._updatable = true;
  39147. }
  39148. }
  39149. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39150. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39151. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39152. serializationObject.uv4s._updatable = true;
  39153. }
  39154. }
  39155. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39156. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39157. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39158. serializationObject.uv5s._updatable = true;
  39159. }
  39160. }
  39161. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39162. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39163. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39164. serializationObject.uv6s._updatable = true;
  39165. }
  39166. }
  39167. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39168. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39169. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39170. serializationObject.colors._updatable = true;
  39171. }
  39172. }
  39173. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39174. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39175. serializationObject.matricesIndices._isExpanded = true;
  39176. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39177. serializationObject.matricesIndices._updatable = true;
  39178. }
  39179. }
  39180. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39181. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39182. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39183. serializationObject.matricesWeights._updatable = true;
  39184. }
  39185. }
  39186. serializationObject.indices = this.toNumberArray(this.getIndices());
  39187. return serializationObject;
  39188. };
  39189. // Statics
  39190. /**
  39191. * Extracts a clone of a mesh geometry
  39192. * @param mesh defines the source mesh
  39193. * @param id defines the unique ID of the new geometry object
  39194. * @returns the new geometry object
  39195. */
  39196. Geometry.ExtractFromMesh = function (mesh, id) {
  39197. var geometry = mesh._geometry;
  39198. if (!geometry) {
  39199. return null;
  39200. }
  39201. return geometry.copy(id);
  39202. };
  39203. /**
  39204. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39205. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39206. * Be aware Math.random() could cause collisions, but:
  39207. * "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"
  39208. * @returns a string containing a new GUID
  39209. */
  39210. Geometry.RandomId = function () {
  39211. return BABYLON.Tools.RandomId();
  39212. };
  39213. /** @hidden */
  39214. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39215. var scene = mesh.getScene();
  39216. // Geometry
  39217. var geometryId = parsedGeometry.geometryId;
  39218. if (geometryId) {
  39219. var geometry = scene.getGeometryByID(geometryId);
  39220. if (geometry) {
  39221. geometry.applyToMesh(mesh);
  39222. }
  39223. }
  39224. else if (parsedGeometry instanceof ArrayBuffer) {
  39225. var binaryInfo = mesh._binaryInfo;
  39226. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39227. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39228. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39229. }
  39230. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39231. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39232. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39233. }
  39234. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39235. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39236. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39237. }
  39238. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39239. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39240. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39241. }
  39242. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39243. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39244. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39245. }
  39246. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39247. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39248. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39249. }
  39250. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39251. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39252. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39253. }
  39254. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39255. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39256. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39257. }
  39258. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39259. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39260. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39261. }
  39262. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39263. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39264. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39265. }
  39266. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39267. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39268. var floatIndices = [];
  39269. for (var i = 0; i < matricesIndicesData.length; i++) {
  39270. var index = matricesIndicesData[i];
  39271. floatIndices.push(index & 0x000000FF);
  39272. floatIndices.push((index & 0x0000FF00) >> 8);
  39273. floatIndices.push((index & 0x00FF0000) >> 16);
  39274. floatIndices.push(index >> 24);
  39275. }
  39276. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39277. }
  39278. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39279. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39280. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39281. }
  39282. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39283. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39284. mesh.setIndices(indicesData, null);
  39285. }
  39286. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39287. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39288. mesh.subMeshes = [];
  39289. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39290. var materialIndex = subMeshesData[(i * 5) + 0];
  39291. var verticesStart = subMeshesData[(i * 5) + 1];
  39292. var verticesCount = subMeshesData[(i * 5) + 2];
  39293. var indexStart = subMeshesData[(i * 5) + 3];
  39294. var indexCount = subMeshesData[(i * 5) + 4];
  39295. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39296. }
  39297. }
  39298. }
  39299. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39300. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39301. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39302. if (parsedGeometry.tangents) {
  39303. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39304. }
  39305. if (parsedGeometry.uvs) {
  39306. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39307. }
  39308. if (parsedGeometry.uvs2) {
  39309. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39310. }
  39311. if (parsedGeometry.uvs3) {
  39312. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39313. }
  39314. if (parsedGeometry.uvs4) {
  39315. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39316. }
  39317. if (parsedGeometry.uvs5) {
  39318. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39319. }
  39320. if (parsedGeometry.uvs6) {
  39321. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39322. }
  39323. if (parsedGeometry.colors) {
  39324. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39325. }
  39326. if (parsedGeometry.matricesIndices) {
  39327. if (!parsedGeometry.matricesIndices._isExpanded) {
  39328. var floatIndices = [];
  39329. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39330. var matricesIndex = parsedGeometry.matricesIndices[i];
  39331. floatIndices.push(matricesIndex & 0x000000FF);
  39332. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39333. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39334. floatIndices.push(matricesIndex >> 24);
  39335. }
  39336. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39337. }
  39338. else {
  39339. delete parsedGeometry.matricesIndices._isExpanded;
  39340. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39341. }
  39342. }
  39343. if (parsedGeometry.matricesIndicesExtra) {
  39344. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39345. var floatIndices = [];
  39346. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39347. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39348. floatIndices.push(matricesIndex & 0x000000FF);
  39349. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39350. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39351. floatIndices.push(matricesIndex >> 24);
  39352. }
  39353. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39354. }
  39355. else {
  39356. delete parsedGeometry.matricesIndices._isExpanded;
  39357. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39358. }
  39359. }
  39360. if (parsedGeometry.matricesWeights) {
  39361. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39362. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39363. }
  39364. if (parsedGeometry.matricesWeightsExtra) {
  39365. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39366. }
  39367. mesh.setIndices(parsedGeometry.indices, null);
  39368. }
  39369. // SubMeshes
  39370. if (parsedGeometry.subMeshes) {
  39371. mesh.subMeshes = [];
  39372. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39373. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39374. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39375. }
  39376. }
  39377. // Flat shading
  39378. if (mesh._shouldGenerateFlatShading) {
  39379. mesh.convertToFlatShadedMesh();
  39380. delete mesh._shouldGenerateFlatShading;
  39381. }
  39382. // Update
  39383. mesh.computeWorldMatrix(true);
  39384. scene.onMeshImportedObservable.notifyObservers(mesh);
  39385. };
  39386. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39387. var epsilon = 1e-3;
  39388. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39389. return;
  39390. }
  39391. var noInfluenceBoneIndex = 0.0;
  39392. if (parsedGeometry.skeletonId > -1) {
  39393. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39394. if (!skeleton) {
  39395. return;
  39396. }
  39397. noInfluenceBoneIndex = skeleton.bones.length;
  39398. }
  39399. else {
  39400. return;
  39401. }
  39402. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39403. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39404. var matricesWeights = parsedGeometry.matricesWeights;
  39405. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39406. var influencers = parsedGeometry.numBoneInfluencer;
  39407. var size = matricesWeights.length;
  39408. for (var i = 0; i < size; i += 4) {
  39409. var weight = 0.0;
  39410. var firstZeroWeight = -1;
  39411. for (var j = 0; j < 4; j++) {
  39412. var w = matricesWeights[i + j];
  39413. weight += w;
  39414. if (w < epsilon && firstZeroWeight < 0) {
  39415. firstZeroWeight = j;
  39416. }
  39417. }
  39418. if (matricesWeightsExtra) {
  39419. for (var j = 0; j < 4; j++) {
  39420. var w = matricesWeightsExtra[i + j];
  39421. weight += w;
  39422. if (w < epsilon && firstZeroWeight < 0) {
  39423. firstZeroWeight = j + 4;
  39424. }
  39425. }
  39426. }
  39427. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39428. firstZeroWeight = influencers - 1;
  39429. }
  39430. if (weight > epsilon) {
  39431. var mweight = 1.0 / weight;
  39432. for (var j = 0; j < 4; j++) {
  39433. matricesWeights[i + j] *= mweight;
  39434. }
  39435. if (matricesWeightsExtra) {
  39436. for (var j = 0; j < 4; j++) {
  39437. matricesWeightsExtra[i + j] *= mweight;
  39438. }
  39439. }
  39440. }
  39441. else {
  39442. if (firstZeroWeight >= 4) {
  39443. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39444. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39445. }
  39446. else {
  39447. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39448. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39449. }
  39450. }
  39451. }
  39452. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39453. if (parsedGeometry.matricesWeightsExtra) {
  39454. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39455. }
  39456. };
  39457. /**
  39458. * Create a new geometry from persisted data (Using .babylon file format)
  39459. * @param parsedVertexData defines the persisted data
  39460. * @param scene defines the hosting scene
  39461. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39462. * @returns the new geometry object
  39463. */
  39464. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39465. if (scene.getGeometryByID(parsedVertexData.id)) {
  39466. return null; // null since geometry could be something else than a box...
  39467. }
  39468. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39469. if (BABYLON.Tags) {
  39470. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39471. }
  39472. if (parsedVertexData.delayLoadingFile) {
  39473. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39474. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39475. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39476. geometry._delayInfo = [];
  39477. if (parsedVertexData.hasUVs) {
  39478. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39479. }
  39480. if (parsedVertexData.hasUVs2) {
  39481. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39482. }
  39483. if (parsedVertexData.hasUVs3) {
  39484. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39485. }
  39486. if (parsedVertexData.hasUVs4) {
  39487. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39488. }
  39489. if (parsedVertexData.hasUVs5) {
  39490. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39491. }
  39492. if (parsedVertexData.hasUVs6) {
  39493. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39494. }
  39495. if (parsedVertexData.hasColors) {
  39496. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39497. }
  39498. if (parsedVertexData.hasMatricesIndices) {
  39499. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39500. }
  39501. if (parsedVertexData.hasMatricesWeights) {
  39502. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39503. }
  39504. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39505. }
  39506. else {
  39507. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39508. }
  39509. scene.pushGeometry(geometry, true);
  39510. return geometry;
  39511. };
  39512. return Geometry;
  39513. }());
  39514. BABYLON.Geometry = Geometry;
  39515. // Primitives
  39516. /// Abstract class
  39517. /**
  39518. * Abstract class used to provide common services for all typed geometries
  39519. * @hidden
  39520. */
  39521. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39522. __extends(_PrimitiveGeometry, _super);
  39523. /**
  39524. * Creates a new typed geometry
  39525. * @param id defines the unique ID of the geometry
  39526. * @param scene defines the hosting scene
  39527. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39528. * @param mesh defines the hosting mesh (can be null)
  39529. */
  39530. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39531. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39532. if (mesh === void 0) { mesh = null; }
  39533. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39534. _this._canBeRegenerated = _canBeRegenerated;
  39535. _this._beingRegenerated = true;
  39536. _this.regenerate();
  39537. _this._beingRegenerated = false;
  39538. return _this;
  39539. }
  39540. /**
  39541. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39542. * @returns true if the geometry can be regenerated
  39543. */
  39544. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39545. return this._canBeRegenerated;
  39546. };
  39547. /**
  39548. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39549. */
  39550. _PrimitiveGeometry.prototype.regenerate = function () {
  39551. if (!this._canBeRegenerated) {
  39552. return;
  39553. }
  39554. this._beingRegenerated = true;
  39555. this.setAllVerticesData(this._regenerateVertexData(), false);
  39556. this._beingRegenerated = false;
  39557. };
  39558. /**
  39559. * Clone the geometry
  39560. * @param id defines the unique ID of the new geometry
  39561. * @returns the new geometry
  39562. */
  39563. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39564. return _super.prototype.copy.call(this, id);
  39565. };
  39566. // overrides
  39567. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39568. if (!this._beingRegenerated) {
  39569. return;
  39570. }
  39571. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39572. };
  39573. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39574. if (!this._beingRegenerated) {
  39575. return;
  39576. }
  39577. _super.prototype.setVerticesData.call(this, kind, data, false);
  39578. };
  39579. // to override
  39580. /** @hidden */
  39581. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39582. throw new Error("Abstract method");
  39583. };
  39584. _PrimitiveGeometry.prototype.copy = function (id) {
  39585. throw new Error("Must be overriden in sub-classes.");
  39586. };
  39587. _PrimitiveGeometry.prototype.serialize = function () {
  39588. var serializationObject = _super.prototype.serialize.call(this);
  39589. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39590. return serializationObject;
  39591. };
  39592. return _PrimitiveGeometry;
  39593. }(Geometry));
  39594. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39595. /**
  39596. * Creates a ribbon geometry
  39597. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39598. */
  39599. var RibbonGeometry = /** @class */ (function (_super) {
  39600. __extends(RibbonGeometry, _super);
  39601. /**
  39602. * Creates a ribbon geometry
  39603. * @param id defines the unique ID of the geometry
  39604. * @param scene defines the hosting scene
  39605. * @param pathArray defines the array of paths to use
  39606. * @param closeArray defines if the last path and the first path must be joined
  39607. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39608. * @param offset defines the offset between points
  39609. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39610. * @param mesh defines the hosting mesh (can be null)
  39611. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39612. */
  39613. function RibbonGeometry(id, scene,
  39614. /**
  39615. * Defines the array of paths to use
  39616. */
  39617. pathArray,
  39618. /**
  39619. * Defines if the last and first points of each path in your pathArray must be joined
  39620. */
  39621. closeArray,
  39622. /**
  39623. * Defines if the last and first points of each path in your pathArray must be joined
  39624. */
  39625. closePath,
  39626. /**
  39627. * Defines the offset between points
  39628. */
  39629. offset, canBeRegenerated, mesh,
  39630. /**
  39631. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39632. */
  39633. side) {
  39634. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39635. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39636. _this.pathArray = pathArray;
  39637. _this.closeArray = closeArray;
  39638. _this.closePath = closePath;
  39639. _this.offset = offset;
  39640. _this.side = side;
  39641. return _this;
  39642. }
  39643. /** @hidden */
  39644. RibbonGeometry.prototype._regenerateVertexData = function () {
  39645. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39646. };
  39647. RibbonGeometry.prototype.copy = function (id) {
  39648. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39649. };
  39650. return RibbonGeometry;
  39651. }(_PrimitiveGeometry));
  39652. BABYLON.RibbonGeometry = RibbonGeometry;
  39653. /**
  39654. * Creates a box geometry
  39655. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39656. */
  39657. var BoxGeometry = /** @class */ (function (_super) {
  39658. __extends(BoxGeometry, _super);
  39659. /**
  39660. * Creates a box geometry
  39661. * @param id defines the unique ID of the geometry
  39662. * @param scene defines the hosting scene
  39663. * @param size defines the zise of the box (width, height and depth are the same)
  39664. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39665. * @param mesh defines the hosting mesh (can be null)
  39666. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39667. */
  39668. function BoxGeometry(id, scene,
  39669. /**
  39670. * Defines the zise of the box (width, height and depth are the same)
  39671. */
  39672. size, canBeRegenerated, mesh,
  39673. /**
  39674. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39675. */
  39676. side) {
  39677. if (mesh === void 0) { mesh = null; }
  39678. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39679. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39680. _this.size = size;
  39681. _this.side = side;
  39682. return _this;
  39683. }
  39684. /** @hidden */
  39685. BoxGeometry.prototype._regenerateVertexData = function () {
  39686. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39687. };
  39688. BoxGeometry.prototype.copy = function (id) {
  39689. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39690. };
  39691. BoxGeometry.prototype.serialize = function () {
  39692. var serializationObject = _super.prototype.serialize.call(this);
  39693. serializationObject.size = this.size;
  39694. return serializationObject;
  39695. };
  39696. BoxGeometry.Parse = function (parsedBox, scene) {
  39697. if (scene.getGeometryByID(parsedBox.id)) {
  39698. return null; // null since geometry could be something else than a box...
  39699. }
  39700. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39701. if (BABYLON.Tags) {
  39702. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39703. }
  39704. scene.pushGeometry(box, true);
  39705. return box;
  39706. };
  39707. return BoxGeometry;
  39708. }(_PrimitiveGeometry));
  39709. BABYLON.BoxGeometry = BoxGeometry;
  39710. /**
  39711. * Creates a sphere geometry
  39712. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39713. */
  39714. var SphereGeometry = /** @class */ (function (_super) {
  39715. __extends(SphereGeometry, _super);
  39716. /**
  39717. * Create a new sphere geometry
  39718. * @param id defines the unique ID of the geometry
  39719. * @param scene defines the hosting scene
  39720. * @param segments defines the number of segments to use to create the sphere
  39721. * @param diameter defines the diameter of the sphere
  39722. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39723. * @param mesh defines the hosting mesh (can be null)
  39724. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39725. */
  39726. function SphereGeometry(id, scene,
  39727. /**
  39728. * Defines the number of segments to use to create the sphere
  39729. */
  39730. segments,
  39731. /**
  39732. * Defines the diameter of the sphere
  39733. */
  39734. diameter, canBeRegenerated, mesh,
  39735. /**
  39736. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39737. */
  39738. side) {
  39739. if (mesh === void 0) { mesh = null; }
  39740. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39741. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39742. _this.segments = segments;
  39743. _this.diameter = diameter;
  39744. _this.side = side;
  39745. return _this;
  39746. }
  39747. /** @hidden */
  39748. SphereGeometry.prototype._regenerateVertexData = function () {
  39749. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39750. };
  39751. SphereGeometry.prototype.copy = function (id) {
  39752. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39753. };
  39754. SphereGeometry.prototype.serialize = function () {
  39755. var serializationObject = _super.prototype.serialize.call(this);
  39756. serializationObject.segments = this.segments;
  39757. serializationObject.diameter = this.diameter;
  39758. return serializationObject;
  39759. };
  39760. SphereGeometry.Parse = function (parsedSphere, scene) {
  39761. if (scene.getGeometryByID(parsedSphere.id)) {
  39762. return null; // null since geometry could be something else than a sphere...
  39763. }
  39764. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39765. if (BABYLON.Tags) {
  39766. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39767. }
  39768. scene.pushGeometry(sphere, true);
  39769. return sphere;
  39770. };
  39771. return SphereGeometry;
  39772. }(_PrimitiveGeometry));
  39773. BABYLON.SphereGeometry = SphereGeometry;
  39774. /**
  39775. * Creates a disc geometry
  39776. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39777. */
  39778. var DiscGeometry = /** @class */ (function (_super) {
  39779. __extends(DiscGeometry, _super);
  39780. /**
  39781. * Creates a new disc geometry
  39782. * @param id defines the unique ID of the geometry
  39783. * @param scene defines the hosting scene
  39784. * @param radius defines the radius of the disc
  39785. * @param tessellation defines the tesselation factor to apply to the disc
  39786. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39787. * @param mesh defines the hosting mesh (can be null)
  39788. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39789. */
  39790. function DiscGeometry(id, scene,
  39791. /**
  39792. * Defines the radius of the disc
  39793. */
  39794. radius,
  39795. /**
  39796. * Defines the tesselation factor to apply to the disc
  39797. */
  39798. tessellation, canBeRegenerated, mesh,
  39799. /**
  39800. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39801. */
  39802. side) {
  39803. if (mesh === void 0) { mesh = null; }
  39804. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39805. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39806. _this.radius = radius;
  39807. _this.tessellation = tessellation;
  39808. _this.side = side;
  39809. return _this;
  39810. }
  39811. /** @hidden */
  39812. DiscGeometry.prototype._regenerateVertexData = function () {
  39813. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39814. };
  39815. DiscGeometry.prototype.copy = function (id) {
  39816. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39817. };
  39818. return DiscGeometry;
  39819. }(_PrimitiveGeometry));
  39820. BABYLON.DiscGeometry = DiscGeometry;
  39821. /**
  39822. * Creates a new cylinder geometry
  39823. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39824. */
  39825. var CylinderGeometry = /** @class */ (function (_super) {
  39826. __extends(CylinderGeometry, _super);
  39827. /**
  39828. * Creates a new cylinder geometry
  39829. * @param id defines the unique ID of the geometry
  39830. * @param scene defines the hosting scene
  39831. * @param height defines the height of the cylinder
  39832. * @param diameterTop defines the diameter of the cylinder's top cap
  39833. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39834. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39835. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39836. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39837. * @param mesh defines the hosting mesh (can be null)
  39838. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39839. */
  39840. function CylinderGeometry(id, scene,
  39841. /**
  39842. * Defines the height of the cylinder
  39843. */
  39844. height,
  39845. /**
  39846. * Defines the diameter of the cylinder's top cap
  39847. */
  39848. diameterTop,
  39849. /**
  39850. * Defines the diameter of the cylinder's bottom cap
  39851. */
  39852. diameterBottom,
  39853. /**
  39854. * Defines the tessellation factor to apply to the cylinder
  39855. */
  39856. tessellation,
  39857. /**
  39858. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39859. */
  39860. subdivisions, canBeRegenerated, mesh,
  39861. /**
  39862. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39863. */
  39864. side) {
  39865. if (subdivisions === void 0) { subdivisions = 1; }
  39866. if (mesh === void 0) { mesh = null; }
  39867. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39868. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39869. _this.height = height;
  39870. _this.diameterTop = diameterTop;
  39871. _this.diameterBottom = diameterBottom;
  39872. _this.tessellation = tessellation;
  39873. _this.subdivisions = subdivisions;
  39874. _this.side = side;
  39875. return _this;
  39876. }
  39877. /** @hidden */
  39878. CylinderGeometry.prototype._regenerateVertexData = function () {
  39879. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39880. };
  39881. CylinderGeometry.prototype.copy = function (id) {
  39882. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39883. };
  39884. CylinderGeometry.prototype.serialize = function () {
  39885. var serializationObject = _super.prototype.serialize.call(this);
  39886. serializationObject.height = this.height;
  39887. serializationObject.diameterTop = this.diameterTop;
  39888. serializationObject.diameterBottom = this.diameterBottom;
  39889. serializationObject.tessellation = this.tessellation;
  39890. return serializationObject;
  39891. };
  39892. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39893. if (scene.getGeometryByID(parsedCylinder.id)) {
  39894. return null; // null since geometry could be something else than a cylinder...
  39895. }
  39896. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39897. if (BABYLON.Tags) {
  39898. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39899. }
  39900. scene.pushGeometry(cylinder, true);
  39901. return cylinder;
  39902. };
  39903. return CylinderGeometry;
  39904. }(_PrimitiveGeometry));
  39905. BABYLON.CylinderGeometry = CylinderGeometry;
  39906. /**
  39907. * Creates a new torus geometry
  39908. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39909. */
  39910. var TorusGeometry = /** @class */ (function (_super) {
  39911. __extends(TorusGeometry, _super);
  39912. /**
  39913. * Creates a new torus geometry
  39914. * @param id defines the unique ID of the geometry
  39915. * @param scene defines the hosting scene
  39916. * @param diameter defines the diameter of the torus
  39917. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39918. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39919. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39920. * @param mesh defines the hosting mesh (can be null)
  39921. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39922. */
  39923. function TorusGeometry(id, scene,
  39924. /**
  39925. * Defines the diameter of the torus
  39926. */
  39927. diameter,
  39928. /**
  39929. * Defines the thickness of the torus (ie. internal diameter)
  39930. */
  39931. thickness,
  39932. /**
  39933. * Defines the tesselation factor to apply to the torus
  39934. */
  39935. tessellation, canBeRegenerated, mesh,
  39936. /**
  39937. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39938. */
  39939. side) {
  39940. if (mesh === void 0) { mesh = null; }
  39941. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39942. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39943. _this.diameter = diameter;
  39944. _this.thickness = thickness;
  39945. _this.tessellation = tessellation;
  39946. _this.side = side;
  39947. return _this;
  39948. }
  39949. /** @hidden */
  39950. TorusGeometry.prototype._regenerateVertexData = function () {
  39951. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39952. };
  39953. TorusGeometry.prototype.copy = function (id) {
  39954. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39955. };
  39956. TorusGeometry.prototype.serialize = function () {
  39957. var serializationObject = _super.prototype.serialize.call(this);
  39958. serializationObject.diameter = this.diameter;
  39959. serializationObject.thickness = this.thickness;
  39960. serializationObject.tessellation = this.tessellation;
  39961. return serializationObject;
  39962. };
  39963. TorusGeometry.Parse = function (parsedTorus, scene) {
  39964. if (scene.getGeometryByID(parsedTorus.id)) {
  39965. return null; // null since geometry could be something else than a torus...
  39966. }
  39967. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39968. if (BABYLON.Tags) {
  39969. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39970. }
  39971. scene.pushGeometry(torus, true);
  39972. return torus;
  39973. };
  39974. return TorusGeometry;
  39975. }(_PrimitiveGeometry));
  39976. BABYLON.TorusGeometry = TorusGeometry;
  39977. /**
  39978. * Creates a new ground geometry
  39979. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39980. */
  39981. var GroundGeometry = /** @class */ (function (_super) {
  39982. __extends(GroundGeometry, _super);
  39983. /**
  39984. * Creates a new ground geometry
  39985. * @param id defines the unique ID of the geometry
  39986. * @param scene defines the hosting scene
  39987. * @param width defines the width of the ground
  39988. * @param height defines the height of the ground
  39989. * @param subdivisions defines the subdivisions to apply to the ground
  39990. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39991. * @param mesh defines the hosting mesh (can be null)
  39992. */
  39993. function GroundGeometry(id, scene,
  39994. /**
  39995. * Defines the width of the ground
  39996. */
  39997. width,
  39998. /**
  39999. * Defines the height of the ground
  40000. */
  40001. height,
  40002. /**
  40003. * Defines the subdivisions to apply to the ground
  40004. */
  40005. subdivisions, canBeRegenerated, mesh) {
  40006. if (mesh === void 0) { mesh = null; }
  40007. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40008. _this.width = width;
  40009. _this.height = height;
  40010. _this.subdivisions = subdivisions;
  40011. return _this;
  40012. }
  40013. /** @hidden */
  40014. GroundGeometry.prototype._regenerateVertexData = function () {
  40015. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40016. };
  40017. GroundGeometry.prototype.copy = function (id) {
  40018. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40019. };
  40020. GroundGeometry.prototype.serialize = function () {
  40021. var serializationObject = _super.prototype.serialize.call(this);
  40022. serializationObject.width = this.width;
  40023. serializationObject.height = this.height;
  40024. serializationObject.subdivisions = this.subdivisions;
  40025. return serializationObject;
  40026. };
  40027. GroundGeometry.Parse = function (parsedGround, scene) {
  40028. if (scene.getGeometryByID(parsedGround.id)) {
  40029. return null; // null since geometry could be something else than a ground...
  40030. }
  40031. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40032. if (BABYLON.Tags) {
  40033. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40034. }
  40035. scene.pushGeometry(ground, true);
  40036. return ground;
  40037. };
  40038. return GroundGeometry;
  40039. }(_PrimitiveGeometry));
  40040. BABYLON.GroundGeometry = GroundGeometry;
  40041. /**
  40042. * Creates a tiled ground geometry
  40043. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40044. */
  40045. var TiledGroundGeometry = /** @class */ (function (_super) {
  40046. __extends(TiledGroundGeometry, _super);
  40047. /**
  40048. * Creates a tiled ground geometry
  40049. * @param id defines the unique ID of the geometry
  40050. * @param scene defines the hosting scene
  40051. * @param xmin defines the minimum value on X axis
  40052. * @param zmin defines the minimum value on Z axis
  40053. * @param xmax defines the maximum value on X axis
  40054. * @param zmax defines the maximum value on Z axis
  40055. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40056. * @param precision defines the precision to use when computing the tiles
  40057. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40058. * @param mesh defines the hosting mesh (can be null)
  40059. */
  40060. function TiledGroundGeometry(id, scene,
  40061. /**
  40062. * Defines the minimum value on X axis
  40063. */
  40064. xmin,
  40065. /**
  40066. * Defines the minimum value on Z axis
  40067. */
  40068. zmin,
  40069. /**
  40070. * Defines the maximum value on X axis
  40071. */
  40072. xmax,
  40073. /**
  40074. * Defines the maximum value on Z axis
  40075. */
  40076. zmax,
  40077. /**
  40078. * Defines the subdivisions to apply to the ground
  40079. */
  40080. subdivisions,
  40081. /**
  40082. * Defines the precision to use when computing the tiles
  40083. */
  40084. precision, canBeRegenerated, mesh) {
  40085. if (mesh === void 0) { mesh = null; }
  40086. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40087. _this.xmin = xmin;
  40088. _this.zmin = zmin;
  40089. _this.xmax = xmax;
  40090. _this.zmax = zmax;
  40091. _this.subdivisions = subdivisions;
  40092. _this.precision = precision;
  40093. return _this;
  40094. }
  40095. /** @hidden */
  40096. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40097. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40098. };
  40099. TiledGroundGeometry.prototype.copy = function (id) {
  40100. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40101. };
  40102. return TiledGroundGeometry;
  40103. }(_PrimitiveGeometry));
  40104. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40105. /**
  40106. * Creates a plane geometry
  40107. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40108. */
  40109. var PlaneGeometry = /** @class */ (function (_super) {
  40110. __extends(PlaneGeometry, _super);
  40111. /**
  40112. * Creates a plane geometry
  40113. * @param id defines the unique ID of the geometry
  40114. * @param scene defines the hosting scene
  40115. * @param size defines the size of the plane (width === height)
  40116. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40117. * @param mesh defines the hosting mesh (can be null)
  40118. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40119. */
  40120. function PlaneGeometry(id, scene,
  40121. /**
  40122. * Defines the size of the plane (width === height)
  40123. */
  40124. size, canBeRegenerated, mesh,
  40125. /**
  40126. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40127. */
  40128. side) {
  40129. if (mesh === void 0) { mesh = null; }
  40130. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40131. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40132. _this.size = size;
  40133. _this.side = side;
  40134. return _this;
  40135. }
  40136. /** @hidden */
  40137. PlaneGeometry.prototype._regenerateVertexData = function () {
  40138. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40139. };
  40140. PlaneGeometry.prototype.copy = function (id) {
  40141. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40142. };
  40143. PlaneGeometry.prototype.serialize = function () {
  40144. var serializationObject = _super.prototype.serialize.call(this);
  40145. serializationObject.size = this.size;
  40146. return serializationObject;
  40147. };
  40148. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40149. if (scene.getGeometryByID(parsedPlane.id)) {
  40150. return null; // null since geometry could be something else than a ground...
  40151. }
  40152. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40153. if (BABYLON.Tags) {
  40154. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40155. }
  40156. scene.pushGeometry(plane, true);
  40157. return plane;
  40158. };
  40159. return PlaneGeometry;
  40160. }(_PrimitiveGeometry));
  40161. BABYLON.PlaneGeometry = PlaneGeometry;
  40162. /**
  40163. * Creates a torus knot geometry
  40164. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40165. */
  40166. var TorusKnotGeometry = /** @class */ (function (_super) {
  40167. __extends(TorusKnotGeometry, _super);
  40168. /**
  40169. * Creates a torus knot geometry
  40170. * @param id defines the unique ID of the geometry
  40171. * @param scene defines the hosting scene
  40172. * @param radius defines the radius of the torus knot
  40173. * @param tube defines the thickness of the torus knot tube
  40174. * @param radialSegments defines the number of radial segments
  40175. * @param tubularSegments defines the number of tubular segments
  40176. * @param p defines the first number of windings
  40177. * @param q defines the second number of windings
  40178. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40179. * @param mesh defines the hosting mesh (can be null)
  40180. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40181. */
  40182. function TorusKnotGeometry(id, scene,
  40183. /**
  40184. * Defines the radius of the torus knot
  40185. */
  40186. radius,
  40187. /**
  40188. * Defines the thickness of the torus knot tube
  40189. */
  40190. tube,
  40191. /**
  40192. * Defines the number of radial segments
  40193. */
  40194. radialSegments,
  40195. /**
  40196. * Defines the number of tubular segments
  40197. */
  40198. tubularSegments,
  40199. /**
  40200. * Defines the first number of windings
  40201. */
  40202. p,
  40203. /**
  40204. * Defines the second number of windings
  40205. */
  40206. q, canBeRegenerated, mesh,
  40207. /**
  40208. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40209. */
  40210. side) {
  40211. if (mesh === void 0) { mesh = null; }
  40212. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40213. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40214. _this.radius = radius;
  40215. _this.tube = tube;
  40216. _this.radialSegments = radialSegments;
  40217. _this.tubularSegments = tubularSegments;
  40218. _this.p = p;
  40219. _this.q = q;
  40220. _this.side = side;
  40221. return _this;
  40222. }
  40223. /** @hidden */
  40224. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40225. 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 });
  40226. };
  40227. TorusKnotGeometry.prototype.copy = function (id) {
  40228. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40229. };
  40230. TorusKnotGeometry.prototype.serialize = function () {
  40231. var serializationObject = _super.prototype.serialize.call(this);
  40232. serializationObject.radius = this.radius;
  40233. serializationObject.tube = this.tube;
  40234. serializationObject.radialSegments = this.radialSegments;
  40235. serializationObject.tubularSegments = this.tubularSegments;
  40236. serializationObject.p = this.p;
  40237. serializationObject.q = this.q;
  40238. return serializationObject;
  40239. };
  40240. ;
  40241. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40242. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40243. return null; // null since geometry could be something else than a ground...
  40244. }
  40245. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40246. if (BABYLON.Tags) {
  40247. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40248. }
  40249. scene.pushGeometry(torusKnot, true);
  40250. return torusKnot;
  40251. };
  40252. return TorusKnotGeometry;
  40253. }(_PrimitiveGeometry));
  40254. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40255. //}
  40256. })(BABYLON || (BABYLON = {}));
  40257. //# sourceMappingURL=babylon.geometry.js.map
  40258. var BABYLON;
  40259. (function (BABYLON) {
  40260. /**
  40261. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40262. */
  40263. var PerformanceMonitor = /** @class */ (function () {
  40264. /**
  40265. * constructor
  40266. * @param frameSampleSize The number of samples required to saturate the sliding window
  40267. */
  40268. function PerformanceMonitor(frameSampleSize) {
  40269. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40270. this._enabled = true;
  40271. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40272. }
  40273. /**
  40274. * Samples current frame
  40275. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40276. */
  40277. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40278. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40279. if (!this._enabled)
  40280. return;
  40281. if (this._lastFrameTimeMs != null) {
  40282. var dt = timeMs - this._lastFrameTimeMs;
  40283. this._rollingFrameTime.add(dt);
  40284. }
  40285. this._lastFrameTimeMs = timeMs;
  40286. };
  40287. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40288. /**
  40289. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40290. * @return Average frame time in milliseconds
  40291. */
  40292. get: function () {
  40293. return this._rollingFrameTime.average;
  40294. },
  40295. enumerable: true,
  40296. configurable: true
  40297. });
  40298. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40299. /**
  40300. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40301. * @return Frame time variance in milliseconds squared
  40302. */
  40303. get: function () {
  40304. return this._rollingFrameTime.variance;
  40305. },
  40306. enumerable: true,
  40307. configurable: true
  40308. });
  40309. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40310. /**
  40311. * Returns the frame time of the most recent frame
  40312. * @return Frame time in milliseconds
  40313. */
  40314. get: function () {
  40315. return this._rollingFrameTime.history(0);
  40316. },
  40317. enumerable: true,
  40318. configurable: true
  40319. });
  40320. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40321. /**
  40322. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40323. * @return Framerate in frames per second
  40324. */
  40325. get: function () {
  40326. return 1000.0 / this._rollingFrameTime.average;
  40327. },
  40328. enumerable: true,
  40329. configurable: true
  40330. });
  40331. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40332. /**
  40333. * Returns the average framerate in frames per second using the most recent frame time
  40334. * @return Framerate in frames per second
  40335. */
  40336. get: function () {
  40337. var history = this._rollingFrameTime.history(0);
  40338. if (history === 0) {
  40339. return 0;
  40340. }
  40341. return 1000.0 / history;
  40342. },
  40343. enumerable: true,
  40344. configurable: true
  40345. });
  40346. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40347. /**
  40348. * Returns true if enough samples have been taken to completely fill the sliding window
  40349. * @return true if saturated
  40350. */
  40351. get: function () {
  40352. return this._rollingFrameTime.isSaturated();
  40353. },
  40354. enumerable: true,
  40355. configurable: true
  40356. });
  40357. /**
  40358. * Enables contributions to the sliding window sample set
  40359. */
  40360. PerformanceMonitor.prototype.enable = function () {
  40361. this._enabled = true;
  40362. };
  40363. /**
  40364. * Disables contributions to the sliding window sample set
  40365. * Samples will not be interpolated over the disabled period
  40366. */
  40367. PerformanceMonitor.prototype.disable = function () {
  40368. this._enabled = false;
  40369. //clear last sample to avoid interpolating over the disabled period when next enabled
  40370. this._lastFrameTimeMs = null;
  40371. };
  40372. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40373. /**
  40374. * Returns true if sampling is enabled
  40375. * @return true if enabled
  40376. */
  40377. get: function () {
  40378. return this._enabled;
  40379. },
  40380. enumerable: true,
  40381. configurable: true
  40382. });
  40383. /**
  40384. * Resets performance monitor
  40385. */
  40386. PerformanceMonitor.prototype.reset = function () {
  40387. //clear last sample to avoid interpolating over the disabled period when next enabled
  40388. this._lastFrameTimeMs = null;
  40389. //wipe record
  40390. this._rollingFrameTime.reset();
  40391. };
  40392. return PerformanceMonitor;
  40393. }());
  40394. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40395. /**
  40396. * RollingAverage
  40397. *
  40398. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40399. */
  40400. var RollingAverage = /** @class */ (function () {
  40401. /**
  40402. * constructor
  40403. * @param length The number of samples required to saturate the sliding window
  40404. */
  40405. function RollingAverage(length) {
  40406. this._samples = new Array(length);
  40407. this.reset();
  40408. }
  40409. /**
  40410. * Adds a sample to the sample set
  40411. * @param v The sample value
  40412. */
  40413. RollingAverage.prototype.add = function (v) {
  40414. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40415. var delta;
  40416. //we need to check if we've already wrapped round
  40417. if (this.isSaturated()) {
  40418. //remove bottom of stack from mean
  40419. var bottomValue = this._samples[this._pos];
  40420. delta = bottomValue - this.average;
  40421. this.average -= delta / (this._sampleCount - 1);
  40422. this._m2 -= delta * (bottomValue - this.average);
  40423. }
  40424. else {
  40425. this._sampleCount++;
  40426. }
  40427. //add new value to mean
  40428. delta = v - this.average;
  40429. this.average += delta / (this._sampleCount);
  40430. this._m2 += delta * (v - this.average);
  40431. //set the new variance
  40432. this.variance = this._m2 / (this._sampleCount - 1);
  40433. this._samples[this._pos] = v;
  40434. this._pos++;
  40435. this._pos %= this._samples.length; //positive wrap around
  40436. };
  40437. /**
  40438. * Returns previously added values or null if outside of history or outside the sliding window domain
  40439. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40440. * @return Value previously recorded with add() or null if outside of range
  40441. */
  40442. RollingAverage.prototype.history = function (i) {
  40443. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40444. return 0;
  40445. }
  40446. var i0 = this._wrapPosition(this._pos - 1.0);
  40447. return this._samples[this._wrapPosition(i0 - i)];
  40448. };
  40449. /**
  40450. * Returns true if enough samples have been taken to completely fill the sliding window
  40451. * @return true if sample-set saturated
  40452. */
  40453. RollingAverage.prototype.isSaturated = function () {
  40454. return this._sampleCount >= this._samples.length;
  40455. };
  40456. /**
  40457. * Resets the rolling average (equivalent to 0 samples taken so far)
  40458. */
  40459. RollingAverage.prototype.reset = function () {
  40460. this.average = 0;
  40461. this.variance = 0;
  40462. this._sampleCount = 0;
  40463. this._pos = 0;
  40464. this._m2 = 0;
  40465. };
  40466. /**
  40467. * Wraps a value around the sample range boundaries
  40468. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40469. * @return Wrapped position in sample range
  40470. */
  40471. RollingAverage.prototype._wrapPosition = function (i) {
  40472. var max = this._samples.length;
  40473. return ((i % max) + max) % max;
  40474. };
  40475. return RollingAverage;
  40476. }());
  40477. BABYLON.RollingAverage = RollingAverage;
  40478. })(BABYLON || (BABYLON = {}));
  40479. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40480. var BABYLON;
  40481. (function (BABYLON) {
  40482. /**
  40483. * "Static Class" containing the most commonly used helper while dealing with material for
  40484. * rendering purpose.
  40485. *
  40486. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40487. *
  40488. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40489. */
  40490. var MaterialHelper = /** @class */ (function () {
  40491. function MaterialHelper() {
  40492. }
  40493. /**
  40494. * Bind the current view position to an effect.
  40495. * @param effect The effect to be bound
  40496. * @param scene The scene the eyes position is used from
  40497. */
  40498. MaterialHelper.BindEyePosition = function (effect, scene) {
  40499. if (scene._forcedViewPosition) {
  40500. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40501. return;
  40502. }
  40503. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40504. };
  40505. /**
  40506. * Helps preparing the defines values about the UVs in used in the effect.
  40507. * UVs are shared as much as we can accross chanels in the shaders.
  40508. * @param texture The texture we are preparing the UVs for
  40509. * @param defines The defines to update
  40510. * @param key The chanel key "diffuse", "specular"... used in the shader
  40511. */
  40512. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40513. defines._needUVs = true;
  40514. defines[key] = true;
  40515. if (texture.getTextureMatrix().isIdentity(true)) {
  40516. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40517. if (texture.coordinatesIndex === 0) {
  40518. defines["MAINUV1"] = true;
  40519. }
  40520. else {
  40521. defines["MAINUV2"] = true;
  40522. }
  40523. }
  40524. else {
  40525. defines[key + "DIRECTUV"] = 0;
  40526. }
  40527. };
  40528. /**
  40529. * Binds a texture matrix value to its corrsponding uniform
  40530. * @param texture The texture to bind the matrix for
  40531. * @param uniformBuffer The uniform buffer receivin the data
  40532. * @param key The chanel key "diffuse", "specular"... used in the shader
  40533. */
  40534. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40535. var matrix = texture.getTextureMatrix();
  40536. if (!matrix.isIdentity(true)) {
  40537. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40538. }
  40539. };
  40540. /**
  40541. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40542. * @param mesh defines the current mesh
  40543. * @param scene defines the current scene
  40544. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40545. * @param pointsCloud defines if point cloud rendering has to be turned on
  40546. * @param fogEnabled defines if fog has to be turned on
  40547. * @param alphaTest defines if alpha testing has to be turned on
  40548. * @param defines defines the current list of defines
  40549. */
  40550. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40551. if (defines._areMiscDirty) {
  40552. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40553. defines["POINTSIZE"] = pointsCloud;
  40554. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40555. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40556. defines["ALPHATEST"] = alphaTest;
  40557. }
  40558. };
  40559. /**
  40560. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40561. * @param scene defines the current scene
  40562. * @param engine defines the current engine
  40563. * @param defines specifies the list of active defines
  40564. * @param useInstances defines if instances have to be turned on
  40565. * @param useClipPlane defines if clip plane have to be turned on
  40566. */
  40567. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40568. if (useClipPlane === void 0) { useClipPlane = null; }
  40569. var changed = false;
  40570. var useClipPlane1 = false;
  40571. var useClipPlane2 = false;
  40572. var useClipPlane3 = false;
  40573. var useClipPlane4 = false;
  40574. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40575. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40576. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40577. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40578. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40579. defines["CLIPPLANE"] = useClipPlane1;
  40580. changed = true;
  40581. }
  40582. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40583. defines["CLIPPLANE2"] = useClipPlane2;
  40584. changed = true;
  40585. }
  40586. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40587. defines["CLIPPLANE3"] = useClipPlane3;
  40588. changed = true;
  40589. }
  40590. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40591. defines["CLIPPLANE4"] = useClipPlane4;
  40592. changed = true;
  40593. }
  40594. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40595. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40596. changed = true;
  40597. }
  40598. if (defines["INSTANCES"] !== useInstances) {
  40599. defines["INSTANCES"] = useInstances;
  40600. changed = true;
  40601. }
  40602. if (changed) {
  40603. defines.markAsUnprocessed();
  40604. }
  40605. };
  40606. /**
  40607. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40608. * @param mesh The mesh containing the geometry data we will draw
  40609. * @param defines The defines to update
  40610. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40611. * @param useBones Precise whether bones should be used or not (override mesh info)
  40612. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40613. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40614. * @returns false if defines are considered not dirty and have not been checked
  40615. */
  40616. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40617. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40618. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40619. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40620. return false;
  40621. }
  40622. defines._normals = defines._needNormals;
  40623. defines._uvs = defines._needUVs;
  40624. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40625. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40626. defines["TANGENT"] = true;
  40627. }
  40628. if (defines._needUVs) {
  40629. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40630. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40631. }
  40632. else {
  40633. defines["UV1"] = false;
  40634. defines["UV2"] = false;
  40635. }
  40636. if (useVertexColor) {
  40637. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40638. defines["VERTEXCOLOR"] = hasVertexColors;
  40639. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40640. }
  40641. if (useBones) {
  40642. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40643. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40644. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40645. }
  40646. else {
  40647. defines["NUM_BONE_INFLUENCERS"] = 0;
  40648. defines["BonesPerMesh"] = 0;
  40649. }
  40650. }
  40651. if (useMorphTargets) {
  40652. var manager = mesh.morphTargetManager;
  40653. if (manager) {
  40654. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40655. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40656. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40657. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40658. }
  40659. else {
  40660. defines["MORPHTARGETS_TANGENT"] = false;
  40661. defines["MORPHTARGETS_NORMAL"] = false;
  40662. defines["MORPHTARGETS"] = false;
  40663. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40664. }
  40665. }
  40666. return true;
  40667. };
  40668. /**
  40669. * Prepares the defines related to the light information passed in parameter
  40670. * @param scene The scene we are intending to draw
  40671. * @param mesh The mesh the effect is compiling for
  40672. * @param defines The defines to update
  40673. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40674. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40675. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40676. * @returns true if normals will be required for the rest of the effect
  40677. */
  40678. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40679. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40680. if (disableLighting === void 0) { disableLighting = false; }
  40681. if (!defines._areLightsDirty) {
  40682. return defines._needNormals;
  40683. }
  40684. var lightIndex = 0;
  40685. var needNormals = false;
  40686. var needRebuild = false;
  40687. var lightmapMode = false;
  40688. var shadowEnabled = false;
  40689. var specularEnabled = false;
  40690. if (scene.lightsEnabled && !disableLighting) {
  40691. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40692. var light = _a[_i];
  40693. needNormals = true;
  40694. if (defines["LIGHT" + lightIndex] === undefined) {
  40695. needRebuild = true;
  40696. }
  40697. defines["LIGHT" + lightIndex] = true;
  40698. defines["SPOTLIGHT" + lightIndex] = false;
  40699. defines["HEMILIGHT" + lightIndex] = false;
  40700. defines["POINTLIGHT" + lightIndex] = false;
  40701. defines["DIRLIGHT" + lightIndex] = false;
  40702. light.prepareLightSpecificDefines(defines, lightIndex);
  40703. // FallOff.
  40704. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  40705. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  40706. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  40707. switch (light.falloffType) {
  40708. case BABYLON.Light.FALLOFF_GLTF:
  40709. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  40710. break;
  40711. case BABYLON.Light.FALLOFF_PHYSICAL:
  40712. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  40713. break;
  40714. case BABYLON.Light.FALLOFF_STANDARD:
  40715. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  40716. break;
  40717. }
  40718. // Specular
  40719. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40720. specularEnabled = true;
  40721. }
  40722. // Shadows
  40723. defines["SHADOW" + lightIndex] = false;
  40724. defines["SHADOWPCF" + lightIndex] = false;
  40725. defines["SHADOWPCSS" + lightIndex] = false;
  40726. defines["SHADOWPOISSON" + lightIndex] = false;
  40727. defines["SHADOWESM" + lightIndex] = false;
  40728. defines["SHADOWCUBE" + lightIndex] = false;
  40729. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40730. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40731. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40732. var shadowGenerator = light.getShadowGenerator();
  40733. if (shadowGenerator) {
  40734. var shadowMap = shadowGenerator.getShadowMap();
  40735. if (shadowMap) {
  40736. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40737. shadowEnabled = true;
  40738. shadowGenerator.prepareDefines(defines, lightIndex);
  40739. }
  40740. }
  40741. }
  40742. }
  40743. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40744. lightmapMode = true;
  40745. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40746. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40747. }
  40748. else {
  40749. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40750. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40751. }
  40752. lightIndex++;
  40753. if (lightIndex === maxSimultaneousLights)
  40754. break;
  40755. }
  40756. }
  40757. defines["SPECULARTERM"] = specularEnabled;
  40758. defines["SHADOWS"] = shadowEnabled;
  40759. // Resetting all other lights if any
  40760. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40761. if (defines["LIGHT" + index] !== undefined) {
  40762. defines["LIGHT" + index] = false;
  40763. defines["HEMILIGHT" + lightIndex] = false;
  40764. defines["POINTLIGHT" + lightIndex] = false;
  40765. defines["DIRLIGHT" + lightIndex] = false;
  40766. defines["SPOTLIGHT" + lightIndex] = false;
  40767. defines["SHADOW" + lightIndex] = false;
  40768. }
  40769. }
  40770. var caps = scene.getEngine().getCaps();
  40771. if (defines["SHADOWFLOAT"] === undefined) {
  40772. needRebuild = true;
  40773. }
  40774. defines["SHADOWFLOAT"] = shadowEnabled &&
  40775. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40776. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40777. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40778. if (needRebuild) {
  40779. defines.rebuild();
  40780. }
  40781. return needNormals;
  40782. };
  40783. /**
  40784. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40785. * that won t be acctive due to defines being turned off.
  40786. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  40787. * @param samplersList The samplers list
  40788. * @param defines The defines helping in the list generation
  40789. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  40790. */
  40791. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  40792. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40793. var uniformsList;
  40794. var uniformBuffersList = null;
  40795. if (uniformsListOrOptions.uniformsNames) {
  40796. var options = uniformsListOrOptions;
  40797. uniformsList = options.uniformsNames;
  40798. uniformBuffersList = options.uniformBuffersNames;
  40799. samplersList = options.samplers;
  40800. defines = options.defines;
  40801. maxSimultaneousLights = options.maxSimultaneousLights;
  40802. }
  40803. else {
  40804. uniformsList = uniformsListOrOptions;
  40805. if (!samplersList) {
  40806. samplersList = [];
  40807. }
  40808. }
  40809. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40810. if (!defines["LIGHT" + lightIndex]) {
  40811. break;
  40812. }
  40813. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  40814. if (uniformBuffersList) {
  40815. uniformBuffersList.push("Light" + lightIndex);
  40816. }
  40817. samplersList.push("shadowSampler" + lightIndex);
  40818. samplersList.push("depthSampler" + lightIndex);
  40819. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  40820. samplersList.push("projectionLightSampler" + lightIndex);
  40821. uniformsList.push("textureProjectionMatrix" + lightIndex);
  40822. }
  40823. }
  40824. if (defines["NUM_MORPH_INFLUENCERS"]) {
  40825. uniformsList.push("morphTargetInfluences");
  40826. }
  40827. };
  40828. /**
  40829. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  40830. * @param defines The defines to update while falling back
  40831. * @param fallbacks The authorized effect fallbacks
  40832. * @param maxSimultaneousLights The maximum number of lights allowed
  40833. * @param rank the current rank of the Effect
  40834. * @returns The newly affected rank
  40835. */
  40836. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  40837. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40838. if (rank === void 0) { rank = 0; }
  40839. var lightFallbackRank = 0;
  40840. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40841. if (!defines["LIGHT" + lightIndex]) {
  40842. break;
  40843. }
  40844. if (lightIndex > 0) {
  40845. lightFallbackRank = rank + lightIndex;
  40846. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  40847. }
  40848. if (!defines["SHADOWS"]) {
  40849. if (defines["SHADOW" + lightIndex]) {
  40850. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  40851. }
  40852. if (defines["SHADOWPCF" + lightIndex]) {
  40853. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  40854. }
  40855. if (defines["SHADOWPCSS" + lightIndex]) {
  40856. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  40857. }
  40858. if (defines["SHADOWPOISSON" + lightIndex]) {
  40859. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  40860. }
  40861. if (defines["SHADOWESM" + lightIndex]) {
  40862. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  40863. }
  40864. }
  40865. }
  40866. return lightFallbackRank++;
  40867. };
  40868. /**
  40869. * Prepares the list of attributes required for morph targets according to the effect defines.
  40870. * @param attribs The current list of supported attribs
  40871. * @param mesh The mesh to prepare the morph targets attributes for
  40872. * @param defines The current Defines of the effect
  40873. */
  40874. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  40875. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  40876. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  40877. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  40878. var manager = mesh.morphTargetManager;
  40879. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  40880. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  40881. for (var index = 0; index < influencers; index++) {
  40882. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  40883. if (normal) {
  40884. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  40885. }
  40886. if (tangent) {
  40887. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  40888. }
  40889. if (attribs.length > maxAttributesCount) {
  40890. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  40891. }
  40892. }
  40893. }
  40894. };
  40895. /**
  40896. * Prepares the list of attributes required for bones according to the effect defines.
  40897. * @param attribs The current list of supported attribs
  40898. * @param mesh The mesh to prepare the bones attributes for
  40899. * @param defines The current Defines of the effect
  40900. * @param fallbacks The current efffect fallback strategy
  40901. */
  40902. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  40903. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  40904. fallbacks.addCPUSkinningFallback(0, mesh);
  40905. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40906. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40907. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  40908. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40909. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40910. }
  40911. }
  40912. };
  40913. /**
  40914. * Prepares the list of attributes required for instances according to the effect defines.
  40915. * @param attribs The current list of supported attribs
  40916. * @param defines The current Defines of the effect
  40917. */
  40918. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  40919. if (defines["INSTANCES"]) {
  40920. attribs.push("world0");
  40921. attribs.push("world1");
  40922. attribs.push("world2");
  40923. attribs.push("world3");
  40924. }
  40925. };
  40926. /**
  40927. * Binds the light shadow information to the effect for the given mesh.
  40928. * @param light The light containing the generator
  40929. * @param scene The scene the lights belongs to
  40930. * @param mesh The mesh we are binding the information to render
  40931. * @param lightIndex The light index in the effect used to render the mesh
  40932. * @param effect The effect we are binding the data to
  40933. */
  40934. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  40935. if (light.shadowEnabled && mesh.receiveShadows) {
  40936. var shadowGenerator = light.getShadowGenerator();
  40937. if (shadowGenerator) {
  40938. shadowGenerator.bindShadowLight(lightIndex, effect);
  40939. }
  40940. }
  40941. };
  40942. /**
  40943. * Binds the light information to the effect.
  40944. * @param light The light containing the generator
  40945. * @param effect The effect we are binding the data to
  40946. * @param lightIndex The light index in the effect used to render
  40947. */
  40948. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  40949. light.transferToEffect(effect, lightIndex + "");
  40950. };
  40951. /**
  40952. * Binds the lights information from the scene to the effect for the given mesh.
  40953. * @param scene The scene the lights belongs to
  40954. * @param mesh The mesh we are binding the information to render
  40955. * @param effect The effect we are binding the data to
  40956. * @param defines The generated defines for the effect
  40957. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  40958. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  40959. */
  40960. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  40961. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40962. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  40963. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  40964. for (var i = 0; i < len; i++) {
  40965. var light = mesh._lightSources[i];
  40966. var iAsString = i.toString();
  40967. var scaledIntensity = light.getScaledIntensity();
  40968. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  40969. MaterialHelper.BindLightProperties(light, effect, i);
  40970. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  40971. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  40972. if (defines["SPECULARTERM"]) {
  40973. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  40974. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  40975. }
  40976. // Shadows
  40977. if (scene.shadowsEnabled) {
  40978. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  40979. }
  40980. light._uniformBuffer.update();
  40981. }
  40982. };
  40983. /**
  40984. * Binds the fog information from the scene to the effect for the given mesh.
  40985. * @param scene The scene the lights belongs to
  40986. * @param mesh The mesh we are binding the information to render
  40987. * @param effect The effect we are binding the data to
  40988. */
  40989. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  40990. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  40991. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  40992. effect.setColor3("vFogColor", scene.fogColor);
  40993. }
  40994. };
  40995. /**
  40996. * Binds the bones information from the mesh to the effect.
  40997. * @param mesh The mesh we are binding the information to render
  40998. * @param effect The effect we are binding the data to
  40999. */
  41000. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41001. if (!effect || !mesh) {
  41002. return;
  41003. }
  41004. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41005. mesh.computeBonesUsingShaders = false;
  41006. }
  41007. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41008. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41009. if (matrices) {
  41010. effect.setMatrices("mBones", matrices);
  41011. }
  41012. }
  41013. };
  41014. /**
  41015. * Binds the morph targets information from the mesh to the effect.
  41016. * @param abstractMesh The mesh we are binding the information to render
  41017. * @param effect The effect we are binding the data to
  41018. */
  41019. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41020. var manager = abstractMesh.morphTargetManager;
  41021. if (!abstractMesh || !manager) {
  41022. return;
  41023. }
  41024. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41025. };
  41026. /**
  41027. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41028. * @param defines The generated defines used in the effect
  41029. * @param effect The effect we are binding the data to
  41030. * @param scene The scene we are willing to render with logarithmic scale for
  41031. */
  41032. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41033. if (defines["LOGARITHMICDEPTH"]) {
  41034. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41035. }
  41036. };
  41037. /**
  41038. * Binds the clip plane information from the scene to the effect.
  41039. * @param scene The scene the clip plane information are extracted from
  41040. * @param effect The effect we are binding the data to
  41041. */
  41042. MaterialHelper.BindClipPlane = function (effect, scene) {
  41043. if (scene.clipPlane) {
  41044. var clipPlane = scene.clipPlane;
  41045. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41046. }
  41047. if (scene.clipPlane2) {
  41048. var clipPlane = scene.clipPlane2;
  41049. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41050. }
  41051. if (scene.clipPlane3) {
  41052. var clipPlane = scene.clipPlane3;
  41053. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41054. }
  41055. if (scene.clipPlane4) {
  41056. var clipPlane = scene.clipPlane4;
  41057. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41058. }
  41059. };
  41060. return MaterialHelper;
  41061. }());
  41062. BABYLON.MaterialHelper = MaterialHelper;
  41063. })(BABYLON || (BABYLON = {}));
  41064. //# sourceMappingURL=babylon.materialHelper.js.map
  41065. var BABYLON;
  41066. (function (BABYLON) {
  41067. var PushMaterial = /** @class */ (function (_super) {
  41068. __extends(PushMaterial, _super);
  41069. function PushMaterial(name, scene) {
  41070. var _this = _super.call(this, name, scene) || this;
  41071. _this._normalMatrix = new BABYLON.Matrix();
  41072. _this.storeEffectOnSubMeshes = true;
  41073. return _this;
  41074. }
  41075. PushMaterial.prototype.getEffect = function () {
  41076. return this._activeEffect;
  41077. };
  41078. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41079. if (!mesh) {
  41080. return false;
  41081. }
  41082. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41083. return true;
  41084. }
  41085. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41086. };
  41087. /**
  41088. * Binds the given world matrix to the active effect
  41089. *
  41090. * @param world the matrix to bind
  41091. */
  41092. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41093. this._activeEffect.setMatrix("world", world);
  41094. };
  41095. /**
  41096. * Binds the given normal matrix to the active effect
  41097. *
  41098. * @param normalMatrix the matrix to bind
  41099. */
  41100. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41101. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41102. };
  41103. PushMaterial.prototype.bind = function (world, mesh) {
  41104. if (!mesh) {
  41105. return;
  41106. }
  41107. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41108. };
  41109. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41110. if (effect === void 0) { effect = null; }
  41111. _super.prototype._afterBind.call(this, mesh);
  41112. this.getScene()._cachedEffect = effect;
  41113. };
  41114. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41115. if (visibility === void 0) { visibility = 1; }
  41116. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41117. };
  41118. return PushMaterial;
  41119. }(BABYLON.Material));
  41120. BABYLON.PushMaterial = PushMaterial;
  41121. })(BABYLON || (BABYLON = {}));
  41122. //# sourceMappingURL=babylon.pushMaterial.js.map
  41123. var BABYLON;
  41124. (function (BABYLON) {
  41125. /** @hidden */
  41126. var StandardMaterialDefines = /** @class */ (function (_super) {
  41127. __extends(StandardMaterialDefines, _super);
  41128. function StandardMaterialDefines() {
  41129. var _this = _super.call(this) || this;
  41130. _this.MAINUV1 = false;
  41131. _this.MAINUV2 = false;
  41132. _this.DIFFUSE = false;
  41133. _this.DIFFUSEDIRECTUV = 0;
  41134. _this.AMBIENT = false;
  41135. _this.AMBIENTDIRECTUV = 0;
  41136. _this.OPACITY = false;
  41137. _this.OPACITYDIRECTUV = 0;
  41138. _this.OPACITYRGB = false;
  41139. _this.REFLECTION = false;
  41140. _this.EMISSIVE = false;
  41141. _this.EMISSIVEDIRECTUV = 0;
  41142. _this.SPECULAR = false;
  41143. _this.SPECULARDIRECTUV = 0;
  41144. _this.BUMP = false;
  41145. _this.BUMPDIRECTUV = 0;
  41146. _this.PARALLAX = false;
  41147. _this.PARALLAXOCCLUSION = false;
  41148. _this.SPECULAROVERALPHA = false;
  41149. _this.CLIPPLANE = false;
  41150. _this.CLIPPLANE2 = false;
  41151. _this.CLIPPLANE3 = false;
  41152. _this.CLIPPLANE4 = false;
  41153. _this.ALPHATEST = false;
  41154. _this.DEPTHPREPASS = false;
  41155. _this.ALPHAFROMDIFFUSE = false;
  41156. _this.POINTSIZE = false;
  41157. _this.FOG = false;
  41158. _this.SPECULARTERM = false;
  41159. _this.DIFFUSEFRESNEL = false;
  41160. _this.OPACITYFRESNEL = false;
  41161. _this.REFLECTIONFRESNEL = false;
  41162. _this.REFRACTIONFRESNEL = false;
  41163. _this.EMISSIVEFRESNEL = false;
  41164. _this.FRESNEL = false;
  41165. _this.NORMAL = false;
  41166. _this.UV1 = false;
  41167. _this.UV2 = false;
  41168. _this.VERTEXCOLOR = false;
  41169. _this.VERTEXALPHA = false;
  41170. _this.NUM_BONE_INFLUENCERS = 0;
  41171. _this.BonesPerMesh = 0;
  41172. _this.INSTANCES = false;
  41173. _this.GLOSSINESS = false;
  41174. _this.ROUGHNESS = false;
  41175. _this.EMISSIVEASILLUMINATION = false;
  41176. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41177. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41178. _this.LIGHTMAP = false;
  41179. _this.LIGHTMAPDIRECTUV = 0;
  41180. _this.OBJECTSPACE_NORMALMAP = false;
  41181. _this.USELIGHTMAPASSHADOWMAP = false;
  41182. _this.REFLECTIONMAP_3D = false;
  41183. _this.REFLECTIONMAP_SPHERICAL = false;
  41184. _this.REFLECTIONMAP_PLANAR = false;
  41185. _this.REFLECTIONMAP_CUBIC = false;
  41186. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41187. _this.REFLECTIONMAP_PROJECTION = false;
  41188. _this.REFLECTIONMAP_SKYBOX = false;
  41189. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41190. _this.REFLECTIONMAP_EXPLICIT = false;
  41191. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41192. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41193. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41194. _this.INVERTCUBICMAP = false;
  41195. _this.LOGARITHMICDEPTH = false;
  41196. _this.REFRACTION = false;
  41197. _this.REFRACTIONMAP_3D = false;
  41198. _this.REFLECTIONOVERALPHA = false;
  41199. _this.TWOSIDEDLIGHTING = false;
  41200. _this.SHADOWFLOAT = false;
  41201. _this.MORPHTARGETS = false;
  41202. _this.MORPHTARGETS_NORMAL = false;
  41203. _this.MORPHTARGETS_TANGENT = false;
  41204. _this.NUM_MORPH_INFLUENCERS = 0;
  41205. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41206. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41207. _this.IMAGEPROCESSING = false;
  41208. _this.VIGNETTE = false;
  41209. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41210. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41211. _this.TONEMAPPING = false;
  41212. _this.TONEMAPPING_ACES = false;
  41213. _this.CONTRAST = false;
  41214. _this.COLORCURVES = false;
  41215. _this.COLORGRADING = false;
  41216. _this.COLORGRADING3D = false;
  41217. _this.SAMPLER3DGREENDEPTH = false;
  41218. _this.SAMPLER3DBGRMAP = false;
  41219. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41220. /**
  41221. * If the reflection texture on this material is in linear color space
  41222. * @hidden
  41223. */
  41224. _this.IS_REFLECTION_LINEAR = false;
  41225. /**
  41226. * If the refraction texture on this material is in linear color space
  41227. * @hidden
  41228. */
  41229. _this.IS_REFRACTION_LINEAR = false;
  41230. _this.EXPOSURE = false;
  41231. _this.rebuild();
  41232. return _this;
  41233. }
  41234. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41235. var modes = [
  41236. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41237. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41238. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41239. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41240. ];
  41241. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41242. var mode = modes_1[_i];
  41243. this[mode] = (mode === modeToEnable);
  41244. }
  41245. };
  41246. return StandardMaterialDefines;
  41247. }(BABYLON.MaterialDefines));
  41248. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41249. var StandardMaterial = /** @class */ (function (_super) {
  41250. __extends(StandardMaterial, _super);
  41251. function StandardMaterial(name, scene) {
  41252. var _this = _super.call(this, name, scene) || this;
  41253. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41254. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41255. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41256. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41257. _this.specularPower = 64;
  41258. _this._useAlphaFromDiffuseTexture = false;
  41259. _this._useEmissiveAsIllumination = false;
  41260. _this._linkEmissiveWithDiffuse = false;
  41261. _this._useSpecularOverAlpha = false;
  41262. _this._useReflectionOverAlpha = false;
  41263. _this._disableLighting = false;
  41264. _this._useObjectSpaceNormalMap = false;
  41265. _this._useParallax = false;
  41266. _this._useParallaxOcclusion = false;
  41267. _this.parallaxScaleBias = 0.05;
  41268. _this._roughness = 0;
  41269. _this.indexOfRefraction = 0.98;
  41270. _this.invertRefractionY = true;
  41271. /**
  41272. * Defines the alpha limits in alpha test mode
  41273. */
  41274. _this.alphaCutOff = 0.4;
  41275. _this._useLightmapAsShadowmap = false;
  41276. _this._useReflectionFresnelFromSpecular = false;
  41277. _this._useGlossinessFromSpecularMapAlpha = false;
  41278. _this._maxSimultaneousLights = 4;
  41279. /**
  41280. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41281. */
  41282. _this._invertNormalMapX = false;
  41283. /**
  41284. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41285. */
  41286. _this._invertNormalMapY = false;
  41287. /**
  41288. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41289. */
  41290. _this._twoSidedLighting = false;
  41291. _this._renderTargets = new BABYLON.SmartArray(16);
  41292. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41293. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41294. // Setup the default processing configuration to the scene.
  41295. _this._attachImageProcessingConfiguration(null);
  41296. _this.getRenderTargetTextures = function () {
  41297. _this._renderTargets.reset();
  41298. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41299. _this._renderTargets.push(_this._reflectionTexture);
  41300. }
  41301. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41302. _this._renderTargets.push(_this._refractionTexture);
  41303. }
  41304. return _this._renderTargets;
  41305. };
  41306. return _this;
  41307. }
  41308. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41309. /**
  41310. * Gets the image processing configuration used either in this material.
  41311. */
  41312. get: function () {
  41313. return this._imageProcessingConfiguration;
  41314. },
  41315. /**
  41316. * Sets the Default image processing configuration used either in the this material.
  41317. *
  41318. * If sets to null, the scene one is in use.
  41319. */
  41320. set: function (value) {
  41321. this._attachImageProcessingConfiguration(value);
  41322. // Ensure the effect will be rebuilt.
  41323. this._markAllSubMeshesAsTexturesDirty();
  41324. },
  41325. enumerable: true,
  41326. configurable: true
  41327. });
  41328. /**
  41329. * Attaches a new image processing configuration to the Standard Material.
  41330. * @param configuration
  41331. */
  41332. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41333. var _this = this;
  41334. if (configuration === this._imageProcessingConfiguration) {
  41335. return;
  41336. }
  41337. // Detaches observer.
  41338. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41339. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41340. }
  41341. // Pick the scene configuration if needed.
  41342. if (!configuration) {
  41343. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41344. }
  41345. else {
  41346. this._imageProcessingConfiguration = configuration;
  41347. }
  41348. // Attaches observer.
  41349. if (this._imageProcessingConfiguration) {
  41350. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41351. _this._markAllSubMeshesAsImageProcessingDirty();
  41352. });
  41353. }
  41354. };
  41355. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41356. /**
  41357. * Gets wether the color curves effect is enabled.
  41358. */
  41359. get: function () {
  41360. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41361. },
  41362. /**
  41363. * Sets wether the color curves effect is enabled.
  41364. */
  41365. set: function (value) {
  41366. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41367. },
  41368. enumerable: true,
  41369. configurable: true
  41370. });
  41371. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41372. /**
  41373. * Gets wether the color grading effect is enabled.
  41374. */
  41375. get: function () {
  41376. return this.imageProcessingConfiguration.colorGradingEnabled;
  41377. },
  41378. /**
  41379. * Gets wether the color grading effect is enabled.
  41380. */
  41381. set: function (value) {
  41382. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41383. },
  41384. enumerable: true,
  41385. configurable: true
  41386. });
  41387. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41388. /**
  41389. * Gets wether tonemapping is enabled or not.
  41390. */
  41391. get: function () {
  41392. return this._imageProcessingConfiguration.toneMappingEnabled;
  41393. },
  41394. /**
  41395. * Sets wether tonemapping is enabled or not
  41396. */
  41397. set: function (value) {
  41398. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41399. },
  41400. enumerable: true,
  41401. configurable: true
  41402. });
  41403. ;
  41404. ;
  41405. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41406. /**
  41407. * The camera exposure used on this material.
  41408. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41409. * This corresponds to a photographic exposure.
  41410. */
  41411. get: function () {
  41412. return this._imageProcessingConfiguration.exposure;
  41413. },
  41414. /**
  41415. * The camera exposure used on this material.
  41416. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41417. * This corresponds to a photographic exposure.
  41418. */
  41419. set: function (value) {
  41420. this._imageProcessingConfiguration.exposure = value;
  41421. },
  41422. enumerable: true,
  41423. configurable: true
  41424. });
  41425. ;
  41426. ;
  41427. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41428. /**
  41429. * Gets The camera contrast used on this material.
  41430. */
  41431. get: function () {
  41432. return this._imageProcessingConfiguration.contrast;
  41433. },
  41434. /**
  41435. * Sets The camera contrast used on this material.
  41436. */
  41437. set: function (value) {
  41438. this._imageProcessingConfiguration.contrast = value;
  41439. },
  41440. enumerable: true,
  41441. configurable: true
  41442. });
  41443. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41444. /**
  41445. * Gets the Color Grading 2D Lookup Texture.
  41446. */
  41447. get: function () {
  41448. return this._imageProcessingConfiguration.colorGradingTexture;
  41449. },
  41450. /**
  41451. * Sets the Color Grading 2D Lookup Texture.
  41452. */
  41453. set: function (value) {
  41454. this._imageProcessingConfiguration.colorGradingTexture = value;
  41455. },
  41456. enumerable: true,
  41457. configurable: true
  41458. });
  41459. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41460. /**
  41461. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41462. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41463. * 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;
  41464. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41465. */
  41466. get: function () {
  41467. return this._imageProcessingConfiguration.colorCurves;
  41468. },
  41469. /**
  41470. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41471. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41472. * 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;
  41473. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41474. */
  41475. set: function (value) {
  41476. this._imageProcessingConfiguration.colorCurves = value;
  41477. },
  41478. enumerable: true,
  41479. configurable: true
  41480. });
  41481. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41482. /**
  41483. * Gets a boolean indicating that current material needs to register RTT
  41484. */
  41485. get: function () {
  41486. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41487. return true;
  41488. }
  41489. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41490. return true;
  41491. }
  41492. return false;
  41493. },
  41494. enumerable: true,
  41495. configurable: true
  41496. });
  41497. StandardMaterial.prototype.getClassName = function () {
  41498. return "StandardMaterial";
  41499. };
  41500. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41501. get: function () {
  41502. return this._useLogarithmicDepth;
  41503. },
  41504. set: function (value) {
  41505. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41506. this._markAllSubMeshesAsMiscDirty();
  41507. },
  41508. enumerable: true,
  41509. configurable: true
  41510. });
  41511. StandardMaterial.prototype.needAlphaBlending = function () {
  41512. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41513. };
  41514. StandardMaterial.prototype.needAlphaTesting = function () {
  41515. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41516. };
  41517. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41518. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41519. };
  41520. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41521. return this._diffuseTexture;
  41522. };
  41523. /**
  41524. * Child classes can use it to update shaders
  41525. */
  41526. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41527. if (useInstances === void 0) { useInstances = false; }
  41528. if (subMesh.effect && this.isFrozen) {
  41529. if (this._wasPreviouslyReady) {
  41530. return true;
  41531. }
  41532. }
  41533. if (!subMesh._materialDefines) {
  41534. subMesh._materialDefines = new StandardMaterialDefines();
  41535. }
  41536. var scene = this.getScene();
  41537. var defines = subMesh._materialDefines;
  41538. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41539. if (defines._renderId === scene.getRenderId()) {
  41540. return true;
  41541. }
  41542. }
  41543. var engine = scene.getEngine();
  41544. // Lights
  41545. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41546. // Textures
  41547. if (defines._areTexturesDirty) {
  41548. defines._needUVs = false;
  41549. defines.MAINUV1 = false;
  41550. defines.MAINUV2 = false;
  41551. if (scene.texturesEnabled) {
  41552. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41553. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41554. return false;
  41555. }
  41556. else {
  41557. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41558. }
  41559. }
  41560. else {
  41561. defines.DIFFUSE = false;
  41562. }
  41563. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41564. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41565. return false;
  41566. }
  41567. else {
  41568. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41569. }
  41570. }
  41571. else {
  41572. defines.AMBIENT = false;
  41573. }
  41574. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41575. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41576. return false;
  41577. }
  41578. else {
  41579. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41580. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41581. }
  41582. }
  41583. else {
  41584. defines.OPACITY = false;
  41585. }
  41586. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41587. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41588. return false;
  41589. }
  41590. else {
  41591. defines._needNormals = true;
  41592. defines.REFLECTION = true;
  41593. defines.ROUGHNESS = (this._roughness > 0);
  41594. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41595. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41596. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41597. switch (this._reflectionTexture.coordinatesMode) {
  41598. case BABYLON.Texture.EXPLICIT_MODE:
  41599. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41600. break;
  41601. case BABYLON.Texture.PLANAR_MODE:
  41602. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41603. break;
  41604. case BABYLON.Texture.PROJECTION_MODE:
  41605. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41606. break;
  41607. case BABYLON.Texture.SKYBOX_MODE:
  41608. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41609. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41610. break;
  41611. case BABYLON.Texture.SPHERICAL_MODE:
  41612. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41613. break;
  41614. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41615. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41616. break;
  41617. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41618. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41619. break;
  41620. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41621. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41622. break;
  41623. case BABYLON.Texture.CUBIC_MODE:
  41624. case BABYLON.Texture.INVCUBIC_MODE:
  41625. default:
  41626. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41627. break;
  41628. }
  41629. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41630. }
  41631. }
  41632. else {
  41633. defines.REFLECTION = false;
  41634. }
  41635. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41636. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41637. return false;
  41638. }
  41639. else {
  41640. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41641. }
  41642. }
  41643. else {
  41644. defines.EMISSIVE = false;
  41645. }
  41646. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41647. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41648. return false;
  41649. }
  41650. else {
  41651. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41652. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41653. }
  41654. }
  41655. else {
  41656. defines.LIGHTMAP = false;
  41657. }
  41658. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41659. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41660. return false;
  41661. }
  41662. else {
  41663. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41664. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41665. }
  41666. }
  41667. else {
  41668. defines.SPECULAR = false;
  41669. }
  41670. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41671. // Bump texure can not be not blocking.
  41672. if (!this._bumpTexture.isReady()) {
  41673. return false;
  41674. }
  41675. else {
  41676. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41677. defines.PARALLAX = this._useParallax;
  41678. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41679. }
  41680. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41681. }
  41682. else {
  41683. defines.BUMP = false;
  41684. }
  41685. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41686. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41687. return false;
  41688. }
  41689. else {
  41690. defines._needUVs = true;
  41691. defines.REFRACTION = true;
  41692. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41693. }
  41694. }
  41695. else {
  41696. defines.REFRACTION = false;
  41697. }
  41698. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41699. }
  41700. else {
  41701. defines.DIFFUSE = false;
  41702. defines.AMBIENT = false;
  41703. defines.OPACITY = false;
  41704. defines.REFLECTION = false;
  41705. defines.EMISSIVE = false;
  41706. defines.LIGHTMAP = false;
  41707. defines.BUMP = false;
  41708. defines.REFRACTION = false;
  41709. }
  41710. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41711. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41712. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41713. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41714. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41715. }
  41716. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41717. if (!this._imageProcessingConfiguration.isReady()) {
  41718. return false;
  41719. }
  41720. this._imageProcessingConfiguration.prepareDefines(defines);
  41721. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41722. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41723. }
  41724. if (defines._areFresnelDirty) {
  41725. if (StandardMaterial.FresnelEnabled) {
  41726. // Fresnel
  41727. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41728. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41729. this._reflectionFresnelParameters) {
  41730. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41731. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41732. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41733. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41734. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41735. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41736. defines._needNormals = true;
  41737. defines.FRESNEL = true;
  41738. }
  41739. }
  41740. else {
  41741. defines.FRESNEL = false;
  41742. }
  41743. }
  41744. // Misc.
  41745. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41746. // Attribs
  41747. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41748. // Values that need to be evaluated on every frame
  41749. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41750. // Get correct effect
  41751. if (defines.isDirty) {
  41752. defines.markAsProcessed();
  41753. scene.resetCachedMaterial();
  41754. // Fallbacks
  41755. var fallbacks = new BABYLON.EffectFallbacks();
  41756. if (defines.REFLECTION) {
  41757. fallbacks.addFallback(0, "REFLECTION");
  41758. }
  41759. if (defines.SPECULAR) {
  41760. fallbacks.addFallback(0, "SPECULAR");
  41761. }
  41762. if (defines.BUMP) {
  41763. fallbacks.addFallback(0, "BUMP");
  41764. }
  41765. if (defines.PARALLAX) {
  41766. fallbacks.addFallback(1, "PARALLAX");
  41767. }
  41768. if (defines.PARALLAXOCCLUSION) {
  41769. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41770. }
  41771. if (defines.SPECULAROVERALPHA) {
  41772. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41773. }
  41774. if (defines.FOG) {
  41775. fallbacks.addFallback(1, "FOG");
  41776. }
  41777. if (defines.POINTSIZE) {
  41778. fallbacks.addFallback(0, "POINTSIZE");
  41779. }
  41780. if (defines.LOGARITHMICDEPTH) {
  41781. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41782. }
  41783. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41784. if (defines.SPECULARTERM) {
  41785. fallbacks.addFallback(0, "SPECULARTERM");
  41786. }
  41787. if (defines.DIFFUSEFRESNEL) {
  41788. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41789. }
  41790. if (defines.OPACITYFRESNEL) {
  41791. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41792. }
  41793. if (defines.REFLECTIONFRESNEL) {
  41794. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41795. }
  41796. if (defines.EMISSIVEFRESNEL) {
  41797. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41798. }
  41799. if (defines.FRESNEL) {
  41800. fallbacks.addFallback(4, "FRESNEL");
  41801. }
  41802. //Attributes
  41803. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41804. if (defines.NORMAL) {
  41805. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41806. }
  41807. if (defines.UV1) {
  41808. attribs.push(BABYLON.VertexBuffer.UVKind);
  41809. }
  41810. if (defines.UV2) {
  41811. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41812. }
  41813. if (defines.VERTEXCOLOR) {
  41814. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41815. }
  41816. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41817. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41818. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41819. var shaderName = "default";
  41820. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41821. "vFogInfos", "vFogColor", "pointSize",
  41822. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41823. "mBones",
  41824. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  41825. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41826. "vReflectionPosition", "vReflectionSize",
  41827. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  41828. ];
  41829. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  41830. var uniformBuffers = ["Material", "Scene"];
  41831. if (BABYLON.ImageProcessingConfiguration) {
  41832. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41833. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41834. }
  41835. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41836. uniformsNames: uniforms,
  41837. uniformBuffersNames: uniformBuffers,
  41838. samplers: samplers,
  41839. defines: defines,
  41840. maxSimultaneousLights: this._maxSimultaneousLights
  41841. });
  41842. if (this.customShaderNameResolve) {
  41843. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  41844. }
  41845. var join = defines.toString();
  41846. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  41847. attributes: attribs,
  41848. uniformsNames: uniforms,
  41849. uniformBuffersNames: uniformBuffers,
  41850. samplers: samplers,
  41851. defines: join,
  41852. fallbacks: fallbacks,
  41853. onCompiled: this.onCompiled,
  41854. onError: this.onError,
  41855. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41856. }, engine), defines);
  41857. this.buildUniformLayout();
  41858. }
  41859. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41860. return false;
  41861. }
  41862. defines._renderId = scene.getRenderId();
  41863. this._wasPreviouslyReady = true;
  41864. return true;
  41865. };
  41866. StandardMaterial.prototype.buildUniformLayout = function () {
  41867. // Order is important !
  41868. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  41869. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  41870. this._uniformBuffer.addUniform("opacityParts", 4);
  41871. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  41872. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  41873. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  41874. this._uniformBuffer.addUniform("refractionRightColor", 4);
  41875. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  41876. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  41877. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  41878. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  41879. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41880. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41881. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41882. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41883. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41884. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41885. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  41886. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41887. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  41888. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41889. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41890. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41891. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41892. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41893. this._uniformBuffer.addUniform("specularMatrix", 16);
  41894. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41895. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41896. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41897. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41898. this._uniformBuffer.addUniform("vSpecularColor", 4);
  41899. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41900. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  41901. this._uniformBuffer.addUniform("pointSize", 1);
  41902. this._uniformBuffer.create();
  41903. };
  41904. StandardMaterial.prototype.unbind = function () {
  41905. if (this._activeEffect) {
  41906. var needFlag = false;
  41907. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41908. this._activeEffect.setTexture("reflection2DSampler", null);
  41909. needFlag = true;
  41910. }
  41911. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41912. this._activeEffect.setTexture("refraction2DSampler", null);
  41913. needFlag = true;
  41914. }
  41915. if (needFlag) {
  41916. this._markAllSubMeshesAsTexturesDirty();
  41917. }
  41918. }
  41919. _super.prototype.unbind.call(this);
  41920. };
  41921. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41922. var scene = this.getScene();
  41923. var defines = subMesh._materialDefines;
  41924. if (!defines) {
  41925. return;
  41926. }
  41927. var effect = subMesh.effect;
  41928. if (!effect) {
  41929. return;
  41930. }
  41931. this._activeEffect = effect;
  41932. // Matrices
  41933. this.bindOnlyWorldMatrix(world);
  41934. // Normal Matrix
  41935. if (defines.OBJECTSPACE_NORMALMAP) {
  41936. world.toNormalMatrix(this._normalMatrix);
  41937. this.bindOnlyNormalMatrix(this._normalMatrix);
  41938. }
  41939. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41940. // Bones
  41941. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  41942. if (mustRebind) {
  41943. this._uniformBuffer.bindToEffect(effect, "Material");
  41944. this.bindViewProjection(effect);
  41945. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41946. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  41947. // Fresnel
  41948. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  41949. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  41950. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  41951. }
  41952. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  41953. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  41954. }
  41955. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  41956. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  41957. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  41958. }
  41959. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  41960. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  41961. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  41962. }
  41963. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  41964. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  41965. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  41966. }
  41967. }
  41968. // Textures
  41969. if (scene.texturesEnabled) {
  41970. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41971. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  41972. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  41973. if (this._diffuseTexture.hasAlpha) {
  41974. effect.setFloat("alphaCutOff", this.alphaCutOff);
  41975. }
  41976. }
  41977. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41978. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  41979. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41980. }
  41981. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41982. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41983. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41984. }
  41985. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41986. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  41987. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  41988. if (this._reflectionTexture.boundingBoxSize) {
  41989. var cubeTexture = this._reflectionTexture;
  41990. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41991. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41992. }
  41993. }
  41994. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41995. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41996. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41997. }
  41998. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41999. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42000. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42001. }
  42002. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42003. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42004. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42005. }
  42006. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42007. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42008. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42009. if (scene._mirroredCameraPosition) {
  42010. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42011. }
  42012. else {
  42013. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42014. }
  42015. }
  42016. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42017. var depth = 1.0;
  42018. if (!this._refractionTexture.isCube) {
  42019. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42020. if (this._refractionTexture.depth) {
  42021. depth = this._refractionTexture.depth;
  42022. }
  42023. }
  42024. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42025. }
  42026. }
  42027. // Point size
  42028. if (this.pointsCloud) {
  42029. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42030. }
  42031. if (defines.SPECULARTERM) {
  42032. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42033. }
  42034. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42035. // Diffuse
  42036. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42037. }
  42038. // Textures
  42039. if (scene.texturesEnabled) {
  42040. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42041. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42042. }
  42043. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42044. effect.setTexture("ambientSampler", this._ambientTexture);
  42045. }
  42046. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42047. effect.setTexture("opacitySampler", this._opacityTexture);
  42048. }
  42049. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42050. if (this._reflectionTexture.isCube) {
  42051. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42052. }
  42053. else {
  42054. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42055. }
  42056. }
  42057. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42058. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42059. }
  42060. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42061. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42062. }
  42063. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42064. effect.setTexture("specularSampler", this._specularTexture);
  42065. }
  42066. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42067. effect.setTexture("bumpSampler", this._bumpTexture);
  42068. }
  42069. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42070. var depth = 1.0;
  42071. if (this._refractionTexture.isCube) {
  42072. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42073. }
  42074. else {
  42075. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42076. }
  42077. }
  42078. }
  42079. // Clip plane
  42080. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42081. // Colors
  42082. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42083. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42084. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42085. }
  42086. if (mustRebind || !this.isFrozen) {
  42087. // Lights
  42088. if (scene.lightsEnabled && !this._disableLighting) {
  42089. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42090. }
  42091. // View
  42092. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42093. this.bindView(effect);
  42094. }
  42095. // Fog
  42096. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42097. // Morph targets
  42098. if (defines.NUM_MORPH_INFLUENCERS) {
  42099. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42100. }
  42101. // Log. depth
  42102. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42103. // image processing
  42104. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42105. this._imageProcessingConfiguration.bind(this._activeEffect);
  42106. }
  42107. }
  42108. this._uniformBuffer.update();
  42109. this._afterBind(mesh, this._activeEffect);
  42110. };
  42111. StandardMaterial.prototype.getAnimatables = function () {
  42112. var results = [];
  42113. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42114. results.push(this._diffuseTexture);
  42115. }
  42116. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42117. results.push(this._ambientTexture);
  42118. }
  42119. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42120. results.push(this._opacityTexture);
  42121. }
  42122. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42123. results.push(this._reflectionTexture);
  42124. }
  42125. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42126. results.push(this._emissiveTexture);
  42127. }
  42128. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42129. results.push(this._specularTexture);
  42130. }
  42131. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42132. results.push(this._bumpTexture);
  42133. }
  42134. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42135. results.push(this._lightmapTexture);
  42136. }
  42137. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42138. results.push(this._refractionTexture);
  42139. }
  42140. return results;
  42141. };
  42142. StandardMaterial.prototype.getActiveTextures = function () {
  42143. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42144. if (this._diffuseTexture) {
  42145. activeTextures.push(this._diffuseTexture);
  42146. }
  42147. if (this._ambientTexture) {
  42148. activeTextures.push(this._ambientTexture);
  42149. }
  42150. if (this._opacityTexture) {
  42151. activeTextures.push(this._opacityTexture);
  42152. }
  42153. if (this._reflectionTexture) {
  42154. activeTextures.push(this._reflectionTexture);
  42155. }
  42156. if (this._emissiveTexture) {
  42157. activeTextures.push(this._emissiveTexture);
  42158. }
  42159. if (this._specularTexture) {
  42160. activeTextures.push(this._specularTexture);
  42161. }
  42162. if (this._bumpTexture) {
  42163. activeTextures.push(this._bumpTexture);
  42164. }
  42165. if (this._lightmapTexture) {
  42166. activeTextures.push(this._lightmapTexture);
  42167. }
  42168. if (this._refractionTexture) {
  42169. activeTextures.push(this._refractionTexture);
  42170. }
  42171. return activeTextures;
  42172. };
  42173. StandardMaterial.prototype.hasTexture = function (texture) {
  42174. if (_super.prototype.hasTexture.call(this, texture)) {
  42175. return true;
  42176. }
  42177. if (this._diffuseTexture === texture) {
  42178. return true;
  42179. }
  42180. if (this._ambientTexture === texture) {
  42181. return true;
  42182. }
  42183. if (this._opacityTexture === texture) {
  42184. return true;
  42185. }
  42186. if (this._reflectionTexture === texture) {
  42187. return true;
  42188. }
  42189. if (this._emissiveTexture === texture) {
  42190. return true;
  42191. }
  42192. if (this._specularTexture === texture) {
  42193. return true;
  42194. }
  42195. if (this._bumpTexture === texture) {
  42196. return true;
  42197. }
  42198. if (this._lightmapTexture === texture) {
  42199. return true;
  42200. }
  42201. if (this._refractionTexture === texture) {
  42202. return true;
  42203. }
  42204. return false;
  42205. };
  42206. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42207. if (forceDisposeTextures) {
  42208. if (this._diffuseTexture) {
  42209. this._diffuseTexture.dispose();
  42210. }
  42211. if (this._ambientTexture) {
  42212. this._ambientTexture.dispose();
  42213. }
  42214. if (this._opacityTexture) {
  42215. this._opacityTexture.dispose();
  42216. }
  42217. if (this._reflectionTexture) {
  42218. this._reflectionTexture.dispose();
  42219. }
  42220. if (this._emissiveTexture) {
  42221. this._emissiveTexture.dispose();
  42222. }
  42223. if (this._specularTexture) {
  42224. this._specularTexture.dispose();
  42225. }
  42226. if (this._bumpTexture) {
  42227. this._bumpTexture.dispose();
  42228. }
  42229. if (this._lightmapTexture) {
  42230. this._lightmapTexture.dispose();
  42231. }
  42232. if (this._refractionTexture) {
  42233. this._refractionTexture.dispose();
  42234. }
  42235. }
  42236. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42237. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42238. }
  42239. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42240. };
  42241. StandardMaterial.prototype.clone = function (name) {
  42242. var _this = this;
  42243. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42244. result.name = name;
  42245. result.id = name;
  42246. return result;
  42247. };
  42248. StandardMaterial.prototype.serialize = function () {
  42249. return BABYLON.SerializationHelper.Serialize(this);
  42250. };
  42251. // Statics
  42252. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42253. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42254. };
  42255. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42256. get: function () {
  42257. return StandardMaterial._DiffuseTextureEnabled;
  42258. },
  42259. set: function (value) {
  42260. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42261. return;
  42262. }
  42263. StandardMaterial._DiffuseTextureEnabled = value;
  42264. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42265. },
  42266. enumerable: true,
  42267. configurable: true
  42268. });
  42269. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42270. get: function () {
  42271. return StandardMaterial._AmbientTextureEnabled;
  42272. },
  42273. set: function (value) {
  42274. if (StandardMaterial._AmbientTextureEnabled === value) {
  42275. return;
  42276. }
  42277. StandardMaterial._AmbientTextureEnabled = value;
  42278. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42279. },
  42280. enumerable: true,
  42281. configurable: true
  42282. });
  42283. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42284. get: function () {
  42285. return StandardMaterial._OpacityTextureEnabled;
  42286. },
  42287. set: function (value) {
  42288. if (StandardMaterial._OpacityTextureEnabled === value) {
  42289. return;
  42290. }
  42291. StandardMaterial._OpacityTextureEnabled = value;
  42292. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42293. },
  42294. enumerable: true,
  42295. configurable: true
  42296. });
  42297. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42298. get: function () {
  42299. return StandardMaterial._ReflectionTextureEnabled;
  42300. },
  42301. set: function (value) {
  42302. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42303. return;
  42304. }
  42305. StandardMaterial._ReflectionTextureEnabled = value;
  42306. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42307. },
  42308. enumerable: true,
  42309. configurable: true
  42310. });
  42311. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42312. get: function () {
  42313. return StandardMaterial._EmissiveTextureEnabled;
  42314. },
  42315. set: function (value) {
  42316. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42317. return;
  42318. }
  42319. StandardMaterial._EmissiveTextureEnabled = value;
  42320. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42321. },
  42322. enumerable: true,
  42323. configurable: true
  42324. });
  42325. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42326. get: function () {
  42327. return StandardMaterial._SpecularTextureEnabled;
  42328. },
  42329. set: function (value) {
  42330. if (StandardMaterial._SpecularTextureEnabled === value) {
  42331. return;
  42332. }
  42333. StandardMaterial._SpecularTextureEnabled = value;
  42334. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42335. },
  42336. enumerable: true,
  42337. configurable: true
  42338. });
  42339. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42340. get: function () {
  42341. return StandardMaterial._BumpTextureEnabled;
  42342. },
  42343. set: function (value) {
  42344. if (StandardMaterial._BumpTextureEnabled === value) {
  42345. return;
  42346. }
  42347. StandardMaterial._BumpTextureEnabled = value;
  42348. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42349. },
  42350. enumerable: true,
  42351. configurable: true
  42352. });
  42353. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42354. get: function () {
  42355. return StandardMaterial._LightmapTextureEnabled;
  42356. },
  42357. set: function (value) {
  42358. if (StandardMaterial._LightmapTextureEnabled === value) {
  42359. return;
  42360. }
  42361. StandardMaterial._LightmapTextureEnabled = value;
  42362. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42363. },
  42364. enumerable: true,
  42365. configurable: true
  42366. });
  42367. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42368. get: function () {
  42369. return StandardMaterial._RefractionTextureEnabled;
  42370. },
  42371. set: function (value) {
  42372. if (StandardMaterial._RefractionTextureEnabled === value) {
  42373. return;
  42374. }
  42375. StandardMaterial._RefractionTextureEnabled = value;
  42376. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42377. },
  42378. enumerable: true,
  42379. configurable: true
  42380. });
  42381. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42382. get: function () {
  42383. return StandardMaterial._ColorGradingTextureEnabled;
  42384. },
  42385. set: function (value) {
  42386. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42387. return;
  42388. }
  42389. StandardMaterial._ColorGradingTextureEnabled = value;
  42390. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42391. },
  42392. enumerable: true,
  42393. configurable: true
  42394. });
  42395. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42396. get: function () {
  42397. return StandardMaterial._FresnelEnabled;
  42398. },
  42399. set: function (value) {
  42400. if (StandardMaterial._FresnelEnabled === value) {
  42401. return;
  42402. }
  42403. StandardMaterial._FresnelEnabled = value;
  42404. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42405. },
  42406. enumerable: true,
  42407. configurable: true
  42408. });
  42409. // Flags used to enable or disable a type of texture for all Standard Materials
  42410. StandardMaterial._DiffuseTextureEnabled = true;
  42411. StandardMaterial._AmbientTextureEnabled = true;
  42412. StandardMaterial._OpacityTextureEnabled = true;
  42413. StandardMaterial._ReflectionTextureEnabled = true;
  42414. StandardMaterial._EmissiveTextureEnabled = true;
  42415. StandardMaterial._SpecularTextureEnabled = true;
  42416. StandardMaterial._BumpTextureEnabled = true;
  42417. StandardMaterial._LightmapTextureEnabled = true;
  42418. StandardMaterial._RefractionTextureEnabled = true;
  42419. StandardMaterial._ColorGradingTextureEnabled = true;
  42420. StandardMaterial._FresnelEnabled = true;
  42421. __decorate([
  42422. BABYLON.serializeAsTexture("diffuseTexture")
  42423. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42424. __decorate([
  42425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42426. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42427. __decorate([
  42428. BABYLON.serializeAsTexture("ambientTexture")
  42429. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42430. __decorate([
  42431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42432. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42433. __decorate([
  42434. BABYLON.serializeAsTexture("opacityTexture")
  42435. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42436. __decorate([
  42437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42438. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42439. __decorate([
  42440. BABYLON.serializeAsTexture("reflectionTexture")
  42441. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42442. __decorate([
  42443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42444. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42445. __decorate([
  42446. BABYLON.serializeAsTexture("emissiveTexture")
  42447. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42448. __decorate([
  42449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42450. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42451. __decorate([
  42452. BABYLON.serializeAsTexture("specularTexture")
  42453. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42454. __decorate([
  42455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42456. ], StandardMaterial.prototype, "specularTexture", void 0);
  42457. __decorate([
  42458. BABYLON.serializeAsTexture("bumpTexture")
  42459. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42460. __decorate([
  42461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42462. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42463. __decorate([
  42464. BABYLON.serializeAsTexture("lightmapTexture")
  42465. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42466. __decorate([
  42467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42468. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42469. __decorate([
  42470. BABYLON.serializeAsTexture("refractionTexture")
  42471. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42472. __decorate([
  42473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42474. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42475. __decorate([
  42476. BABYLON.serializeAsColor3("ambient")
  42477. ], StandardMaterial.prototype, "ambientColor", void 0);
  42478. __decorate([
  42479. BABYLON.serializeAsColor3("diffuse")
  42480. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42481. __decorate([
  42482. BABYLON.serializeAsColor3("specular")
  42483. ], StandardMaterial.prototype, "specularColor", void 0);
  42484. __decorate([
  42485. BABYLON.serializeAsColor3("emissive")
  42486. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42487. __decorate([
  42488. BABYLON.serialize()
  42489. ], StandardMaterial.prototype, "specularPower", void 0);
  42490. __decorate([
  42491. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42492. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42493. __decorate([
  42494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42495. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42496. __decorate([
  42497. BABYLON.serialize("useEmissiveAsIllumination")
  42498. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42499. __decorate([
  42500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42501. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42502. __decorate([
  42503. BABYLON.serialize("linkEmissiveWithDiffuse")
  42504. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42505. __decorate([
  42506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42507. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42508. __decorate([
  42509. BABYLON.serialize("useSpecularOverAlpha")
  42510. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42511. __decorate([
  42512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42513. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42514. __decorate([
  42515. BABYLON.serialize("useReflectionOverAlpha")
  42516. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42517. __decorate([
  42518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42519. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42520. __decorate([
  42521. BABYLON.serialize("disableLighting")
  42522. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42523. __decorate([
  42524. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42525. ], StandardMaterial.prototype, "disableLighting", void 0);
  42526. __decorate([
  42527. BABYLON.serialize("useObjectSpaceNormalMap")
  42528. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42529. __decorate([
  42530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42531. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42532. __decorate([
  42533. BABYLON.serialize("useParallax")
  42534. ], StandardMaterial.prototype, "_useParallax", void 0);
  42535. __decorate([
  42536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42537. ], StandardMaterial.prototype, "useParallax", void 0);
  42538. __decorate([
  42539. BABYLON.serialize("useParallaxOcclusion")
  42540. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42541. __decorate([
  42542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42543. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42544. __decorate([
  42545. BABYLON.serialize()
  42546. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42547. __decorate([
  42548. BABYLON.serialize("roughness")
  42549. ], StandardMaterial.prototype, "_roughness", void 0);
  42550. __decorate([
  42551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42552. ], StandardMaterial.prototype, "roughness", void 0);
  42553. __decorate([
  42554. BABYLON.serialize()
  42555. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42556. __decorate([
  42557. BABYLON.serialize()
  42558. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42559. __decorate([
  42560. BABYLON.serialize()
  42561. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42562. __decorate([
  42563. BABYLON.serialize("useLightmapAsShadowmap")
  42564. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42565. __decorate([
  42566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42567. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42568. __decorate([
  42569. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42570. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42571. __decorate([
  42572. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42573. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42574. __decorate([
  42575. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42576. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42577. __decorate([
  42578. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42579. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42580. __decorate([
  42581. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42582. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42583. __decorate([
  42584. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42585. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42586. __decorate([
  42587. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42588. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42589. __decorate([
  42590. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42591. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42592. __decorate([
  42593. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42594. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42595. __decorate([
  42596. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42597. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42598. __decorate([
  42599. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42600. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42601. __decorate([
  42602. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42603. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42604. __decorate([
  42605. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42606. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42607. __decorate([
  42608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42609. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42610. __decorate([
  42611. BABYLON.serialize("maxSimultaneousLights")
  42612. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42613. __decorate([
  42614. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42615. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42616. __decorate([
  42617. BABYLON.serialize("invertNormalMapX")
  42618. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42619. __decorate([
  42620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42621. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42622. __decorate([
  42623. BABYLON.serialize("invertNormalMapY")
  42624. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42625. __decorate([
  42626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42627. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42628. __decorate([
  42629. BABYLON.serialize("twoSidedLighting")
  42630. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42631. __decorate([
  42632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42633. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42634. __decorate([
  42635. BABYLON.serialize()
  42636. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42637. return StandardMaterial;
  42638. }(BABYLON.PushMaterial));
  42639. BABYLON.StandardMaterial = StandardMaterial;
  42640. })(BABYLON || (BABYLON = {}));
  42641. //# sourceMappingURL=babylon.standardMaterial.js.map
  42642. var BABYLON;
  42643. (function (BABYLON) {
  42644. /**
  42645. * Class representing spherical polynomial coefficients to the 3rd degree
  42646. */
  42647. var SphericalPolynomial = /** @class */ (function () {
  42648. function SphericalPolynomial() {
  42649. /**
  42650. * The x coefficients of the spherical polynomial
  42651. */
  42652. this.x = BABYLON.Vector3.Zero();
  42653. /**
  42654. * The y coefficients of the spherical polynomial
  42655. */
  42656. this.y = BABYLON.Vector3.Zero();
  42657. /**
  42658. * The z coefficients of the spherical polynomial
  42659. */
  42660. this.z = BABYLON.Vector3.Zero();
  42661. /**
  42662. * The xx coefficients of the spherical polynomial
  42663. */
  42664. this.xx = BABYLON.Vector3.Zero();
  42665. /**
  42666. * The yy coefficients of the spherical polynomial
  42667. */
  42668. this.yy = BABYLON.Vector3.Zero();
  42669. /**
  42670. * The zz coefficients of the spherical polynomial
  42671. */
  42672. this.zz = BABYLON.Vector3.Zero();
  42673. /**
  42674. * The xy coefficients of the spherical polynomial
  42675. */
  42676. this.xy = BABYLON.Vector3.Zero();
  42677. /**
  42678. * The yz coefficients of the spherical polynomial
  42679. */
  42680. this.yz = BABYLON.Vector3.Zero();
  42681. /**
  42682. * The zx coefficients of the spherical polynomial
  42683. */
  42684. this.zx = BABYLON.Vector3.Zero();
  42685. }
  42686. /**
  42687. * Adds an ambient color to the spherical polynomial
  42688. * @param color the color to add
  42689. */
  42690. SphericalPolynomial.prototype.addAmbient = function (color) {
  42691. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42692. this.xx = this.xx.add(colorVector);
  42693. this.yy = this.yy.add(colorVector);
  42694. this.zz = this.zz.add(colorVector);
  42695. };
  42696. /**
  42697. * Scales the spherical polynomial by the given amount
  42698. * @param scale the amount to scale
  42699. */
  42700. SphericalPolynomial.prototype.scale = function (scale) {
  42701. this.x = this.x.scale(scale);
  42702. this.y = this.y.scale(scale);
  42703. this.z = this.z.scale(scale);
  42704. this.xx = this.xx.scale(scale);
  42705. this.yy = this.yy.scale(scale);
  42706. this.zz = this.zz.scale(scale);
  42707. this.yz = this.yz.scale(scale);
  42708. this.zx = this.zx.scale(scale);
  42709. this.xy = this.xy.scale(scale);
  42710. };
  42711. /**
  42712. * Gets the spherical polynomial from harmonics
  42713. * @param harmonics the spherical harmonics
  42714. * @returns the spherical polynomial
  42715. */
  42716. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42717. var result = new SphericalPolynomial();
  42718. result.x = harmonics.l11.scale(1.02333);
  42719. result.y = harmonics.l1_1.scale(1.02333);
  42720. result.z = harmonics.l10.scale(1.02333);
  42721. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42722. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42723. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42724. result.yz = harmonics.l2_1.scale(0.858086);
  42725. result.zx = harmonics.l21.scale(0.858086);
  42726. result.xy = harmonics.l2_2.scale(0.858086);
  42727. result.scale(1.0 / Math.PI);
  42728. return result;
  42729. };
  42730. /**
  42731. * Constructs a spherical polynomial from an array.
  42732. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42733. * @returns the spherical polynomial
  42734. */
  42735. SphericalPolynomial.FromArray = function (data) {
  42736. var sp = new SphericalPolynomial();
  42737. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42738. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42739. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42740. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42741. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42742. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42743. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42744. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42745. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42746. return sp;
  42747. };
  42748. return SphericalPolynomial;
  42749. }());
  42750. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42751. /**
  42752. * Class representing spherical harmonics coefficients to the 3rd degree
  42753. */
  42754. var SphericalHarmonics = /** @class */ (function () {
  42755. function SphericalHarmonics() {
  42756. /**
  42757. * The l0,0 coefficients of the spherical harmonics
  42758. */
  42759. this.l00 = BABYLON.Vector3.Zero();
  42760. /**
  42761. * The l1,-1 coefficients of the spherical harmonics
  42762. */
  42763. this.l1_1 = BABYLON.Vector3.Zero();
  42764. /**
  42765. * The l1,0 coefficients of the spherical harmonics
  42766. */
  42767. this.l10 = BABYLON.Vector3.Zero();
  42768. /**
  42769. * The l1,1 coefficients of the spherical harmonics
  42770. */
  42771. this.l11 = BABYLON.Vector3.Zero();
  42772. /**
  42773. * The l2,-2 coefficients of the spherical harmonics
  42774. */
  42775. this.l2_2 = BABYLON.Vector3.Zero();
  42776. /**
  42777. * The l2,-1 coefficients of the spherical harmonics
  42778. */
  42779. this.l2_1 = BABYLON.Vector3.Zero();
  42780. /**
  42781. * The l2,0 coefficients of the spherical harmonics
  42782. */
  42783. this.l20 = BABYLON.Vector3.Zero();
  42784. /**
  42785. * The l2,1 coefficients of the spherical harmonics
  42786. */
  42787. this.l21 = BABYLON.Vector3.Zero();
  42788. /**
  42789. * The l2,2 coefficients of the spherical harmonics
  42790. */
  42791. this.lL22 = BABYLON.Vector3.Zero();
  42792. }
  42793. /**
  42794. * Adds a light to the spherical harmonics
  42795. * @param direction the direction of the light
  42796. * @param color the color of the light
  42797. * @param deltaSolidAngle the delta solid angle of the light
  42798. */
  42799. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  42800. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42801. var c = colorVector.scale(deltaSolidAngle);
  42802. this.l00 = this.l00.add(c.scale(0.282095));
  42803. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  42804. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  42805. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  42806. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  42807. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  42808. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  42809. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  42810. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  42811. };
  42812. /**
  42813. * Scales the spherical harmonics by the given amount
  42814. * @param scale the amount to scale
  42815. */
  42816. SphericalHarmonics.prototype.scale = function (scale) {
  42817. this.l00 = this.l00.scale(scale);
  42818. this.l1_1 = this.l1_1.scale(scale);
  42819. this.l10 = this.l10.scale(scale);
  42820. this.l11 = this.l11.scale(scale);
  42821. this.l2_2 = this.l2_2.scale(scale);
  42822. this.l2_1 = this.l2_1.scale(scale);
  42823. this.l20 = this.l20.scale(scale);
  42824. this.l21 = this.l21.scale(scale);
  42825. this.lL22 = this.lL22.scale(scale);
  42826. };
  42827. /**
  42828. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  42829. *
  42830. * ```
  42831. * E_lm = A_l * L_lm
  42832. * ```
  42833. *
  42834. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  42835. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  42836. * the scaling factors are given in equation 9.
  42837. */
  42838. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  42839. // Constant (Band 0)
  42840. this.l00 = this.l00.scale(3.141593);
  42841. // Linear (Band 1)
  42842. this.l1_1 = this.l1_1.scale(2.094395);
  42843. this.l10 = this.l10.scale(2.094395);
  42844. this.l11 = this.l11.scale(2.094395);
  42845. // Quadratic (Band 2)
  42846. this.l2_2 = this.l2_2.scale(0.785398);
  42847. this.l2_1 = this.l2_1.scale(0.785398);
  42848. this.l20 = this.l20.scale(0.785398);
  42849. this.l21 = this.l21.scale(0.785398);
  42850. this.lL22 = this.lL22.scale(0.785398);
  42851. };
  42852. /**
  42853. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  42854. *
  42855. * ```
  42856. * L = (1/pi) * E * rho
  42857. * ```
  42858. *
  42859. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  42860. */
  42861. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  42862. this.scale(1.0 / Math.PI);
  42863. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  42864. // (The pixel shader must apply albedo after texture fetches, etc).
  42865. };
  42866. /**
  42867. * Gets the spherical harmonics from polynomial
  42868. * @param polynomial the spherical polynomial
  42869. * @returns the spherical harmonics
  42870. */
  42871. SphericalHarmonics.FromPolynomial = function (polynomial) {
  42872. var result = new SphericalHarmonics();
  42873. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  42874. result.l1_1 = polynomial.y.scale(0.977204);
  42875. result.l10 = polynomial.z.scale(0.977204);
  42876. result.l11 = polynomial.x.scale(0.977204);
  42877. result.l2_2 = polynomial.xy.scale(1.16538);
  42878. result.l2_1 = polynomial.yz.scale(1.16538);
  42879. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  42880. result.l21 = polynomial.zx.scale(1.16538);
  42881. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  42882. result.scale(Math.PI);
  42883. return result;
  42884. };
  42885. /**
  42886. * Constructs a spherical harmonics from an array.
  42887. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  42888. * @returns the spherical harmonics
  42889. */
  42890. SphericalHarmonics.FromArray = function (data) {
  42891. var sh = new SphericalHarmonics();
  42892. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  42893. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  42894. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  42895. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  42896. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  42897. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  42898. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  42899. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  42900. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  42901. return sh;
  42902. };
  42903. return SphericalHarmonics;
  42904. }());
  42905. BABYLON.SphericalHarmonics = SphericalHarmonics;
  42906. })(BABYLON || (BABYLON = {}));
  42907. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  42908. var BABYLON;
  42909. (function (BABYLON) {
  42910. var FileFaceOrientation = /** @class */ (function () {
  42911. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42912. this.name = name;
  42913. this.worldAxisForNormal = worldAxisForNormal;
  42914. this.worldAxisForFileX = worldAxisForFileX;
  42915. this.worldAxisForFileY = worldAxisForFileY;
  42916. }
  42917. return FileFaceOrientation;
  42918. }());
  42919. ;
  42920. /**
  42921. * Helper class dealing with the extraction of spherical polynomial dataArray
  42922. * from a cube map.
  42923. */
  42924. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  42925. function CubeMapToSphericalPolynomialTools() {
  42926. }
  42927. /**
  42928. * Converts a texture to the according Spherical Polynomial data.
  42929. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42930. *
  42931. * @param texture The texture to extract the information from.
  42932. * @return The Spherical Polynomial data.
  42933. */
  42934. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  42935. if (!texture.isCube) {
  42936. // Only supports cube Textures currently.
  42937. return null;
  42938. }
  42939. var size = texture.getSize().width;
  42940. var right = texture.readPixels(0);
  42941. var left = texture.readPixels(1);
  42942. var up;
  42943. var down;
  42944. if (texture.isRenderTarget) {
  42945. up = texture.readPixels(3);
  42946. down = texture.readPixels(2);
  42947. }
  42948. else {
  42949. up = texture.readPixels(2);
  42950. down = texture.readPixels(3);
  42951. }
  42952. var front = texture.readPixels(4);
  42953. var back = texture.readPixels(5);
  42954. var gammaSpace = texture.gammaSpace;
  42955. // Always read as RGBA.
  42956. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  42957. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42958. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  42959. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42960. }
  42961. var cubeInfo = {
  42962. size: size,
  42963. right: right,
  42964. left: left,
  42965. up: up,
  42966. down: down,
  42967. front: front,
  42968. back: back,
  42969. format: format,
  42970. type: type,
  42971. gammaSpace: gammaSpace,
  42972. };
  42973. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  42974. };
  42975. /**
  42976. * Converts a cubemap to the according Spherical Polynomial data.
  42977. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42978. *
  42979. * @param cubeInfo The Cube map to extract the information from.
  42980. * @return The Spherical Polynomial data.
  42981. */
  42982. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  42983. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  42984. var totalSolidAngle = 0.0;
  42985. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  42986. var du = 2.0 / cubeInfo.size;
  42987. var dv = du;
  42988. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  42989. var minUV = du * 0.5 - 1.0;
  42990. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  42991. var fileFace = this.FileFaces[faceIndex];
  42992. var dataArray = cubeInfo[fileFace.name];
  42993. var v = minUV;
  42994. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  42995. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  42996. // Because SP is still linear, so summation is fine in that basis.
  42997. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  42998. for (var y = 0; y < cubeInfo.size; y++) {
  42999. var u = minUV;
  43000. for (var x = 0; x < cubeInfo.size; x++) {
  43001. // World direction (not normalised)
  43002. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43003. worldDirection.normalize();
  43004. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43005. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43006. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43007. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43008. // Handle Integer types.
  43009. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43010. r /= 255;
  43011. g /= 255;
  43012. b /= 255;
  43013. }
  43014. // Handle Gamma space textures.
  43015. if (cubeInfo.gammaSpace) {
  43016. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43017. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43018. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43019. }
  43020. var color = new BABYLON.Color3(r, g, b);
  43021. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43022. totalSolidAngle += deltaSolidAngle;
  43023. u += du;
  43024. }
  43025. v += dv;
  43026. }
  43027. }
  43028. // Solid angle for entire sphere is 4*pi
  43029. var sphereSolidAngle = 4.0 * Math.PI;
  43030. // Adjust the solid angle to allow for how many faces we processed.
  43031. var facesProcessed = 6.0;
  43032. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43033. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43034. // This is needed because the numerical integration over the cube uses a
  43035. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43036. // and also to compensate for accumulative error due to float precision in the summation.
  43037. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43038. sphericalHarmonics.scale(correctionFactor);
  43039. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43040. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43041. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43042. };
  43043. CubeMapToSphericalPolynomialTools.FileFaces = [
  43044. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43045. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43046. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43047. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43048. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43049. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43050. ];
  43051. return CubeMapToSphericalPolynomialTools;
  43052. }());
  43053. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43054. })(BABYLON || (BABYLON = {}));
  43055. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43056. var BABYLON;
  43057. (function (BABYLON) {
  43058. /**
  43059. * Manages the defines for the PBR Material.
  43060. * @hiddenChildren
  43061. */
  43062. var PBRMaterialDefines = /** @class */ (function (_super) {
  43063. __extends(PBRMaterialDefines, _super);
  43064. /**
  43065. * Initializes the PBR Material defines.
  43066. */
  43067. function PBRMaterialDefines() {
  43068. var _this = _super.call(this) || this;
  43069. _this.PBR = true;
  43070. _this.MAINUV1 = false;
  43071. _this.MAINUV2 = false;
  43072. _this.UV1 = false;
  43073. _this.UV2 = false;
  43074. _this.ALBEDO = false;
  43075. _this.ALBEDODIRECTUV = 0;
  43076. _this.VERTEXCOLOR = false;
  43077. _this.AMBIENT = false;
  43078. _this.AMBIENTDIRECTUV = 0;
  43079. _this.AMBIENTINGRAYSCALE = false;
  43080. _this.OPACITY = false;
  43081. _this.VERTEXALPHA = false;
  43082. _this.OPACITYDIRECTUV = 0;
  43083. _this.OPACITYRGB = false;
  43084. _this.ALPHATEST = false;
  43085. _this.DEPTHPREPASS = false;
  43086. _this.ALPHABLEND = false;
  43087. _this.ALPHAFROMALBEDO = false;
  43088. _this.ALPHATESTVALUE = "0.5";
  43089. _this.SPECULAROVERALPHA = false;
  43090. _this.RADIANCEOVERALPHA = false;
  43091. _this.ALPHAFRESNEL = false;
  43092. _this.LINEARALPHAFRESNEL = false;
  43093. _this.PREMULTIPLYALPHA = false;
  43094. _this.EMISSIVE = false;
  43095. _this.EMISSIVEDIRECTUV = 0;
  43096. _this.REFLECTIVITY = false;
  43097. _this.REFLECTIVITYDIRECTUV = 0;
  43098. _this.SPECULARTERM = false;
  43099. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43100. _this.MICROSURFACEAUTOMATIC = false;
  43101. _this.LODBASEDMICROSFURACE = false;
  43102. _this.MICROSURFACEMAP = false;
  43103. _this.MICROSURFACEMAPDIRECTUV = 0;
  43104. _this.METALLICWORKFLOW = false;
  43105. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43106. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43107. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43108. _this.AOSTOREINMETALMAPRED = false;
  43109. _this.ENVIRONMENTBRDF = false;
  43110. _this.NORMAL = false;
  43111. _this.TANGENT = false;
  43112. _this.BUMP = false;
  43113. _this.BUMPDIRECTUV = 0;
  43114. _this.OBJECTSPACE_NORMALMAP = false;
  43115. _this.PARALLAX = false;
  43116. _this.PARALLAXOCCLUSION = false;
  43117. _this.NORMALXYSCALE = true;
  43118. _this.LIGHTMAP = false;
  43119. _this.LIGHTMAPDIRECTUV = 0;
  43120. _this.USELIGHTMAPASSHADOWMAP = false;
  43121. _this.GAMMALIGHTMAP = false;
  43122. _this.REFLECTION = false;
  43123. _this.REFLECTIONMAP_3D = false;
  43124. _this.REFLECTIONMAP_SPHERICAL = false;
  43125. _this.REFLECTIONMAP_PLANAR = false;
  43126. _this.REFLECTIONMAP_CUBIC = false;
  43127. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43128. _this.REFLECTIONMAP_PROJECTION = false;
  43129. _this.REFLECTIONMAP_SKYBOX = false;
  43130. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43131. _this.REFLECTIONMAP_EXPLICIT = false;
  43132. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43133. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43134. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43135. _this.INVERTCUBICMAP = false;
  43136. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43137. _this.USESPHERICALINVERTEX = false;
  43138. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43139. _this.LODINREFLECTIONALPHA = false;
  43140. _this.GAMMAREFLECTION = false;
  43141. _this.RGBDREFLECTION = false;
  43142. _this.RADIANCEOCCLUSION = false;
  43143. _this.HORIZONOCCLUSION = false;
  43144. _this.REFRACTION = false;
  43145. _this.REFRACTIONMAP_3D = false;
  43146. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43147. _this.LODINREFRACTIONALPHA = false;
  43148. _this.GAMMAREFRACTION = false;
  43149. _this.RGBDREFRACTION = false;
  43150. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43151. _this.INSTANCES = false;
  43152. _this.NUM_BONE_INFLUENCERS = 0;
  43153. _this.BonesPerMesh = 0;
  43154. _this.NONUNIFORMSCALING = false;
  43155. _this.MORPHTARGETS = false;
  43156. _this.MORPHTARGETS_NORMAL = false;
  43157. _this.MORPHTARGETS_TANGENT = false;
  43158. _this.NUM_MORPH_INFLUENCERS = 0;
  43159. _this.IMAGEPROCESSING = false;
  43160. _this.VIGNETTE = false;
  43161. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43162. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43163. _this.TONEMAPPING = false;
  43164. _this.TONEMAPPING_ACES = false;
  43165. _this.CONTRAST = false;
  43166. _this.COLORCURVES = false;
  43167. _this.COLORGRADING = false;
  43168. _this.COLORGRADING3D = false;
  43169. _this.SAMPLER3DGREENDEPTH = false;
  43170. _this.SAMPLER3DBGRMAP = false;
  43171. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43172. _this.EXPOSURE = false;
  43173. _this.USEPHYSICALLIGHTFALLOFF = false;
  43174. _this.USEGLTFLIGHTFALLOFF = false;
  43175. _this.TWOSIDEDLIGHTING = false;
  43176. _this.SHADOWFLOAT = false;
  43177. _this.CLIPPLANE = false;
  43178. _this.CLIPPLANE2 = false;
  43179. _this.CLIPPLANE3 = false;
  43180. _this.CLIPPLANE4 = false;
  43181. _this.POINTSIZE = false;
  43182. _this.FOG = false;
  43183. _this.LOGARITHMICDEPTH = false;
  43184. _this.FORCENORMALFORWARD = false;
  43185. _this.SPECULARAA = false;
  43186. _this.UNLIT = false;
  43187. _this.rebuild();
  43188. return _this;
  43189. }
  43190. /**
  43191. * Resets the PBR Material defines.
  43192. */
  43193. PBRMaterialDefines.prototype.reset = function () {
  43194. _super.prototype.reset.call(this);
  43195. this.ALPHATESTVALUE = "0.5";
  43196. this.PBR = true;
  43197. };
  43198. return PBRMaterialDefines;
  43199. }(BABYLON.MaterialDefines));
  43200. /**
  43201. * The Physically based material base class of BJS.
  43202. *
  43203. * This offers the main features of a standard PBR material.
  43204. * For more information, please refer to the documentation :
  43205. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43206. */
  43207. var PBRBaseMaterial = /** @class */ (function (_super) {
  43208. __extends(PBRBaseMaterial, _super);
  43209. /**
  43210. * Instantiates a new PBRMaterial instance.
  43211. *
  43212. * @param name The material name
  43213. * @param scene The scene the material will be use in.
  43214. */
  43215. function PBRBaseMaterial(name, scene) {
  43216. var _this = _super.call(this, name, scene) || this;
  43217. /**
  43218. * Intensity of the direct lights e.g. the four lights available in your scene.
  43219. * This impacts both the direct diffuse and specular highlights.
  43220. */
  43221. _this._directIntensity = 1.0;
  43222. /**
  43223. * Intensity of the emissive part of the material.
  43224. * This helps controlling the emissive effect without modifying the emissive color.
  43225. */
  43226. _this._emissiveIntensity = 1.0;
  43227. /**
  43228. * Intensity of the environment e.g. how much the environment will light the object
  43229. * either through harmonics for rough material or through the refelction for shiny ones.
  43230. */
  43231. _this._environmentIntensity = 1.0;
  43232. /**
  43233. * This is a special control allowing the reduction of the specular highlights coming from the
  43234. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43235. */
  43236. _this._specularIntensity = 1.0;
  43237. /**
  43238. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43239. */
  43240. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43241. /**
  43242. * Debug Control allowing disabling the bump map on this material.
  43243. */
  43244. _this._disableBumpMap = false;
  43245. /**
  43246. * AKA Occlusion Texture Intensity in other nomenclature.
  43247. */
  43248. _this._ambientTextureStrength = 1.0;
  43249. /**
  43250. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43251. * 1 means it completely occludes it
  43252. * 0 mean it has no impact
  43253. */
  43254. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43255. /**
  43256. * The color of a material in ambient lighting.
  43257. */
  43258. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43259. /**
  43260. * AKA Diffuse Color in other nomenclature.
  43261. */
  43262. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43263. /**
  43264. * AKA Specular Color in other nomenclature.
  43265. */
  43266. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43267. /**
  43268. * The color applied when light is reflected from a material.
  43269. */
  43270. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43271. /**
  43272. * The color applied when light is emitted from a material.
  43273. */
  43274. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43275. /**
  43276. * AKA Glossiness in other nomenclature.
  43277. */
  43278. _this._microSurface = 0.9;
  43279. /**
  43280. * source material index of refraction (IOR)' / 'destination material IOR.
  43281. */
  43282. _this._indexOfRefraction = 0.66;
  43283. /**
  43284. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43285. */
  43286. _this._invertRefractionY = false;
  43287. /**
  43288. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43289. * Materials half opaque for instance using refraction could benefit from this control.
  43290. */
  43291. _this._linkRefractionWithTransparency = false;
  43292. /**
  43293. * Specifies that the material will use the light map as a show map.
  43294. */
  43295. _this._useLightmapAsShadowmap = false;
  43296. /**
  43297. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43298. * makes the reflect vector face the model (under horizon).
  43299. */
  43300. _this._useHorizonOcclusion = true;
  43301. /**
  43302. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43303. * too much the area relying on ambient texture to define their ambient occlusion.
  43304. */
  43305. _this._useRadianceOcclusion = true;
  43306. /**
  43307. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43308. */
  43309. _this._useAlphaFromAlbedoTexture = false;
  43310. /**
  43311. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43312. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43313. */
  43314. _this._useSpecularOverAlpha = true;
  43315. /**
  43316. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43317. */
  43318. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43319. /**
  43320. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43321. */
  43322. _this._useRoughnessFromMetallicTextureAlpha = true;
  43323. /**
  43324. * Specifies if the metallic texture contains the roughness information in its green channel.
  43325. */
  43326. _this._useRoughnessFromMetallicTextureGreen = false;
  43327. /**
  43328. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43329. */
  43330. _this._useMetallnessFromMetallicTextureBlue = false;
  43331. /**
  43332. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43333. */
  43334. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43335. /**
  43336. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43337. */
  43338. _this._useAmbientInGrayScale = false;
  43339. /**
  43340. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43341. * The material will try to infer what glossiness each pixel should be.
  43342. */
  43343. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43344. /**
  43345. * Defines the falloff type used in this material.
  43346. * It by default is Physical.
  43347. */
  43348. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43349. /**
  43350. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43351. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43352. */
  43353. _this._useRadianceOverAlpha = true;
  43354. /**
  43355. * Allows using an object space normal map (instead of tangent space).
  43356. */
  43357. _this._useObjectSpaceNormalMap = false;
  43358. /**
  43359. * Allows using the bump map in parallax mode.
  43360. */
  43361. _this._useParallax = false;
  43362. /**
  43363. * Allows using the bump map in parallax occlusion mode.
  43364. */
  43365. _this._useParallaxOcclusion = false;
  43366. /**
  43367. * Controls the scale bias of the parallax mode.
  43368. */
  43369. _this._parallaxScaleBias = 0.05;
  43370. /**
  43371. * If sets to true, disables all the lights affecting the material.
  43372. */
  43373. _this._disableLighting = false;
  43374. /**
  43375. * Number of Simultaneous lights allowed on the material.
  43376. */
  43377. _this._maxSimultaneousLights = 4;
  43378. /**
  43379. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43380. */
  43381. _this._invertNormalMapX = false;
  43382. /**
  43383. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43384. */
  43385. _this._invertNormalMapY = false;
  43386. /**
  43387. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43388. */
  43389. _this._twoSidedLighting = false;
  43390. /**
  43391. * Defines the alpha limits in alpha test mode.
  43392. */
  43393. _this._alphaCutOff = 0.4;
  43394. /**
  43395. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43396. */
  43397. _this._forceAlphaTest = false;
  43398. /**
  43399. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43400. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43401. */
  43402. _this._useAlphaFresnel = false;
  43403. /**
  43404. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43405. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43406. */
  43407. _this._useLinearAlphaFresnel = false;
  43408. /**
  43409. * The transparency mode of the material.
  43410. */
  43411. _this._transparencyMode = null;
  43412. /**
  43413. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43414. * from cos thetav and roughness:
  43415. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43416. */
  43417. _this._environmentBRDFTexture = null;
  43418. /**
  43419. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43420. */
  43421. _this._forceIrradianceInFragment = false;
  43422. /**
  43423. * Force normal to face away from face.
  43424. */
  43425. _this._forceNormalForward = false;
  43426. /**
  43427. * Enables specular anti aliasing in the PBR shader.
  43428. * It will both interacts on the Geometry for analytical and IBL lighting.
  43429. * It also prefilter the roughness map based on the bump values.
  43430. */
  43431. _this._enableSpecularAntiAliasing = false;
  43432. /**
  43433. * Stores the available render targets.
  43434. */
  43435. _this._renderTargets = new BABYLON.SmartArray(16);
  43436. /**
  43437. * Sets the global ambient color for the material used in lighting calculations.
  43438. */
  43439. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43440. /**
  43441. * If set to true, no lighting calculations will be applied.
  43442. */
  43443. _this._unlit = false;
  43444. // Setup the default processing configuration to the scene.
  43445. _this._attachImageProcessingConfiguration(null);
  43446. _this.getRenderTargetTextures = function () {
  43447. _this._renderTargets.reset();
  43448. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43449. _this._renderTargets.push(_this._reflectionTexture);
  43450. }
  43451. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43452. _this._renderTargets.push(_this._refractionTexture);
  43453. }
  43454. return _this._renderTargets;
  43455. };
  43456. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43457. return _this;
  43458. }
  43459. /**
  43460. * Attaches a new image processing configuration to the PBR Material.
  43461. * @param configuration
  43462. */
  43463. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43464. var _this = this;
  43465. if (configuration === this._imageProcessingConfiguration) {
  43466. return;
  43467. }
  43468. // Detaches observer.
  43469. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43470. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43471. }
  43472. // Pick the scene configuration if needed.
  43473. if (!configuration) {
  43474. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43475. }
  43476. else {
  43477. this._imageProcessingConfiguration = configuration;
  43478. }
  43479. // Attaches observer.
  43480. if (this._imageProcessingConfiguration) {
  43481. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43482. _this._markAllSubMeshesAsImageProcessingDirty();
  43483. });
  43484. }
  43485. };
  43486. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43487. /**
  43488. * Gets a boolean indicating that current material needs to register RTT
  43489. */
  43490. get: function () {
  43491. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43492. return true;
  43493. }
  43494. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43495. return true;
  43496. }
  43497. return false;
  43498. },
  43499. enumerable: true,
  43500. configurable: true
  43501. });
  43502. /**
  43503. * Gets the name of the material class.
  43504. */
  43505. PBRBaseMaterial.prototype.getClassName = function () {
  43506. return "PBRBaseMaterial";
  43507. };
  43508. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43509. /**
  43510. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43511. */
  43512. get: function () {
  43513. return this._useLogarithmicDepth;
  43514. },
  43515. /**
  43516. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43517. */
  43518. set: function (value) {
  43519. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43520. },
  43521. enumerable: true,
  43522. configurable: true
  43523. });
  43524. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43525. /**
  43526. * Gets the current transparency mode.
  43527. */
  43528. get: function () {
  43529. return this._transparencyMode;
  43530. },
  43531. /**
  43532. * Sets the transparency mode of the material.
  43533. *
  43534. * | Value | Type | Description |
  43535. * | ----- | ----------------------------------- | ----------- |
  43536. * | 0 | OPAQUE | |
  43537. * | 1 | ALPHATEST | |
  43538. * | 2 | ALPHABLEND | |
  43539. * | 3 | ALPHATESTANDBLEND | |
  43540. *
  43541. */
  43542. set: function (value) {
  43543. if (this._transparencyMode === value) {
  43544. return;
  43545. }
  43546. this._transparencyMode = value;
  43547. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43548. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43549. },
  43550. enumerable: true,
  43551. configurable: true
  43552. });
  43553. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43554. /**
  43555. * Returns true if alpha blending should be disabled.
  43556. */
  43557. get: function () {
  43558. return (this._linkRefractionWithTransparency ||
  43559. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43560. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43561. },
  43562. enumerable: true,
  43563. configurable: true
  43564. });
  43565. /**
  43566. * Specifies whether or not this material should be rendered in alpha blend mode.
  43567. */
  43568. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43569. if (this._disableAlphaBlending) {
  43570. return false;
  43571. }
  43572. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43573. };
  43574. /**
  43575. * Specifies if the mesh will require alpha blending.
  43576. * @param mesh - BJS mesh.
  43577. */
  43578. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43579. if (this._disableAlphaBlending) {
  43580. return false;
  43581. }
  43582. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43583. };
  43584. /**
  43585. * Specifies whether or not this material should be rendered in alpha test mode.
  43586. */
  43587. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43588. if (this._forceAlphaTest) {
  43589. return true;
  43590. }
  43591. if (this._linkRefractionWithTransparency) {
  43592. return false;
  43593. }
  43594. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43595. };
  43596. /**
  43597. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43598. */
  43599. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43600. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43601. };
  43602. /**
  43603. * Gets the texture used for the alpha test.
  43604. */
  43605. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43606. return this._albedoTexture;
  43607. };
  43608. /**
  43609. * Specifies that the submesh is ready to be used.
  43610. * @param mesh - BJS mesh.
  43611. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43612. * @param useInstances - Specifies that instances should be used.
  43613. * @returns - boolean indicating that the submesh is ready or not.
  43614. */
  43615. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43616. if (subMesh.effect && this.isFrozen) {
  43617. if (this._wasPreviouslyReady) {
  43618. return true;
  43619. }
  43620. }
  43621. if (!subMesh._materialDefines) {
  43622. subMesh._materialDefines = new PBRMaterialDefines();
  43623. }
  43624. var defines = subMesh._materialDefines;
  43625. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43626. if (defines._renderId === this.getScene().getRenderId()) {
  43627. return true;
  43628. }
  43629. }
  43630. var scene = this.getScene();
  43631. var engine = scene.getEngine();
  43632. if (defines._areTexturesDirty) {
  43633. if (scene.texturesEnabled) {
  43634. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43635. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43636. return false;
  43637. }
  43638. }
  43639. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43640. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43641. return false;
  43642. }
  43643. }
  43644. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43645. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43646. return false;
  43647. }
  43648. }
  43649. var reflectionTexture = this._getReflectionTexture();
  43650. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43651. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43652. return false;
  43653. }
  43654. }
  43655. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43656. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43657. return false;
  43658. }
  43659. }
  43660. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43661. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43662. return false;
  43663. }
  43664. }
  43665. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43666. if (this._metallicTexture) {
  43667. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43668. return false;
  43669. }
  43670. }
  43671. else if (this._reflectivityTexture) {
  43672. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43673. return false;
  43674. }
  43675. }
  43676. if (this._microSurfaceTexture) {
  43677. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43678. return false;
  43679. }
  43680. }
  43681. }
  43682. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43683. // Bump texture cannot be not blocking.
  43684. if (!this._bumpTexture.isReady()) {
  43685. return false;
  43686. }
  43687. }
  43688. var refractionTexture = this._getRefractionTexture();
  43689. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43690. if (!refractionTexture.isReadyOrNotBlocking()) {
  43691. return false;
  43692. }
  43693. }
  43694. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43695. // This is blocking.
  43696. if (!this._environmentBRDFTexture.isReady()) {
  43697. return false;
  43698. }
  43699. }
  43700. }
  43701. }
  43702. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43703. if (!this._imageProcessingConfiguration.isReady()) {
  43704. return false;
  43705. }
  43706. }
  43707. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43708. mesh.createNormals(true);
  43709. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43710. }
  43711. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43712. if (effect) {
  43713. scene.resetCachedMaterial();
  43714. subMesh.setEffect(effect, defines);
  43715. this.buildUniformLayout();
  43716. }
  43717. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43718. return false;
  43719. }
  43720. defines._renderId = scene.getRenderId();
  43721. this._wasPreviouslyReady = true;
  43722. return true;
  43723. };
  43724. /**
  43725. * Specifies if the material uses metallic roughness workflow.
  43726. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43727. */
  43728. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43729. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43730. return true;
  43731. }
  43732. return false;
  43733. };
  43734. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43735. if (onCompiled === void 0) { onCompiled = null; }
  43736. if (onError === void 0) { onError = null; }
  43737. if (useInstances === void 0) { useInstances = null; }
  43738. if (useClipPlane === void 0) { useClipPlane = null; }
  43739. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43740. if (!defines.isDirty) {
  43741. return null;
  43742. }
  43743. defines.markAsProcessed();
  43744. var scene = this.getScene();
  43745. var engine = scene.getEngine();
  43746. // Fallbacks
  43747. var fallbacks = new BABYLON.EffectFallbacks();
  43748. var fallbackRank = 0;
  43749. if (defines.USESPHERICALINVERTEX) {
  43750. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43751. }
  43752. if (defines.FOG) {
  43753. fallbacks.addFallback(fallbackRank, "FOG");
  43754. }
  43755. if (defines.SPECULARAA) {
  43756. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43757. }
  43758. if (defines.POINTSIZE) {
  43759. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43760. }
  43761. if (defines.LOGARITHMICDEPTH) {
  43762. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43763. }
  43764. if (defines.PARALLAX) {
  43765. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43766. }
  43767. if (defines.PARALLAXOCCLUSION) {
  43768. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43769. }
  43770. if (defines.ENVIRONMENTBRDF) {
  43771. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43772. }
  43773. if (defines.TANGENT) {
  43774. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43775. }
  43776. if (defines.BUMP) {
  43777. fallbacks.addFallback(fallbackRank++, "BUMP");
  43778. }
  43779. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43780. if (defines.SPECULARTERM) {
  43781. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43782. }
  43783. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43784. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43785. }
  43786. if (defines.LIGHTMAP) {
  43787. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43788. }
  43789. if (defines.NORMAL) {
  43790. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43791. }
  43792. if (defines.AMBIENT) {
  43793. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43794. }
  43795. if (defines.EMISSIVE) {
  43796. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43797. }
  43798. if (defines.VERTEXCOLOR) {
  43799. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43800. }
  43801. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43802. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43803. }
  43804. if (defines.MORPHTARGETS) {
  43805. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43806. }
  43807. //Attributes
  43808. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43809. if (defines.NORMAL) {
  43810. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43811. }
  43812. if (defines.TANGENT) {
  43813. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43814. }
  43815. if (defines.UV1) {
  43816. attribs.push(BABYLON.VertexBuffer.UVKind);
  43817. }
  43818. if (defines.UV2) {
  43819. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43820. }
  43821. if (defines.VERTEXCOLOR) {
  43822. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43823. }
  43824. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43825. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43826. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43827. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43828. "vFogInfos", "vFogColor", "pointSize",
  43829. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43830. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43831. "mBones",
  43832. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43833. "vLightingIntensity",
  43834. "logarithmicDepthConstant",
  43835. "vSphericalX", "vSphericalY", "vSphericalZ",
  43836. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43837. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43838. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43839. "vTangentSpaceParams"
  43840. ];
  43841. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43842. "bumpSampler", "lightmapSampler", "opacitySampler",
  43843. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43844. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43845. "microSurfaceSampler", "environmentBrdfSampler"];
  43846. var uniformBuffers = ["Material", "Scene"];
  43847. if (BABYLON.ImageProcessingConfiguration) {
  43848. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43849. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43850. }
  43851. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43852. uniformsNames: uniforms,
  43853. uniformBuffersNames: uniformBuffers,
  43854. samplers: samplers,
  43855. defines: defines,
  43856. maxSimultaneousLights: this._maxSimultaneousLights
  43857. });
  43858. var join = defines.toString();
  43859. return engine.createEffect("pbr", {
  43860. attributes: attribs,
  43861. uniformsNames: uniforms,
  43862. uniformBuffersNames: uniformBuffers,
  43863. samplers: samplers,
  43864. defines: join,
  43865. fallbacks: fallbacks,
  43866. onCompiled: onCompiled,
  43867. onError: onError,
  43868. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43869. }, engine);
  43870. };
  43871. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43872. if (useInstances === void 0) { useInstances = null; }
  43873. if (useClipPlane === void 0) { useClipPlane = null; }
  43874. var scene = this.getScene();
  43875. var engine = scene.getEngine();
  43876. // Lights
  43877. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43878. defines._needNormals = true;
  43879. // Textures
  43880. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43881. if (defines._areTexturesDirty) {
  43882. defines._needUVs = false;
  43883. if (scene.texturesEnabled) {
  43884. if (scene.getEngine().getCaps().textureLOD) {
  43885. defines.LODBASEDMICROSFURACE = true;
  43886. }
  43887. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43888. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43889. }
  43890. else {
  43891. defines.ALBEDO = false;
  43892. }
  43893. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43894. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43895. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43896. }
  43897. else {
  43898. defines.AMBIENT = false;
  43899. }
  43900. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43901. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43902. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43903. }
  43904. else {
  43905. defines.OPACITY = false;
  43906. }
  43907. var reflectionTexture = this._getReflectionTexture();
  43908. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43909. defines.REFLECTION = true;
  43910. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43911. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43912. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43913. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43914. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43915. defines.INVERTCUBICMAP = true;
  43916. }
  43917. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43918. switch (reflectionTexture.coordinatesMode) {
  43919. case BABYLON.Texture.EXPLICIT_MODE:
  43920. defines.REFLECTIONMAP_EXPLICIT = true;
  43921. break;
  43922. case BABYLON.Texture.PLANAR_MODE:
  43923. defines.REFLECTIONMAP_PLANAR = true;
  43924. break;
  43925. case BABYLON.Texture.PROJECTION_MODE:
  43926. defines.REFLECTIONMAP_PROJECTION = true;
  43927. break;
  43928. case BABYLON.Texture.SKYBOX_MODE:
  43929. defines.REFLECTIONMAP_SKYBOX = true;
  43930. break;
  43931. case BABYLON.Texture.SPHERICAL_MODE:
  43932. defines.REFLECTIONMAP_SPHERICAL = true;
  43933. break;
  43934. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43935. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43936. break;
  43937. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43938. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43939. break;
  43940. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43941. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43942. break;
  43943. case BABYLON.Texture.CUBIC_MODE:
  43944. case BABYLON.Texture.INVCUBIC_MODE:
  43945. default:
  43946. defines.REFLECTIONMAP_CUBIC = true;
  43947. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43948. break;
  43949. }
  43950. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43951. if (reflectionTexture.sphericalPolynomial) {
  43952. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43953. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43954. defines.USESPHERICALINVERTEX = false;
  43955. }
  43956. else {
  43957. defines.USESPHERICALINVERTEX = true;
  43958. }
  43959. }
  43960. }
  43961. else {
  43962. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43963. }
  43964. }
  43965. else {
  43966. defines.REFLECTION = false;
  43967. defines.REFLECTIONMAP_3D = false;
  43968. defines.REFLECTIONMAP_SPHERICAL = false;
  43969. defines.REFLECTIONMAP_PLANAR = false;
  43970. defines.REFLECTIONMAP_CUBIC = false;
  43971. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43972. defines.REFLECTIONMAP_PROJECTION = false;
  43973. defines.REFLECTIONMAP_SKYBOX = false;
  43974. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43975. defines.REFLECTIONMAP_EXPLICIT = false;
  43976. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43977. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43978. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43979. defines.INVERTCUBICMAP = false;
  43980. defines.USESPHERICALFROMREFLECTIONMAP = false;
  43981. defines.USESPHERICALINVERTEX = false;
  43982. defines.REFLECTIONMAP_OPPOSITEZ = false;
  43983. defines.LODINREFLECTIONALPHA = false;
  43984. defines.GAMMAREFLECTION = false;
  43985. defines.RGBDREFLECTION = false;
  43986. }
  43987. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43988. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43989. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43990. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  43991. }
  43992. else {
  43993. defines.LIGHTMAP = false;
  43994. }
  43995. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43996. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43997. }
  43998. else {
  43999. defines.EMISSIVE = false;
  44000. }
  44001. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44002. if (this._metallicTexture) {
  44003. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44004. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44005. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44006. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44007. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44008. }
  44009. else if (this._reflectivityTexture) {
  44010. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44011. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44012. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44013. }
  44014. else {
  44015. defines.REFLECTIVITY = false;
  44016. }
  44017. if (this._microSurfaceTexture) {
  44018. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44019. }
  44020. else {
  44021. defines.MICROSURFACEMAP = false;
  44022. }
  44023. }
  44024. else {
  44025. defines.REFLECTIVITY = false;
  44026. defines.MICROSURFACEMAP = false;
  44027. }
  44028. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44029. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44030. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44031. defines.PARALLAX = true;
  44032. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44033. }
  44034. else {
  44035. defines.PARALLAX = false;
  44036. }
  44037. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44038. }
  44039. else {
  44040. defines.BUMP = false;
  44041. }
  44042. var refractionTexture = this._getRefractionTexture();
  44043. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44044. defines.REFRACTION = true;
  44045. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44046. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44047. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44048. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44049. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44050. if (this._linkRefractionWithTransparency) {
  44051. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44052. }
  44053. }
  44054. else {
  44055. defines.REFRACTION = false;
  44056. }
  44057. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44058. defines.ENVIRONMENTBRDF = true;
  44059. }
  44060. else {
  44061. defines.ENVIRONMENTBRDF = false;
  44062. }
  44063. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44064. defines.ALPHAFROMALBEDO = true;
  44065. }
  44066. else {
  44067. defines.ALPHAFROMALBEDO = false;
  44068. }
  44069. }
  44070. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44071. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44072. defines.USEPHYSICALLIGHTFALLOFF = false;
  44073. defines.USEGLTFLIGHTFALLOFF = false;
  44074. }
  44075. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44076. defines.USEPHYSICALLIGHTFALLOFF = false;
  44077. defines.USEGLTFLIGHTFALLOFF = true;
  44078. }
  44079. else {
  44080. defines.USEPHYSICALLIGHTFALLOFF = true;
  44081. defines.USEGLTFLIGHTFALLOFF = false;
  44082. }
  44083. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44084. if (!this.backFaceCulling && this._twoSidedLighting) {
  44085. defines.TWOSIDEDLIGHTING = true;
  44086. }
  44087. else {
  44088. defines.TWOSIDEDLIGHTING = false;
  44089. }
  44090. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44091. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44092. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44093. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44094. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44095. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44096. }
  44097. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44098. this._imageProcessingConfiguration.prepareDefines(defines);
  44099. }
  44100. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44101. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44102. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44103. // Misc.
  44104. if (defines._areMiscDirty) {
  44105. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44106. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44107. }
  44108. // Values that need to be evaluated on every frame
  44109. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44110. // Attribs
  44111. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44112. };
  44113. /**
  44114. * Force shader compilation
  44115. */
  44116. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44117. var _this = this;
  44118. var localOptions = __assign({ clipPlane: false }, options);
  44119. var defines = new PBRMaterialDefines();
  44120. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44121. if (effect.isReady()) {
  44122. if (onCompiled) {
  44123. onCompiled(this);
  44124. }
  44125. }
  44126. else {
  44127. effect.onCompileObservable.add(function () {
  44128. if (onCompiled) {
  44129. onCompiled(_this);
  44130. }
  44131. });
  44132. }
  44133. };
  44134. /**
  44135. * Initializes the uniform buffer layout for the shader.
  44136. */
  44137. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44138. // Order is important !
  44139. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44140. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44141. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44142. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44143. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44144. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44145. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44146. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44147. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44148. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44149. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44150. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44151. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44152. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44153. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44154. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44155. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44156. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44157. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44158. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44159. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44160. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44161. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44162. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44163. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44164. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44165. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44166. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44167. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44168. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44169. this._uniformBuffer.addUniform("pointSize", 1);
  44170. this._uniformBuffer.create();
  44171. };
  44172. /**
  44173. * Unbinds the textures.
  44174. */
  44175. PBRBaseMaterial.prototype.unbind = function () {
  44176. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44177. this._uniformBuffer.setTexture("reflectionSampler", null);
  44178. }
  44179. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44180. this._uniformBuffer.setTexture("refractionSampler", null);
  44181. }
  44182. _super.prototype.unbind.call(this);
  44183. };
  44184. /**
  44185. * Binds the submesh data.
  44186. * @param world - The world matrix.
  44187. * @param mesh - The BJS mesh.
  44188. * @param subMesh - A submesh of the BJS mesh.
  44189. */
  44190. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44191. var scene = this.getScene();
  44192. var defines = subMesh._materialDefines;
  44193. if (!defines) {
  44194. return;
  44195. }
  44196. var effect = subMesh.effect;
  44197. if (!effect) {
  44198. return;
  44199. }
  44200. this._activeEffect = effect;
  44201. // Matrices
  44202. this.bindOnlyWorldMatrix(world);
  44203. // Normal Matrix
  44204. if (defines.OBJECTSPACE_NORMALMAP) {
  44205. world.toNormalMatrix(this._normalMatrix);
  44206. this.bindOnlyNormalMatrix(this._normalMatrix);
  44207. }
  44208. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44209. // Bones
  44210. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44211. var reflectionTexture = null;
  44212. if (mustRebind) {
  44213. this._uniformBuffer.bindToEffect(effect, "Material");
  44214. this.bindViewProjection(effect);
  44215. reflectionTexture = this._getReflectionTexture();
  44216. var refractionTexture = this._getRefractionTexture();
  44217. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44218. // Texture uniforms
  44219. if (scene.texturesEnabled) {
  44220. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44221. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44222. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44223. }
  44224. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44225. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44226. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44227. }
  44228. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44229. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44230. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44231. }
  44232. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44233. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44234. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44235. if (reflectionTexture.boundingBoxSize) {
  44236. var cubeTexture = reflectionTexture;
  44237. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44238. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44239. }
  44240. var polynomials = reflectionTexture.sphericalPolynomial;
  44241. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44242. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44243. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44244. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44245. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44246. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44247. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44248. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44249. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44250. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44251. }
  44252. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44253. }
  44254. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44255. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44256. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44257. }
  44258. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44259. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44260. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44261. }
  44262. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44263. if (this._metallicTexture) {
  44264. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44265. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44266. }
  44267. else if (this._reflectivityTexture) {
  44268. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44269. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44270. }
  44271. if (this._microSurfaceTexture) {
  44272. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44273. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44274. }
  44275. }
  44276. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44277. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44278. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44279. if (scene._mirroredCameraPosition) {
  44280. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44281. }
  44282. else {
  44283. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44284. }
  44285. }
  44286. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44287. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44288. var depth = 1.0;
  44289. if (!refractionTexture.isCube) {
  44290. if (refractionTexture.depth) {
  44291. depth = refractionTexture.depth;
  44292. }
  44293. }
  44294. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44295. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44296. }
  44297. }
  44298. // Point size
  44299. if (this.pointsCloud) {
  44300. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44301. }
  44302. // Colors
  44303. if (defines.METALLICWORKFLOW) {
  44304. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44305. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44306. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44307. }
  44308. else {
  44309. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44310. }
  44311. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44312. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44313. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44314. // Misc
  44315. this._lightingInfos.x = this._directIntensity;
  44316. this._lightingInfos.y = this._emissiveIntensity;
  44317. this._lightingInfos.z = this._environmentIntensity;
  44318. this._lightingInfos.w = this._specularIntensity;
  44319. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44320. }
  44321. // Textures
  44322. if (scene.texturesEnabled) {
  44323. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44324. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44325. }
  44326. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44327. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44328. }
  44329. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44330. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44331. }
  44332. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44333. if (defines.LODBASEDMICROSFURACE) {
  44334. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44335. }
  44336. else {
  44337. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44338. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44339. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44340. }
  44341. }
  44342. if (defines.ENVIRONMENTBRDF) {
  44343. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44344. }
  44345. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44346. if (defines.LODBASEDMICROSFURACE) {
  44347. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44348. }
  44349. else {
  44350. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44351. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44352. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44353. }
  44354. }
  44355. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44356. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44357. }
  44358. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44359. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44360. }
  44361. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44362. if (this._metallicTexture) {
  44363. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44364. }
  44365. else if (this._reflectivityTexture) {
  44366. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44367. }
  44368. if (this._microSurfaceTexture) {
  44369. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44370. }
  44371. }
  44372. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44373. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44374. }
  44375. }
  44376. // Clip plane
  44377. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44378. // Colors
  44379. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44380. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44381. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44382. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44383. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44384. }
  44385. if (mustRebind || !this.isFrozen) {
  44386. // Lights
  44387. if (scene.lightsEnabled && !this._disableLighting) {
  44388. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44389. }
  44390. // View
  44391. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44392. this.bindView(effect);
  44393. }
  44394. // Fog
  44395. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44396. // Morph targets
  44397. if (defines.NUM_MORPH_INFLUENCERS) {
  44398. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44399. }
  44400. // image processing
  44401. this._imageProcessingConfiguration.bind(this._activeEffect);
  44402. // Log. depth
  44403. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44404. }
  44405. this._uniformBuffer.update();
  44406. this._afterBind(mesh, this._activeEffect);
  44407. };
  44408. /**
  44409. * Returns the animatable textures.
  44410. * @returns - Array of animatable textures.
  44411. */
  44412. PBRBaseMaterial.prototype.getAnimatables = function () {
  44413. var results = [];
  44414. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44415. results.push(this._albedoTexture);
  44416. }
  44417. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44418. results.push(this._ambientTexture);
  44419. }
  44420. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44421. results.push(this._opacityTexture);
  44422. }
  44423. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44424. results.push(this._reflectionTexture);
  44425. }
  44426. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44427. results.push(this._emissiveTexture);
  44428. }
  44429. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44430. results.push(this._metallicTexture);
  44431. }
  44432. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44433. results.push(this._reflectivityTexture);
  44434. }
  44435. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44436. results.push(this._bumpTexture);
  44437. }
  44438. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44439. results.push(this._lightmapTexture);
  44440. }
  44441. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44442. results.push(this._refractionTexture);
  44443. }
  44444. return results;
  44445. };
  44446. /**
  44447. * Returns the texture used for reflections.
  44448. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44449. */
  44450. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44451. if (this._reflectionTexture) {
  44452. return this._reflectionTexture;
  44453. }
  44454. return this.getScene().environmentTexture;
  44455. };
  44456. /**
  44457. * Returns the texture used for refraction or null if none is used.
  44458. * @returns - Refection texture if present. If no refraction texture and refraction
  44459. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44460. */
  44461. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44462. if (this._refractionTexture) {
  44463. return this._refractionTexture;
  44464. }
  44465. if (this._linkRefractionWithTransparency) {
  44466. return this.getScene().environmentTexture;
  44467. }
  44468. return null;
  44469. };
  44470. /**
  44471. * Disposes the resources of the material.
  44472. * @param forceDisposeEffect - Forces the disposal of effects.
  44473. * @param forceDisposeTextures - Forces the disposal of all textures.
  44474. */
  44475. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44476. if (forceDisposeTextures) {
  44477. if (this._albedoTexture) {
  44478. this._albedoTexture.dispose();
  44479. }
  44480. if (this._ambientTexture) {
  44481. this._ambientTexture.dispose();
  44482. }
  44483. if (this._opacityTexture) {
  44484. this._opacityTexture.dispose();
  44485. }
  44486. if (this._reflectionTexture) {
  44487. this._reflectionTexture.dispose();
  44488. }
  44489. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44490. this._environmentBRDFTexture.dispose();
  44491. }
  44492. if (this._emissiveTexture) {
  44493. this._emissiveTexture.dispose();
  44494. }
  44495. if (this._metallicTexture) {
  44496. this._metallicTexture.dispose();
  44497. }
  44498. if (this._reflectivityTexture) {
  44499. this._reflectivityTexture.dispose();
  44500. }
  44501. if (this._bumpTexture) {
  44502. this._bumpTexture.dispose();
  44503. }
  44504. if (this._lightmapTexture) {
  44505. this._lightmapTexture.dispose();
  44506. }
  44507. if (this._refractionTexture) {
  44508. this._refractionTexture.dispose();
  44509. }
  44510. }
  44511. this._renderTargets.dispose();
  44512. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44513. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44514. }
  44515. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44516. };
  44517. /**
  44518. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44519. */
  44520. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44521. /**
  44522. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44523. * to enhance interoperability with other engines.
  44524. */
  44525. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44526. /**
  44527. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44528. * to enhance interoperability with other materials.
  44529. */
  44530. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44531. /**
  44532. * Stores the reflectivity values based on metallic roughness workflow.
  44533. */
  44534. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44535. __decorate([
  44536. BABYLON.serializeAsImageProcessingConfiguration()
  44537. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44538. __decorate([
  44539. BABYLON.serialize()
  44540. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44541. __decorate([
  44542. BABYLON.serialize()
  44543. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44544. return PBRBaseMaterial;
  44545. }(BABYLON.PushMaterial));
  44546. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44547. })(BABYLON || (BABYLON = {}));
  44548. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44549. var BABYLON;
  44550. (function (BABYLON) {
  44551. /**
  44552. * The Physically based simple base material of BJS.
  44553. *
  44554. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44555. * It is used as the base class for both the specGloss and metalRough conventions.
  44556. */
  44557. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44558. __extends(PBRBaseSimpleMaterial, _super);
  44559. /**
  44560. * Instantiates a new PBRMaterial instance.
  44561. *
  44562. * @param name The material name
  44563. * @param scene The scene the material will be use in.
  44564. */
  44565. function PBRBaseSimpleMaterial(name, scene) {
  44566. var _this = _super.call(this, name, scene) || this;
  44567. /**
  44568. * Number of Simultaneous lights allowed on the material.
  44569. */
  44570. _this.maxSimultaneousLights = 4;
  44571. /**
  44572. * If sets to true, disables all the lights affecting the material.
  44573. */
  44574. _this.disableLighting = false;
  44575. /**
  44576. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44577. */
  44578. _this.invertNormalMapX = false;
  44579. /**
  44580. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44581. */
  44582. _this.invertNormalMapY = false;
  44583. /**
  44584. * Emissivie color used to self-illuminate the model.
  44585. */
  44586. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44587. /**
  44588. * Occlusion Channel Strenght.
  44589. */
  44590. _this.occlusionStrength = 1.0;
  44591. _this.useLightmapAsShadowmap = false;
  44592. _this._useAlphaFromAlbedoTexture = true;
  44593. _this._useAmbientInGrayScale = true;
  44594. return _this;
  44595. }
  44596. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44597. /**
  44598. * Gets the current double sided mode.
  44599. */
  44600. get: function () {
  44601. return this._twoSidedLighting;
  44602. },
  44603. /**
  44604. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44605. */
  44606. set: function (value) {
  44607. if (this._twoSidedLighting === value) {
  44608. return;
  44609. }
  44610. this._twoSidedLighting = value;
  44611. this.backFaceCulling = !value;
  44612. this._markAllSubMeshesAsTexturesDirty();
  44613. },
  44614. enumerable: true,
  44615. configurable: true
  44616. });
  44617. /**
  44618. * Return the active textures of the material.
  44619. */
  44620. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44621. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44622. if (this.environmentTexture) {
  44623. activeTextures.push(this.environmentTexture);
  44624. }
  44625. if (this.normalTexture) {
  44626. activeTextures.push(this.normalTexture);
  44627. }
  44628. if (this.emissiveTexture) {
  44629. activeTextures.push(this.emissiveTexture);
  44630. }
  44631. if (this.occlusionTexture) {
  44632. activeTextures.push(this.occlusionTexture);
  44633. }
  44634. if (this.lightmapTexture) {
  44635. activeTextures.push(this.lightmapTexture);
  44636. }
  44637. return activeTextures;
  44638. };
  44639. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44640. if (_super.prototype.hasTexture.call(this, texture)) {
  44641. return true;
  44642. }
  44643. if (this.lightmapTexture === texture) {
  44644. return true;
  44645. }
  44646. return false;
  44647. };
  44648. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44649. return "PBRBaseSimpleMaterial";
  44650. };
  44651. __decorate([
  44652. BABYLON.serialize(),
  44653. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44654. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44655. __decorate([
  44656. BABYLON.serialize(),
  44657. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44658. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44659. __decorate([
  44660. BABYLON.serializeAsTexture(),
  44661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44662. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44663. __decorate([
  44664. BABYLON.serialize(),
  44665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44666. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44667. __decorate([
  44668. BABYLON.serialize(),
  44669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44670. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44671. __decorate([
  44672. BABYLON.serializeAsTexture(),
  44673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44674. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44675. __decorate([
  44676. BABYLON.serializeAsColor3("emissive"),
  44677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44678. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44679. __decorate([
  44680. BABYLON.serializeAsTexture(),
  44681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44682. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44683. __decorate([
  44684. BABYLON.serialize(),
  44685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44686. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44687. __decorate([
  44688. BABYLON.serializeAsTexture(),
  44689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44690. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44691. __decorate([
  44692. BABYLON.serialize(),
  44693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44694. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44695. __decorate([
  44696. BABYLON.serialize()
  44697. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44698. __decorate([
  44699. BABYLON.serializeAsTexture(),
  44700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44701. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44702. __decorate([
  44703. BABYLON.serialize(),
  44704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44705. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44706. return PBRBaseSimpleMaterial;
  44707. }(BABYLON.PBRBaseMaterial));
  44708. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44709. })(BABYLON || (BABYLON = {}));
  44710. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44711. var BABYLON;
  44712. (function (BABYLON) {
  44713. /**
  44714. * The Physically based material of BJS.
  44715. *
  44716. * This offers the main features of a standard PBR material.
  44717. * For more information, please refer to the documentation :
  44718. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44719. */
  44720. var PBRMaterial = /** @class */ (function (_super) {
  44721. __extends(PBRMaterial, _super);
  44722. /**
  44723. * Instantiates a new PBRMaterial instance.
  44724. *
  44725. * @param name The material name
  44726. * @param scene The scene the material will be use in.
  44727. */
  44728. function PBRMaterial(name, scene) {
  44729. var _this = _super.call(this, name, scene) || this;
  44730. /**
  44731. * Intensity of the direct lights e.g. the four lights available in your scene.
  44732. * This impacts both the direct diffuse and specular highlights.
  44733. */
  44734. _this.directIntensity = 1.0;
  44735. /**
  44736. * Intensity of the emissive part of the material.
  44737. * This helps controlling the emissive effect without modifying the emissive color.
  44738. */
  44739. _this.emissiveIntensity = 1.0;
  44740. /**
  44741. * Intensity of the environment e.g. how much the environment will light the object
  44742. * either through harmonics for rough material or through the refelction for shiny ones.
  44743. */
  44744. _this.environmentIntensity = 1.0;
  44745. /**
  44746. * This is a special control allowing the reduction of the specular highlights coming from the
  44747. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44748. */
  44749. _this.specularIntensity = 1.0;
  44750. /**
  44751. * Debug Control allowing disabling the bump map on this material.
  44752. */
  44753. _this.disableBumpMap = false;
  44754. /**
  44755. * AKA Occlusion Texture Intensity in other nomenclature.
  44756. */
  44757. _this.ambientTextureStrength = 1.0;
  44758. /**
  44759. * Defines how much the AO map is occluding the analytical lights (point spot...).
  44760. * 1 means it completely occludes it
  44761. * 0 mean it has no impact
  44762. */
  44763. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  44764. /**
  44765. * The color of a material in ambient lighting.
  44766. */
  44767. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44768. /**
  44769. * AKA Diffuse Color in other nomenclature.
  44770. */
  44771. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44772. /**
  44773. * AKA Specular Color in other nomenclature.
  44774. */
  44775. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44776. /**
  44777. * The color reflected from the material.
  44778. */
  44779. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44780. /**
  44781. * The color emitted from the material.
  44782. */
  44783. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44784. /**
  44785. * AKA Glossiness in other nomenclature.
  44786. */
  44787. _this.microSurface = 1.0;
  44788. /**
  44789. * source material index of refraction (IOR)' / 'destination material IOR.
  44790. */
  44791. _this.indexOfRefraction = 0.66;
  44792. /**
  44793. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44794. */
  44795. _this.invertRefractionY = false;
  44796. /**
  44797. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44798. * Materials half opaque for instance using refraction could benefit from this control.
  44799. */
  44800. _this.linkRefractionWithTransparency = false;
  44801. _this.useLightmapAsShadowmap = false;
  44802. /**
  44803. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44804. */
  44805. _this.useAlphaFromAlbedoTexture = false;
  44806. /**
  44807. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44808. */
  44809. _this.forceAlphaTest = false;
  44810. /**
  44811. * Defines the alpha limits in alpha test mode.
  44812. */
  44813. _this.alphaCutOff = 0.4;
  44814. /**
  44815. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44816. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44817. */
  44818. _this.useSpecularOverAlpha = true;
  44819. /**
  44820. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44821. */
  44822. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44823. /**
  44824. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44825. */
  44826. _this.useRoughnessFromMetallicTextureAlpha = true;
  44827. /**
  44828. * Specifies if the metallic texture contains the roughness information in its green channel.
  44829. */
  44830. _this.useRoughnessFromMetallicTextureGreen = false;
  44831. /**
  44832. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44833. */
  44834. _this.useMetallnessFromMetallicTextureBlue = false;
  44835. /**
  44836. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44837. */
  44838. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44839. /**
  44840. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44841. */
  44842. _this.useAmbientInGrayScale = false;
  44843. /**
  44844. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44845. * The material will try to infer what glossiness each pixel should be.
  44846. */
  44847. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44848. /**
  44849. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44850. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44851. */
  44852. _this.useRadianceOverAlpha = true;
  44853. /**
  44854. * Allows using an object space normal map (instead of tangent space).
  44855. */
  44856. _this.useObjectSpaceNormalMap = false;
  44857. /**
  44858. * Allows using the bump map in parallax mode.
  44859. */
  44860. _this.useParallax = false;
  44861. /**
  44862. * Allows using the bump map in parallax occlusion mode.
  44863. */
  44864. _this.useParallaxOcclusion = false;
  44865. /**
  44866. * Controls the scale bias of the parallax mode.
  44867. */
  44868. _this.parallaxScaleBias = 0.05;
  44869. /**
  44870. * If sets to true, disables all the lights affecting the material.
  44871. */
  44872. _this.disableLighting = false;
  44873. /**
  44874. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44875. */
  44876. _this.forceIrradianceInFragment = false;
  44877. /**
  44878. * Number of Simultaneous lights allowed on the material.
  44879. */
  44880. _this.maxSimultaneousLights = 4;
  44881. /**
  44882. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44883. */
  44884. _this.invertNormalMapX = false;
  44885. /**
  44886. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44887. */
  44888. _this.invertNormalMapY = false;
  44889. /**
  44890. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44891. */
  44892. _this.twoSidedLighting = false;
  44893. /**
  44894. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44895. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44896. */
  44897. _this.useAlphaFresnel = false;
  44898. /**
  44899. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44900. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44901. */
  44902. _this.useLinearAlphaFresnel = false;
  44903. /**
  44904. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44905. * And/Or occlude the blended part.
  44906. */
  44907. _this.environmentBRDFTexture = null;
  44908. /**
  44909. * Force normal to face away from face.
  44910. */
  44911. _this.forceNormalForward = false;
  44912. /**
  44913. * Enables specular anti aliasing in the PBR shader.
  44914. * It will both interacts on the Geometry for analytical and IBL lighting.
  44915. * It also prefilter the roughness map based on the bump values.
  44916. */
  44917. _this.enableSpecularAntiAliasing = false;
  44918. /**
  44919. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44920. * makes the reflect vector face the model (under horizon).
  44921. */
  44922. _this.useHorizonOcclusion = true;
  44923. /**
  44924. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44925. * too much the area relying on ambient texture to define their ambient occlusion.
  44926. */
  44927. _this.useRadianceOcclusion = true;
  44928. /**
  44929. * If set to true, no lighting calculations will be applied.
  44930. */
  44931. _this.unlit = false;
  44932. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44933. return _this;
  44934. }
  44935. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  44936. /**
  44937. * BJS is using an harcoded light falloff based on a manually sets up range.
  44938. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44939. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44940. */
  44941. get: function () {
  44942. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44943. },
  44944. /**
  44945. * BJS is using an harcoded light falloff based on a manually sets up range.
  44946. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44947. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44948. */
  44949. set: function (value) {
  44950. if (value !== this.usePhysicalLightFalloff) {
  44951. // Ensure the effect will be rebuilt.
  44952. this._markAllSubMeshesAsTexturesDirty();
  44953. if (value) {
  44954. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44955. }
  44956. else {
  44957. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  44958. }
  44959. }
  44960. },
  44961. enumerable: true,
  44962. configurable: true
  44963. });
  44964. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  44965. /**
  44966. * In order to support the falloff compatibility with gltf, a special mode has been added
  44967. * to reproduce the gltf light falloff.
  44968. */
  44969. get: function () {
  44970. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  44971. },
  44972. /**
  44973. * In order to support the falloff compatibility with gltf, a special mode has been added
  44974. * to reproduce the gltf light falloff.
  44975. */
  44976. set: function (value) {
  44977. if (value !== this.useGLTFLightFalloff) {
  44978. // Ensure the effect will be rebuilt.
  44979. this._markAllSubMeshesAsTexturesDirty();
  44980. if (value) {
  44981. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  44982. }
  44983. else {
  44984. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  44985. }
  44986. }
  44987. },
  44988. enumerable: true,
  44989. configurable: true
  44990. });
  44991. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44992. /**
  44993. * Gets the image processing configuration used either in this material.
  44994. */
  44995. get: function () {
  44996. return this._imageProcessingConfiguration;
  44997. },
  44998. /**
  44999. * Sets the Default image processing configuration used either in the this material.
  45000. *
  45001. * If sets to null, the scene one is in use.
  45002. */
  45003. set: function (value) {
  45004. this._attachImageProcessingConfiguration(value);
  45005. // Ensure the effect will be rebuilt.
  45006. this._markAllSubMeshesAsTexturesDirty();
  45007. },
  45008. enumerable: true,
  45009. configurable: true
  45010. });
  45011. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45012. /**
  45013. * Gets wether the color curves effect is enabled.
  45014. */
  45015. get: function () {
  45016. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45017. },
  45018. /**
  45019. * Sets wether the color curves effect is enabled.
  45020. */
  45021. set: function (value) {
  45022. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45023. },
  45024. enumerable: true,
  45025. configurable: true
  45026. });
  45027. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45028. /**
  45029. * Gets wether the color grading effect is enabled.
  45030. */
  45031. get: function () {
  45032. return this.imageProcessingConfiguration.colorGradingEnabled;
  45033. },
  45034. /**
  45035. * Gets wether the color grading effect is enabled.
  45036. */
  45037. set: function (value) {
  45038. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45039. },
  45040. enumerable: true,
  45041. configurable: true
  45042. });
  45043. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45044. /**
  45045. * Gets wether tonemapping is enabled or not.
  45046. */
  45047. get: function () {
  45048. return this._imageProcessingConfiguration.toneMappingEnabled;
  45049. },
  45050. /**
  45051. * Sets wether tonemapping is enabled or not
  45052. */
  45053. set: function (value) {
  45054. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45055. },
  45056. enumerable: true,
  45057. configurable: true
  45058. });
  45059. ;
  45060. ;
  45061. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45062. /**
  45063. * The camera exposure used on this material.
  45064. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45065. * This corresponds to a photographic exposure.
  45066. */
  45067. get: function () {
  45068. return this._imageProcessingConfiguration.exposure;
  45069. },
  45070. /**
  45071. * The camera exposure used on this material.
  45072. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45073. * This corresponds to a photographic exposure.
  45074. */
  45075. set: function (value) {
  45076. this._imageProcessingConfiguration.exposure = value;
  45077. },
  45078. enumerable: true,
  45079. configurable: true
  45080. });
  45081. ;
  45082. ;
  45083. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45084. /**
  45085. * Gets The camera contrast used on this material.
  45086. */
  45087. get: function () {
  45088. return this._imageProcessingConfiguration.contrast;
  45089. },
  45090. /**
  45091. * Sets The camera contrast used on this material.
  45092. */
  45093. set: function (value) {
  45094. this._imageProcessingConfiguration.contrast = value;
  45095. },
  45096. enumerable: true,
  45097. configurable: true
  45098. });
  45099. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45100. /**
  45101. * Gets the Color Grading 2D Lookup Texture.
  45102. */
  45103. get: function () {
  45104. return this._imageProcessingConfiguration.colorGradingTexture;
  45105. },
  45106. /**
  45107. * Sets the Color Grading 2D Lookup Texture.
  45108. */
  45109. set: function (value) {
  45110. this._imageProcessingConfiguration.colorGradingTexture = value;
  45111. },
  45112. enumerable: true,
  45113. configurable: true
  45114. });
  45115. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45116. /**
  45117. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45118. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45119. * 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;
  45120. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45121. */
  45122. get: function () {
  45123. return this._imageProcessingConfiguration.colorCurves;
  45124. },
  45125. /**
  45126. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45127. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45128. * 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;
  45129. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45130. */
  45131. set: function (value) {
  45132. this._imageProcessingConfiguration.colorCurves = value;
  45133. },
  45134. enumerable: true,
  45135. configurable: true
  45136. });
  45137. /**
  45138. * Returns the name of this material class.
  45139. */
  45140. PBRMaterial.prototype.getClassName = function () {
  45141. return "PBRMaterial";
  45142. };
  45143. /**
  45144. * Returns an array of the actively used textures.
  45145. * @returns - Array of BaseTextures
  45146. */
  45147. PBRMaterial.prototype.getActiveTextures = function () {
  45148. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45149. if (this._albedoTexture) {
  45150. activeTextures.push(this._albedoTexture);
  45151. }
  45152. if (this._ambientTexture) {
  45153. activeTextures.push(this._ambientTexture);
  45154. }
  45155. if (this._opacityTexture) {
  45156. activeTextures.push(this._opacityTexture);
  45157. }
  45158. if (this._reflectionTexture) {
  45159. activeTextures.push(this._reflectionTexture);
  45160. }
  45161. if (this._emissiveTexture) {
  45162. activeTextures.push(this._emissiveTexture);
  45163. }
  45164. if (this._reflectivityTexture) {
  45165. activeTextures.push(this._reflectivityTexture);
  45166. }
  45167. if (this._metallicTexture) {
  45168. activeTextures.push(this._metallicTexture);
  45169. }
  45170. if (this._microSurfaceTexture) {
  45171. activeTextures.push(this._microSurfaceTexture);
  45172. }
  45173. if (this._bumpTexture) {
  45174. activeTextures.push(this._bumpTexture);
  45175. }
  45176. if (this._lightmapTexture) {
  45177. activeTextures.push(this._lightmapTexture);
  45178. }
  45179. if (this._refractionTexture) {
  45180. activeTextures.push(this._refractionTexture);
  45181. }
  45182. return activeTextures;
  45183. };
  45184. /**
  45185. * Checks to see if a texture is used in the material.
  45186. * @param texture - Base texture to use.
  45187. * @returns - Boolean specifying if a texture is used in the material.
  45188. */
  45189. PBRMaterial.prototype.hasTexture = function (texture) {
  45190. if (_super.prototype.hasTexture.call(this, texture)) {
  45191. return true;
  45192. }
  45193. if (this._albedoTexture === texture) {
  45194. return true;
  45195. }
  45196. if (this._ambientTexture === texture) {
  45197. return true;
  45198. }
  45199. if (this._opacityTexture === texture) {
  45200. return true;
  45201. }
  45202. if (this._reflectionTexture === texture) {
  45203. return true;
  45204. }
  45205. if (this._reflectivityTexture === texture) {
  45206. return true;
  45207. }
  45208. if (this._metallicTexture === texture) {
  45209. return true;
  45210. }
  45211. if (this._microSurfaceTexture === texture) {
  45212. return true;
  45213. }
  45214. if (this._bumpTexture === texture) {
  45215. return true;
  45216. }
  45217. if (this._lightmapTexture === texture) {
  45218. return true;
  45219. }
  45220. if (this._refractionTexture === texture) {
  45221. return true;
  45222. }
  45223. return false;
  45224. };
  45225. /**
  45226. * Makes a duplicate of the current material.
  45227. * @param name - name to use for the new material.
  45228. */
  45229. PBRMaterial.prototype.clone = function (name) {
  45230. var _this = this;
  45231. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45232. clone.id = name;
  45233. clone.name = name;
  45234. return clone;
  45235. };
  45236. /**
  45237. * Serializes this PBR Material.
  45238. * @returns - An object with the serialized material.
  45239. */
  45240. PBRMaterial.prototype.serialize = function () {
  45241. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45242. serializationObject.customType = "BABYLON.PBRMaterial";
  45243. return serializationObject;
  45244. };
  45245. // Statics
  45246. /**
  45247. * Parses a PBR Material from a serialized object.
  45248. * @param source - Serialized object.
  45249. * @param scene - BJS scene instance.
  45250. * @param rootUrl - url for the scene object
  45251. * @returns - PBRMaterial
  45252. */
  45253. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45254. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45255. };
  45256. /**
  45257. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45258. */
  45259. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45260. /**
  45261. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45262. */
  45263. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45264. /**
  45265. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45266. */
  45267. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45268. /**
  45269. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45270. * They are also discarded below the alpha cutoff threshold to improve performances.
  45271. */
  45272. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45273. /**
  45274. * Defines the default value of how much AO map is occluding the analytical lights
  45275. * (point spot...).
  45276. */
  45277. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45278. __decorate([
  45279. BABYLON.serialize(),
  45280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45281. ], PBRMaterial.prototype, "directIntensity", void 0);
  45282. __decorate([
  45283. BABYLON.serialize(),
  45284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45285. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45286. __decorate([
  45287. BABYLON.serialize(),
  45288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45289. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45290. __decorate([
  45291. BABYLON.serialize(),
  45292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45293. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45294. __decorate([
  45295. BABYLON.serialize(),
  45296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45297. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45298. __decorate([
  45299. BABYLON.serializeAsTexture(),
  45300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45301. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45302. __decorate([
  45303. BABYLON.serializeAsTexture(),
  45304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45305. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45306. __decorate([
  45307. BABYLON.serialize(),
  45308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45309. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45310. __decorate([
  45311. BABYLON.serialize(),
  45312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45313. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45314. __decorate([
  45315. BABYLON.serializeAsTexture(),
  45316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45317. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45318. __decorate([
  45319. BABYLON.serializeAsTexture(),
  45320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45321. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45322. __decorate([
  45323. BABYLON.serializeAsTexture(),
  45324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45325. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45326. __decorate([
  45327. BABYLON.serializeAsTexture(),
  45328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45329. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45330. __decorate([
  45331. BABYLON.serializeAsTexture(),
  45332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45333. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45334. __decorate([
  45335. BABYLON.serialize(),
  45336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45337. ], PBRMaterial.prototype, "metallic", void 0);
  45338. __decorate([
  45339. BABYLON.serialize(),
  45340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45341. ], PBRMaterial.prototype, "roughness", void 0);
  45342. __decorate([
  45343. BABYLON.serializeAsTexture(),
  45344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45345. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45346. __decorate([
  45347. BABYLON.serializeAsTexture(),
  45348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45349. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45350. __decorate([
  45351. BABYLON.serializeAsTexture(),
  45352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45353. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45354. __decorate([
  45355. BABYLON.serializeAsTexture(),
  45356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45357. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45358. __decorate([
  45359. BABYLON.serializeAsColor3("ambient"),
  45360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45361. ], PBRMaterial.prototype, "ambientColor", void 0);
  45362. __decorate([
  45363. BABYLON.serializeAsColor3("albedo"),
  45364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45365. ], PBRMaterial.prototype, "albedoColor", void 0);
  45366. __decorate([
  45367. BABYLON.serializeAsColor3("reflectivity"),
  45368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45369. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45370. __decorate([
  45371. BABYLON.serializeAsColor3("reflection"),
  45372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45373. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45374. __decorate([
  45375. BABYLON.serializeAsColor3("emissive"),
  45376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45377. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45378. __decorate([
  45379. BABYLON.serialize(),
  45380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45381. ], PBRMaterial.prototype, "microSurface", void 0);
  45382. __decorate([
  45383. BABYLON.serialize(),
  45384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45385. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45386. __decorate([
  45387. BABYLON.serialize(),
  45388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45389. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45390. __decorate([
  45391. BABYLON.serialize(),
  45392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45393. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45394. __decorate([
  45395. BABYLON.serialize(),
  45396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45397. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45398. __decorate([
  45399. BABYLON.serialize(),
  45400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45401. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45402. __decorate([
  45403. BABYLON.serialize(),
  45404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45405. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45406. __decorate([
  45407. BABYLON.serialize(),
  45408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45409. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45410. __decorate([
  45411. BABYLON.serialize(),
  45412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45413. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45414. __decorate([
  45415. BABYLON.serialize(),
  45416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45417. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45418. __decorate([
  45419. BABYLON.serialize(),
  45420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45421. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45422. __decorate([
  45423. BABYLON.serialize(),
  45424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45425. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45426. __decorate([
  45427. BABYLON.serialize(),
  45428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45429. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45430. __decorate([
  45431. BABYLON.serialize(),
  45432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45433. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45434. __decorate([
  45435. BABYLON.serialize(),
  45436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45437. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45438. __decorate([
  45439. BABYLON.serialize(),
  45440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45441. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45442. __decorate([
  45443. BABYLON.serialize()
  45444. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45445. __decorate([
  45446. BABYLON.serialize()
  45447. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45448. __decorate([
  45449. BABYLON.serialize(),
  45450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45451. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45452. __decorate([
  45453. BABYLON.serialize(),
  45454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45455. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45456. __decorate([
  45457. BABYLON.serialize(),
  45458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45459. ], PBRMaterial.prototype, "useParallax", void 0);
  45460. __decorate([
  45461. BABYLON.serialize(),
  45462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45463. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45464. __decorate([
  45465. BABYLON.serialize(),
  45466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45467. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45468. __decorate([
  45469. BABYLON.serialize(),
  45470. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45471. ], PBRMaterial.prototype, "disableLighting", void 0);
  45472. __decorate([
  45473. BABYLON.serialize(),
  45474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45475. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45476. __decorate([
  45477. BABYLON.serialize(),
  45478. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45479. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45480. __decorate([
  45481. BABYLON.serialize(),
  45482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45483. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45484. __decorate([
  45485. BABYLON.serialize(),
  45486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45487. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45488. __decorate([
  45489. BABYLON.serialize(),
  45490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45491. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45492. __decorate([
  45493. BABYLON.serialize(),
  45494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45495. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45496. __decorate([
  45497. BABYLON.serialize(),
  45498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45499. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45500. __decorate([
  45501. BABYLON.serializeAsTexture(),
  45502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45503. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45504. __decorate([
  45505. BABYLON.serialize(),
  45506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45507. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45508. __decorate([
  45509. BABYLON.serialize(),
  45510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45511. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45512. __decorate([
  45513. BABYLON.serialize(),
  45514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45515. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45516. __decorate([
  45517. BABYLON.serialize(),
  45518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45519. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45520. __decorate([
  45521. BABYLON.serialize(),
  45522. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45523. ], PBRMaterial.prototype, "unlit", void 0);
  45524. return PBRMaterial;
  45525. }(BABYLON.PBRBaseMaterial));
  45526. BABYLON.PBRMaterial = PBRMaterial;
  45527. })(BABYLON || (BABYLON = {}));
  45528. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45529. var BABYLON;
  45530. (function (BABYLON) {
  45531. /**
  45532. * The PBR material of BJS following the metal roughness convention.
  45533. *
  45534. * This fits to the PBR convention in the GLTF definition:
  45535. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45536. */
  45537. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45538. __extends(PBRMetallicRoughnessMaterial, _super);
  45539. /**
  45540. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45541. *
  45542. * @param name The material name
  45543. * @param scene The scene the material will be use in.
  45544. */
  45545. function PBRMetallicRoughnessMaterial(name, scene) {
  45546. var _this = _super.call(this, name, scene) || this;
  45547. _this._useRoughnessFromMetallicTextureAlpha = false;
  45548. _this._useRoughnessFromMetallicTextureGreen = true;
  45549. _this._useMetallnessFromMetallicTextureBlue = true;
  45550. _this.metallic = 1.0;
  45551. _this.roughness = 1.0;
  45552. return _this;
  45553. }
  45554. /**
  45555. * Return the currrent class name of the material.
  45556. */
  45557. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45558. return "PBRMetallicRoughnessMaterial";
  45559. };
  45560. /**
  45561. * Return the active textures of the material.
  45562. */
  45563. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45564. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45565. if (this.baseTexture) {
  45566. activeTextures.push(this.baseTexture);
  45567. }
  45568. if (this.metallicRoughnessTexture) {
  45569. activeTextures.push(this.metallicRoughnessTexture);
  45570. }
  45571. return activeTextures;
  45572. };
  45573. /**
  45574. * Checks to see if a texture is used in the material.
  45575. * @param texture - Base texture to use.
  45576. * @returns - Boolean specifying if a texture is used in the material.
  45577. */
  45578. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45579. if (_super.prototype.hasTexture.call(this, texture)) {
  45580. return true;
  45581. }
  45582. if (this.baseTexture === texture) {
  45583. return true;
  45584. }
  45585. if (this.metallicRoughnessTexture === texture) {
  45586. return true;
  45587. }
  45588. return false;
  45589. };
  45590. /**
  45591. * Makes a duplicate of the current material.
  45592. * @param name - name to use for the new material.
  45593. */
  45594. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45595. var _this = this;
  45596. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45597. clone.id = name;
  45598. clone.name = name;
  45599. return clone;
  45600. };
  45601. /**
  45602. * Serialize the material to a parsable JSON object.
  45603. */
  45604. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45605. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45606. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45607. return serializationObject;
  45608. };
  45609. /**
  45610. * Parses a JSON object correponding to the serialize function.
  45611. */
  45612. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45613. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45614. };
  45615. __decorate([
  45616. BABYLON.serializeAsColor3(),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45618. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45619. __decorate([
  45620. BABYLON.serializeAsTexture(),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45622. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45623. __decorate([
  45624. BABYLON.serialize(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45626. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45627. __decorate([
  45628. BABYLON.serialize(),
  45629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45630. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45631. __decorate([
  45632. BABYLON.serializeAsTexture(),
  45633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45634. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45635. return PBRMetallicRoughnessMaterial;
  45636. }(BABYLON.PBRBaseSimpleMaterial));
  45637. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45638. })(BABYLON || (BABYLON = {}));
  45639. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45640. var BABYLON;
  45641. (function (BABYLON) {
  45642. /**
  45643. * The PBR material of BJS following the specular glossiness convention.
  45644. *
  45645. * This fits to the PBR convention in the GLTF definition:
  45646. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45647. */
  45648. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45649. __extends(PBRSpecularGlossinessMaterial, _super);
  45650. /**
  45651. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45652. *
  45653. * @param name The material name
  45654. * @param scene The scene the material will be use in.
  45655. */
  45656. function PBRSpecularGlossinessMaterial(name, scene) {
  45657. var _this = _super.call(this, name, scene) || this;
  45658. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45659. return _this;
  45660. }
  45661. /**
  45662. * Return the currrent class name of the material.
  45663. */
  45664. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45665. return "PBRSpecularGlossinessMaterial";
  45666. };
  45667. /**
  45668. * Return the active textures of the material.
  45669. */
  45670. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45671. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45672. if (this.diffuseTexture) {
  45673. activeTextures.push(this.diffuseTexture);
  45674. }
  45675. if (this.specularGlossinessTexture) {
  45676. activeTextures.push(this.specularGlossinessTexture);
  45677. }
  45678. return activeTextures;
  45679. };
  45680. /**
  45681. * Checks to see if a texture is used in the material.
  45682. * @param texture - Base texture to use.
  45683. * @returns - Boolean specifying if a texture is used in the material.
  45684. */
  45685. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45686. if (_super.prototype.hasTexture.call(this, texture)) {
  45687. return true;
  45688. }
  45689. if (this.diffuseTexture === texture) {
  45690. return true;
  45691. }
  45692. if (this.specularGlossinessTexture === texture) {
  45693. return true;
  45694. }
  45695. return false;
  45696. };
  45697. /**
  45698. * Makes a duplicate of the current material.
  45699. * @param name - name to use for the new material.
  45700. */
  45701. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45702. var _this = this;
  45703. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45704. clone.id = name;
  45705. clone.name = name;
  45706. return clone;
  45707. };
  45708. /**
  45709. * Serialize the material to a parsable JSON object.
  45710. */
  45711. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45712. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45713. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45714. return serializationObject;
  45715. };
  45716. /**
  45717. * Parses a JSON object correponding to the serialize function.
  45718. */
  45719. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45720. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45721. };
  45722. __decorate([
  45723. BABYLON.serializeAsColor3("diffuse"),
  45724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45725. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45726. __decorate([
  45727. BABYLON.serializeAsTexture(),
  45728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45729. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45730. __decorate([
  45731. BABYLON.serializeAsColor3("specular"),
  45732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45733. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45734. __decorate([
  45735. BABYLON.serialize(),
  45736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45737. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45738. __decorate([
  45739. BABYLON.serializeAsTexture(),
  45740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45741. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45742. return PBRSpecularGlossinessMaterial;
  45743. }(BABYLON.PBRBaseSimpleMaterial));
  45744. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45745. })(BABYLON || (BABYLON = {}));
  45746. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45747. var BABYLON;
  45748. (function (BABYLON) {
  45749. BABYLON.CameraInputTypes = {};
  45750. var CameraInputsManager = /** @class */ (function () {
  45751. function CameraInputsManager(camera) {
  45752. this.attached = {};
  45753. this.camera = camera;
  45754. this.checkInputs = function () { };
  45755. }
  45756. /**
  45757. * Add an input method to a camera
  45758. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45759. * @param input camera input method
  45760. */
  45761. CameraInputsManager.prototype.add = function (input) {
  45762. var type = input.getSimpleName();
  45763. if (this.attached[type]) {
  45764. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45765. return;
  45766. }
  45767. this.attached[type] = input;
  45768. input.camera = this.camera;
  45769. //for checkInputs, we are dynamically creating a function
  45770. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45771. if (input.checkInputs) {
  45772. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45773. }
  45774. if (this.attachedElement) {
  45775. input.attachControl(this.attachedElement);
  45776. }
  45777. };
  45778. /**
  45779. * Remove a specific input method from a camera
  45780. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45781. * @param inputToRemove camera input method
  45782. */
  45783. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45784. for (var cam in this.attached) {
  45785. var input = this.attached[cam];
  45786. if (input === inputToRemove) {
  45787. input.detachControl(this.attachedElement);
  45788. input.camera = null;
  45789. delete this.attached[cam];
  45790. this.rebuildInputCheck();
  45791. }
  45792. }
  45793. };
  45794. CameraInputsManager.prototype.removeByType = function (inputType) {
  45795. for (var cam in this.attached) {
  45796. var input = this.attached[cam];
  45797. if (input.getClassName() === inputType) {
  45798. input.detachControl(this.attachedElement);
  45799. input.camera = null;
  45800. delete this.attached[cam];
  45801. this.rebuildInputCheck();
  45802. }
  45803. }
  45804. };
  45805. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45806. var current = this.checkInputs;
  45807. return function () {
  45808. current();
  45809. fn();
  45810. };
  45811. };
  45812. CameraInputsManager.prototype.attachInput = function (input) {
  45813. if (this.attachedElement) {
  45814. input.attachControl(this.attachedElement, this.noPreventDefault);
  45815. }
  45816. };
  45817. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45818. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45819. if (this.attachedElement) {
  45820. return;
  45821. }
  45822. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45823. this.attachedElement = element;
  45824. this.noPreventDefault = noPreventDefault;
  45825. for (var cam in this.attached) {
  45826. this.attached[cam].attachControl(element, noPreventDefault);
  45827. }
  45828. };
  45829. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45830. if (disconnect === void 0) { disconnect = false; }
  45831. if (this.attachedElement !== element) {
  45832. return;
  45833. }
  45834. for (var cam in this.attached) {
  45835. this.attached[cam].detachControl(element);
  45836. if (disconnect) {
  45837. this.attached[cam].camera = null;
  45838. }
  45839. }
  45840. this.attachedElement = null;
  45841. };
  45842. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45843. this.checkInputs = function () { };
  45844. for (var cam in this.attached) {
  45845. var input = this.attached[cam];
  45846. if (input.checkInputs) {
  45847. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45848. }
  45849. }
  45850. };
  45851. /**
  45852. * Remove all attached input methods from a camera
  45853. */
  45854. CameraInputsManager.prototype.clear = function () {
  45855. if (this.attachedElement) {
  45856. this.detachElement(this.attachedElement, true);
  45857. }
  45858. this.attached = {};
  45859. this.attachedElement = null;
  45860. this.checkInputs = function () { };
  45861. };
  45862. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45863. var inputs = {};
  45864. for (var cam in this.attached) {
  45865. var input = this.attached[cam];
  45866. var res = BABYLON.SerializationHelper.Serialize(input);
  45867. inputs[input.getClassName()] = res;
  45868. }
  45869. serializedCamera.inputsmgr = inputs;
  45870. };
  45871. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45872. var parsedInputs = parsedCamera.inputsmgr;
  45873. if (parsedInputs) {
  45874. this.clear();
  45875. for (var n in parsedInputs) {
  45876. var construct = BABYLON.CameraInputTypes[n];
  45877. if (construct) {
  45878. var parsedinput = parsedInputs[n];
  45879. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45880. this.add(input);
  45881. }
  45882. }
  45883. }
  45884. else {
  45885. //2016-03-08 this part is for managing backward compatibility
  45886. for (var n in this.attached) {
  45887. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45888. if (construct) {
  45889. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45890. this.remove(this.attached[n]);
  45891. this.add(input);
  45892. }
  45893. }
  45894. }
  45895. };
  45896. return CameraInputsManager;
  45897. }());
  45898. BABYLON.CameraInputsManager = CameraInputsManager;
  45899. })(BABYLON || (BABYLON = {}));
  45900. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45901. var BABYLON;
  45902. (function (BABYLON) {
  45903. var TargetCamera = /** @class */ (function (_super) {
  45904. __extends(TargetCamera, _super);
  45905. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45906. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45907. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45908. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45909. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45910. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45911. _this.speed = 2.0;
  45912. _this.noRotationConstraint = false;
  45913. _this.lockedTarget = null;
  45914. /** @hidden */
  45915. _this._currentTarget = BABYLON.Vector3.Zero();
  45916. /** @hidden */
  45917. _this._viewMatrix = BABYLON.Matrix.Zero();
  45918. /** @hidden */
  45919. _this._camMatrix = BABYLON.Matrix.Zero();
  45920. /** @hidden */
  45921. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45922. /** @hidden */
  45923. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45924. /** @hidden */
  45925. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45926. /** @hidden */
  45927. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45928. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45929. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45930. _this._defaultUp = BABYLON.Vector3.Up();
  45931. _this._cachedRotationZ = 0;
  45932. return _this;
  45933. }
  45934. TargetCamera.prototype.getFrontPosition = function (distance) {
  45935. this.getWorldMatrix();
  45936. var direction = this.getTarget().subtract(this.position);
  45937. direction.normalize();
  45938. direction.scaleInPlace(distance);
  45939. return this.globalPosition.add(direction);
  45940. };
  45941. /** @hidden */
  45942. TargetCamera.prototype._getLockedTargetPosition = function () {
  45943. if (!this.lockedTarget) {
  45944. return null;
  45945. }
  45946. if (this.lockedTarget.absolutePosition) {
  45947. this.lockedTarget.computeWorldMatrix();
  45948. }
  45949. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45950. };
  45951. TargetCamera.prototype.storeState = function () {
  45952. this._storedPosition = this.position.clone();
  45953. this._storedRotation = this.rotation.clone();
  45954. if (this.rotationQuaternion) {
  45955. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45956. }
  45957. return _super.prototype.storeState.call(this);
  45958. };
  45959. /**
  45960. * Restored camera state. You must call storeState() first
  45961. * @returns whether it was successful or not
  45962. * @hidden
  45963. */
  45964. TargetCamera.prototype._restoreStateValues = function () {
  45965. if (!_super.prototype._restoreStateValues.call(this)) {
  45966. return false;
  45967. }
  45968. this.position = this._storedPosition.clone();
  45969. this.rotation = this._storedRotation.clone();
  45970. if (this.rotationQuaternion) {
  45971. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45972. }
  45973. this.cameraDirection.copyFromFloats(0, 0, 0);
  45974. this.cameraRotation.copyFromFloats(0, 0);
  45975. return true;
  45976. };
  45977. // Cache
  45978. /** @hidden */
  45979. TargetCamera.prototype._initCache = function () {
  45980. _super.prototype._initCache.call(this);
  45981. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45982. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45983. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45984. };
  45985. /** @hidden */
  45986. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45987. if (!ignoreParentClass) {
  45988. _super.prototype._updateCache.call(this);
  45989. }
  45990. var lockedTargetPosition = this._getLockedTargetPosition();
  45991. if (!lockedTargetPosition) {
  45992. this._cache.lockedTarget = null;
  45993. }
  45994. else {
  45995. if (!this._cache.lockedTarget) {
  45996. this._cache.lockedTarget = lockedTargetPosition.clone();
  45997. }
  45998. else {
  45999. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46000. }
  46001. }
  46002. this._cache.rotation.copyFrom(this.rotation);
  46003. if (this.rotationQuaternion)
  46004. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46005. };
  46006. // Synchronized
  46007. /** @hidden */
  46008. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46009. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46010. return false;
  46011. }
  46012. var lockedTargetPosition = this._getLockedTargetPosition();
  46013. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46014. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46015. };
  46016. // Methods
  46017. /** @hidden */
  46018. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46019. var engine = this.getEngine();
  46020. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46021. };
  46022. // Target
  46023. /** @hidden */
  46024. TargetCamera.prototype.setTarget = function (target) {
  46025. this.upVector.normalize();
  46026. if (this.position.z === target.z) {
  46027. this.position.z += BABYLON.Epsilon;
  46028. }
  46029. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46030. this._camMatrix.invert();
  46031. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46032. var vDir = target.subtract(this.position);
  46033. if (vDir.x >= 0.0) {
  46034. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46035. }
  46036. else {
  46037. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46038. }
  46039. this.rotation.z = 0;
  46040. if (isNaN(this.rotation.x)) {
  46041. this.rotation.x = 0;
  46042. }
  46043. if (isNaN(this.rotation.y)) {
  46044. this.rotation.y = 0;
  46045. }
  46046. if (isNaN(this.rotation.z)) {
  46047. this.rotation.z = 0;
  46048. }
  46049. if (this.rotationQuaternion) {
  46050. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46051. }
  46052. };
  46053. /**
  46054. * Return the current target position of the camera. This value is expressed in local space.
  46055. */
  46056. TargetCamera.prototype.getTarget = function () {
  46057. return this._currentTarget;
  46058. };
  46059. /** @hidden */
  46060. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46061. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46062. };
  46063. /** @hidden */
  46064. TargetCamera.prototype._updatePosition = function () {
  46065. if (this.parent) {
  46066. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46067. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46068. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46069. return;
  46070. }
  46071. this.position.addInPlace(this.cameraDirection);
  46072. };
  46073. /** @hidden */
  46074. TargetCamera.prototype._checkInputs = function () {
  46075. var needToMove = this._decideIfNeedsToMove();
  46076. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46077. // Move
  46078. if (needToMove) {
  46079. this._updatePosition();
  46080. }
  46081. // Rotate
  46082. if (needToRotate) {
  46083. this.rotation.x += this.cameraRotation.x;
  46084. this.rotation.y += this.cameraRotation.y;
  46085. //rotate, if quaternion is set and rotation was used
  46086. if (this.rotationQuaternion) {
  46087. var len = this.rotation.lengthSquared();
  46088. if (len) {
  46089. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46090. }
  46091. }
  46092. if (!this.noRotationConstraint) {
  46093. var limit = (Math.PI / 2) * 0.95;
  46094. if (this.rotation.x > limit)
  46095. this.rotation.x = limit;
  46096. if (this.rotation.x < -limit)
  46097. this.rotation.x = -limit;
  46098. }
  46099. }
  46100. // Inertia
  46101. if (needToMove) {
  46102. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46103. this.cameraDirection.x = 0;
  46104. }
  46105. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46106. this.cameraDirection.y = 0;
  46107. }
  46108. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46109. this.cameraDirection.z = 0;
  46110. }
  46111. this.cameraDirection.scaleInPlace(this.inertia);
  46112. }
  46113. if (needToRotate) {
  46114. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46115. this.cameraRotation.x = 0;
  46116. }
  46117. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46118. this.cameraRotation.y = 0;
  46119. }
  46120. this.cameraRotation.scaleInPlace(this.inertia);
  46121. }
  46122. _super.prototype._checkInputs.call(this);
  46123. };
  46124. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46125. if (this.rotationQuaternion) {
  46126. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46127. }
  46128. else {
  46129. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46130. }
  46131. };
  46132. /**
  46133. * 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)
  46134. * @returns the current camera
  46135. */
  46136. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46137. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46138. return this;
  46139. };
  46140. /** @hidden */
  46141. TargetCamera.prototype._getViewMatrix = function () {
  46142. if (this.lockedTarget) {
  46143. this.setTarget(this._getLockedTargetPosition());
  46144. }
  46145. // Compute
  46146. this._updateCameraRotationMatrix();
  46147. // Apply the changed rotation to the upVector.
  46148. if (this._cachedRotationZ != this.rotation.z) {
  46149. this._rotateUpVectorWithCameraRotationMatrix();
  46150. this._cachedRotationZ = this.rotation.z;
  46151. }
  46152. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46153. // Computing target and final matrix
  46154. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46155. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46156. return this._viewMatrix;
  46157. };
  46158. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46159. if (this.parent) {
  46160. var parentWorldMatrix = this.parent.getWorldMatrix();
  46161. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46162. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46163. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46164. this._markSyncedWithParent();
  46165. }
  46166. else {
  46167. this._globalPosition.copyFrom(position);
  46168. this._globalCurrentTarget.copyFrom(target);
  46169. this._globalCurrentUpVector.copyFrom(up);
  46170. }
  46171. if (this.getScene().useRightHandedSystem) {
  46172. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46173. }
  46174. else {
  46175. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46176. }
  46177. };
  46178. /**
  46179. * @override
  46180. * Override Camera.createRigCamera
  46181. */
  46182. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46183. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46184. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46185. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46186. if (!this.rotationQuaternion) {
  46187. this.rotationQuaternion = new BABYLON.Quaternion();
  46188. }
  46189. rigCamera._cameraRigParams = {};
  46190. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46191. }
  46192. return rigCamera;
  46193. }
  46194. return null;
  46195. };
  46196. /**
  46197. * @hidden
  46198. * @override
  46199. * Override Camera._updateRigCameras
  46200. */
  46201. TargetCamera.prototype._updateRigCameras = function () {
  46202. var camLeft = this._rigCameras[0];
  46203. var camRight = this._rigCameras[1];
  46204. switch (this.cameraRigMode) {
  46205. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46206. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46207. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46208. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46209. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46210. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46211. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46212. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46213. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46214. camLeft.setTarget(this.getTarget());
  46215. camRight.setTarget(this.getTarget());
  46216. break;
  46217. case BABYLON.Camera.RIG_MODE_VR:
  46218. if (camLeft.rotationQuaternion) {
  46219. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46220. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46221. }
  46222. else {
  46223. camLeft.rotation.copyFrom(this.rotation);
  46224. camRight.rotation.copyFrom(this.rotation);
  46225. }
  46226. camLeft.position.copyFrom(this.position);
  46227. camRight.position.copyFrom(this.position);
  46228. break;
  46229. }
  46230. _super.prototype._updateRigCameras.call(this);
  46231. };
  46232. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46233. if (!this._rigCamTransformMatrix) {
  46234. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46235. }
  46236. var target = this.getTarget();
  46237. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46238. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46239. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46240. };
  46241. TargetCamera.prototype.getClassName = function () {
  46242. return "TargetCamera";
  46243. };
  46244. __decorate([
  46245. BABYLON.serializeAsVector3()
  46246. ], TargetCamera.prototype, "rotation", void 0);
  46247. __decorate([
  46248. BABYLON.serialize()
  46249. ], TargetCamera.prototype, "speed", void 0);
  46250. __decorate([
  46251. BABYLON.serializeAsMeshReference("lockedTargetId")
  46252. ], TargetCamera.prototype, "lockedTarget", void 0);
  46253. return TargetCamera;
  46254. }(BABYLON.Camera));
  46255. BABYLON.TargetCamera = TargetCamera;
  46256. })(BABYLON || (BABYLON = {}));
  46257. //# sourceMappingURL=babylon.targetCamera.js.map
  46258. var BABYLON;
  46259. (function (BABYLON) {
  46260. var FreeCameraMouseInput = /** @class */ (function () {
  46261. function FreeCameraMouseInput(touchEnabled) {
  46262. if (touchEnabled === void 0) { touchEnabled = true; }
  46263. this.touchEnabled = touchEnabled;
  46264. this.buttons = [0, 1, 2];
  46265. this.angularSensibility = 2000.0;
  46266. this.previousPosition = null;
  46267. }
  46268. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46269. var _this = this;
  46270. var engine = this.camera.getEngine();
  46271. if (!this._pointerInput) {
  46272. this._pointerInput = function (p, s) {
  46273. var evt = p.event;
  46274. if (engine.isInVRExclusivePointerMode) {
  46275. return;
  46276. }
  46277. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46278. return;
  46279. }
  46280. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46281. return;
  46282. }
  46283. var srcElement = (evt.srcElement || evt.target);
  46284. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46285. try {
  46286. srcElement.setPointerCapture(evt.pointerId);
  46287. }
  46288. catch (e) {
  46289. //Nothing to do with the error. Execution will continue.
  46290. }
  46291. _this.previousPosition = {
  46292. x: evt.clientX,
  46293. y: evt.clientY
  46294. };
  46295. if (!noPreventDefault) {
  46296. evt.preventDefault();
  46297. element.focus();
  46298. }
  46299. }
  46300. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46301. try {
  46302. srcElement.releasePointerCapture(evt.pointerId);
  46303. }
  46304. catch (e) {
  46305. //Nothing to do with the error.
  46306. }
  46307. _this.previousPosition = null;
  46308. if (!noPreventDefault) {
  46309. evt.preventDefault();
  46310. }
  46311. }
  46312. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46313. if (!_this.previousPosition || engine.isPointerLock) {
  46314. return;
  46315. }
  46316. var offsetX = evt.clientX - _this.previousPosition.x;
  46317. if (_this.camera.getScene().useRightHandedSystem)
  46318. offsetX *= -1;
  46319. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46320. offsetX *= -1;
  46321. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46322. var offsetY = evt.clientY - _this.previousPosition.y;
  46323. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46324. _this.previousPosition = {
  46325. x: evt.clientX,
  46326. y: evt.clientY
  46327. };
  46328. if (!noPreventDefault) {
  46329. evt.preventDefault();
  46330. }
  46331. }
  46332. };
  46333. }
  46334. this._onMouseMove = function (evt) {
  46335. if (!engine.isPointerLock) {
  46336. return;
  46337. }
  46338. if (engine.isInVRExclusivePointerMode) {
  46339. return;
  46340. }
  46341. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46342. if (_this.camera.getScene().useRightHandedSystem)
  46343. offsetX *= -1;
  46344. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46345. offsetX *= -1;
  46346. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46347. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46348. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46349. _this.previousPosition = null;
  46350. if (!noPreventDefault) {
  46351. evt.preventDefault();
  46352. }
  46353. };
  46354. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46355. element.addEventListener("mousemove", this._onMouseMove, false);
  46356. };
  46357. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46358. if (this._observer && element) {
  46359. this.camera.getScene().onPointerObservable.remove(this._observer);
  46360. if (this._onMouseMove) {
  46361. element.removeEventListener("mousemove", this._onMouseMove);
  46362. }
  46363. this._observer = null;
  46364. this._onMouseMove = null;
  46365. this.previousPosition = null;
  46366. }
  46367. };
  46368. FreeCameraMouseInput.prototype.getClassName = function () {
  46369. return "FreeCameraMouseInput";
  46370. };
  46371. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46372. return "mouse";
  46373. };
  46374. __decorate([
  46375. BABYLON.serialize()
  46376. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46377. __decorate([
  46378. BABYLON.serialize()
  46379. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46380. return FreeCameraMouseInput;
  46381. }());
  46382. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46383. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46384. })(BABYLON || (BABYLON = {}));
  46385. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46386. var BABYLON;
  46387. (function (BABYLON) {
  46388. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46389. function FreeCameraKeyboardMoveInput() {
  46390. this._keys = new Array();
  46391. this.keysUp = [38];
  46392. this.keysDown = [40];
  46393. this.keysLeft = [37];
  46394. this.keysRight = [39];
  46395. }
  46396. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46397. var _this = this;
  46398. if (this._onCanvasBlurObserver) {
  46399. return;
  46400. }
  46401. this._scene = this.camera.getScene();
  46402. this._engine = this._scene.getEngine();
  46403. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46404. _this._keys = [];
  46405. });
  46406. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46407. var evt = info.event;
  46408. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46409. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46410. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46411. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46412. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46413. var index = _this._keys.indexOf(evt.keyCode);
  46414. if (index === -1) {
  46415. _this._keys.push(evt.keyCode);
  46416. }
  46417. if (!noPreventDefault) {
  46418. evt.preventDefault();
  46419. }
  46420. }
  46421. }
  46422. else {
  46423. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46424. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46425. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46426. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46427. var index = _this._keys.indexOf(evt.keyCode);
  46428. if (index >= 0) {
  46429. _this._keys.splice(index, 1);
  46430. }
  46431. if (!noPreventDefault) {
  46432. evt.preventDefault();
  46433. }
  46434. }
  46435. }
  46436. });
  46437. };
  46438. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46439. if (this._scene) {
  46440. if (this._onKeyboardObserver) {
  46441. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46442. }
  46443. if (this._onCanvasBlurObserver) {
  46444. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46445. }
  46446. this._onKeyboardObserver = null;
  46447. this._onCanvasBlurObserver = null;
  46448. }
  46449. this._keys = [];
  46450. };
  46451. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46452. if (this._onKeyboardObserver) {
  46453. var camera = this.camera;
  46454. // Keyboard
  46455. for (var index = 0; index < this._keys.length; index++) {
  46456. var keyCode = this._keys[index];
  46457. var speed = camera._computeLocalCameraSpeed();
  46458. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46459. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46460. }
  46461. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46462. camera._localDirection.copyFromFloats(0, 0, speed);
  46463. }
  46464. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46465. camera._localDirection.copyFromFloats(speed, 0, 0);
  46466. }
  46467. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46468. camera._localDirection.copyFromFloats(0, 0, -speed);
  46469. }
  46470. if (camera.getScene().useRightHandedSystem) {
  46471. camera._localDirection.z *= -1;
  46472. }
  46473. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46474. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46475. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46476. }
  46477. }
  46478. };
  46479. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46480. return "FreeCameraKeyboardMoveInput";
  46481. };
  46482. /** @hidden */
  46483. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46484. this._keys = [];
  46485. };
  46486. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46487. return "keyboard";
  46488. };
  46489. __decorate([
  46490. BABYLON.serialize()
  46491. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46492. __decorate([
  46493. BABYLON.serialize()
  46494. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46495. __decorate([
  46496. BABYLON.serialize()
  46497. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46498. __decorate([
  46499. BABYLON.serialize()
  46500. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46501. return FreeCameraKeyboardMoveInput;
  46502. }());
  46503. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46504. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46505. })(BABYLON || (BABYLON = {}));
  46506. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46507. var BABYLON;
  46508. (function (BABYLON) {
  46509. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46510. __extends(FreeCameraInputsManager, _super);
  46511. function FreeCameraInputsManager(camera) {
  46512. return _super.call(this, camera) || this;
  46513. }
  46514. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46515. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46516. return this;
  46517. };
  46518. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46519. if (touchEnabled === void 0) { touchEnabled = true; }
  46520. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46521. return this;
  46522. };
  46523. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46524. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46525. return this;
  46526. };
  46527. FreeCameraInputsManager.prototype.addTouch = function () {
  46528. this.add(new BABYLON.FreeCameraTouchInput());
  46529. return this;
  46530. };
  46531. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46532. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46533. return this;
  46534. };
  46535. return FreeCameraInputsManager;
  46536. }(BABYLON.CameraInputsManager));
  46537. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46538. })(BABYLON || (BABYLON = {}));
  46539. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46540. var BABYLON;
  46541. (function (BABYLON) {
  46542. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46543. // Forcing to use the Universal camera
  46544. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46545. });
  46546. var FreeCamera = /** @class */ (function (_super) {
  46547. __extends(FreeCamera, _super);
  46548. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46549. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46550. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46551. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46552. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46553. _this.checkCollisions = false;
  46554. _this.applyGravity = false;
  46555. _this._needMoveForGravity = false;
  46556. _this._oldPosition = BABYLON.Vector3.Zero();
  46557. _this._diffPosition = BABYLON.Vector3.Zero();
  46558. _this._newPosition = BABYLON.Vector3.Zero();
  46559. // Collisions
  46560. _this._collisionMask = -1;
  46561. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46562. if (collidedMesh === void 0) { collidedMesh = null; }
  46563. //TODO move this to the collision coordinator!
  46564. if (_this.getScene().workerCollisions)
  46565. newPosition.multiplyInPlace(_this._collider._radius);
  46566. var updatePosition = function (newPos) {
  46567. _this._newPosition.copyFrom(newPos);
  46568. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46569. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46570. _this.position.addInPlace(_this._diffPosition);
  46571. if (_this.onCollide && collidedMesh) {
  46572. _this.onCollide(collidedMesh);
  46573. }
  46574. }
  46575. };
  46576. updatePosition(newPosition);
  46577. };
  46578. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46579. _this.inputs.addKeyboard().addMouse();
  46580. return _this;
  46581. }
  46582. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46583. //-- begin properties for backward compatibility for inputs
  46584. /**
  46585. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46586. * Higher values reduce sensitivity.
  46587. */
  46588. get: function () {
  46589. var mouse = this.inputs.attached["mouse"];
  46590. if (mouse)
  46591. return mouse.angularSensibility;
  46592. return 0;
  46593. },
  46594. /**
  46595. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46596. * Higher values reduce sensitivity.
  46597. */
  46598. set: function (value) {
  46599. var mouse = this.inputs.attached["mouse"];
  46600. if (mouse)
  46601. mouse.angularSensibility = value;
  46602. },
  46603. enumerable: true,
  46604. configurable: true
  46605. });
  46606. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46607. get: function () {
  46608. var keyboard = this.inputs.attached["keyboard"];
  46609. if (keyboard)
  46610. return keyboard.keysUp;
  46611. return [];
  46612. },
  46613. set: function (value) {
  46614. var keyboard = this.inputs.attached["keyboard"];
  46615. if (keyboard)
  46616. keyboard.keysUp = value;
  46617. },
  46618. enumerable: true,
  46619. configurable: true
  46620. });
  46621. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46622. get: function () {
  46623. var keyboard = this.inputs.attached["keyboard"];
  46624. if (keyboard)
  46625. return keyboard.keysDown;
  46626. return [];
  46627. },
  46628. set: function (value) {
  46629. var keyboard = this.inputs.attached["keyboard"];
  46630. if (keyboard)
  46631. keyboard.keysDown = value;
  46632. },
  46633. enumerable: true,
  46634. configurable: true
  46635. });
  46636. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46637. get: function () {
  46638. var keyboard = this.inputs.attached["keyboard"];
  46639. if (keyboard)
  46640. return keyboard.keysLeft;
  46641. return [];
  46642. },
  46643. set: function (value) {
  46644. var keyboard = this.inputs.attached["keyboard"];
  46645. if (keyboard)
  46646. keyboard.keysLeft = value;
  46647. },
  46648. enumerable: true,
  46649. configurable: true
  46650. });
  46651. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46652. get: function () {
  46653. var keyboard = this.inputs.attached["keyboard"];
  46654. if (keyboard)
  46655. return keyboard.keysRight;
  46656. return [];
  46657. },
  46658. set: function (value) {
  46659. var keyboard = this.inputs.attached["keyboard"];
  46660. if (keyboard)
  46661. keyboard.keysRight = value;
  46662. },
  46663. enumerable: true,
  46664. configurable: true
  46665. });
  46666. // Controls
  46667. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46668. this.inputs.attachElement(element, noPreventDefault);
  46669. };
  46670. FreeCamera.prototype.detachControl = function (element) {
  46671. this.inputs.detachElement(element);
  46672. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46673. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46674. };
  46675. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46676. get: function () {
  46677. return this._collisionMask;
  46678. },
  46679. set: function (mask) {
  46680. this._collisionMask = !isNaN(mask) ? mask : -1;
  46681. },
  46682. enumerable: true,
  46683. configurable: true
  46684. });
  46685. /** @hidden */
  46686. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46687. var globalPosition;
  46688. if (this.parent) {
  46689. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46690. }
  46691. else {
  46692. globalPosition = this.position;
  46693. }
  46694. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46695. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46696. if (!this._collider) {
  46697. this._collider = new BABYLON.Collider();
  46698. }
  46699. this._collider._radius = this.ellipsoid;
  46700. this._collider.collisionMask = this._collisionMask;
  46701. //no need for clone, as long as gravity is not on.
  46702. var actualDisplacement = displacement;
  46703. //add gravity to the direction to prevent the dual-collision checking
  46704. if (this.applyGravity) {
  46705. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46706. actualDisplacement = displacement.add(this.getScene().gravity);
  46707. }
  46708. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46709. };
  46710. /** @hidden */
  46711. FreeCamera.prototype._checkInputs = function () {
  46712. if (!this._localDirection) {
  46713. this._localDirection = BABYLON.Vector3.Zero();
  46714. this._transformedDirection = BABYLON.Vector3.Zero();
  46715. }
  46716. this.inputs.checkInputs();
  46717. _super.prototype._checkInputs.call(this);
  46718. };
  46719. /** @hidden */
  46720. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46721. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46722. };
  46723. /** @hidden */
  46724. FreeCamera.prototype._updatePosition = function () {
  46725. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46726. this._collideWithWorld(this.cameraDirection);
  46727. }
  46728. else {
  46729. _super.prototype._updatePosition.call(this);
  46730. }
  46731. };
  46732. FreeCamera.prototype.dispose = function () {
  46733. this.inputs.clear();
  46734. _super.prototype.dispose.call(this);
  46735. };
  46736. FreeCamera.prototype.getClassName = function () {
  46737. return "FreeCamera";
  46738. };
  46739. __decorate([
  46740. BABYLON.serializeAsVector3()
  46741. ], FreeCamera.prototype, "ellipsoid", void 0);
  46742. __decorate([
  46743. BABYLON.serializeAsVector3()
  46744. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46745. __decorate([
  46746. BABYLON.serialize()
  46747. ], FreeCamera.prototype, "checkCollisions", void 0);
  46748. __decorate([
  46749. BABYLON.serialize()
  46750. ], FreeCamera.prototype, "applyGravity", void 0);
  46751. return FreeCamera;
  46752. }(BABYLON.TargetCamera));
  46753. BABYLON.FreeCamera = FreeCamera;
  46754. })(BABYLON || (BABYLON = {}));
  46755. //# sourceMappingURL=babylon.freeCamera.js.map
  46756. var BABYLON;
  46757. (function (BABYLON) {
  46758. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46759. function ArcRotateCameraKeyboardMoveInput() {
  46760. this._keys = new Array();
  46761. this.keysUp = [38];
  46762. this.keysDown = [40];
  46763. this.keysLeft = [37];
  46764. this.keysRight = [39];
  46765. this.keysReset = [220];
  46766. this.panningSensibility = 50.0;
  46767. this.zoomingSensibility = 25.0;
  46768. this.useAltToZoom = true;
  46769. }
  46770. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46771. var _this = this;
  46772. if (this._onCanvasBlurObserver) {
  46773. return;
  46774. }
  46775. this._scene = this.camera.getScene();
  46776. this._engine = this._scene.getEngine();
  46777. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46778. _this._keys = [];
  46779. });
  46780. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46781. var evt = info.event;
  46782. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46783. _this._ctrlPressed = evt.ctrlKey;
  46784. _this._altPressed = evt.altKey;
  46785. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46786. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46787. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46788. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46789. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46790. var index = _this._keys.indexOf(evt.keyCode);
  46791. if (index === -1) {
  46792. _this._keys.push(evt.keyCode);
  46793. }
  46794. if (evt.preventDefault) {
  46795. if (!noPreventDefault) {
  46796. evt.preventDefault();
  46797. }
  46798. }
  46799. }
  46800. }
  46801. else {
  46802. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46803. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46804. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46805. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46806. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46807. var index = _this._keys.indexOf(evt.keyCode);
  46808. if (index >= 0) {
  46809. _this._keys.splice(index, 1);
  46810. }
  46811. if (evt.preventDefault) {
  46812. if (!noPreventDefault) {
  46813. evt.preventDefault();
  46814. }
  46815. }
  46816. }
  46817. }
  46818. });
  46819. };
  46820. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46821. if (this._scene) {
  46822. if (this._onKeyboardObserver) {
  46823. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46824. }
  46825. if (this._onCanvasBlurObserver) {
  46826. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46827. }
  46828. this._onKeyboardObserver = null;
  46829. this._onCanvasBlurObserver = null;
  46830. }
  46831. this._keys = [];
  46832. };
  46833. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46834. if (this._onKeyboardObserver) {
  46835. var camera = this.camera;
  46836. for (var index = 0; index < this._keys.length; index++) {
  46837. var keyCode = this._keys[index];
  46838. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46839. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46840. camera.inertialPanningX -= 1 / this.panningSensibility;
  46841. }
  46842. else {
  46843. camera.inertialAlphaOffset -= 0.01;
  46844. }
  46845. }
  46846. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46847. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46848. camera.inertialPanningY += 1 / this.panningSensibility;
  46849. }
  46850. else if (this._altPressed && this.useAltToZoom) {
  46851. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46852. }
  46853. else {
  46854. camera.inertialBetaOffset -= 0.01;
  46855. }
  46856. }
  46857. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46858. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46859. camera.inertialPanningX += 1 / this.panningSensibility;
  46860. }
  46861. else {
  46862. camera.inertialAlphaOffset += 0.01;
  46863. }
  46864. }
  46865. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46866. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46867. camera.inertialPanningY -= 1 / this.panningSensibility;
  46868. }
  46869. else if (this._altPressed && this.useAltToZoom) {
  46870. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46871. }
  46872. else {
  46873. camera.inertialBetaOffset += 0.01;
  46874. }
  46875. }
  46876. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46877. camera.restoreState();
  46878. }
  46879. }
  46880. }
  46881. };
  46882. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46883. return "ArcRotateCameraKeyboardMoveInput";
  46884. };
  46885. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46886. return "keyboard";
  46887. };
  46888. __decorate([
  46889. BABYLON.serialize()
  46890. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46891. __decorate([
  46892. BABYLON.serialize()
  46893. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46894. __decorate([
  46895. BABYLON.serialize()
  46896. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46897. __decorate([
  46898. BABYLON.serialize()
  46899. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46900. __decorate([
  46901. BABYLON.serialize()
  46902. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46903. __decorate([
  46904. BABYLON.serialize()
  46905. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46906. __decorate([
  46907. BABYLON.serialize()
  46908. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46909. __decorate([
  46910. BABYLON.serialize()
  46911. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46912. return ArcRotateCameraKeyboardMoveInput;
  46913. }());
  46914. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46915. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46916. })(BABYLON || (BABYLON = {}));
  46917. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46918. var BABYLON;
  46919. (function (BABYLON) {
  46920. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46921. function ArcRotateCameraMouseWheelInput() {
  46922. this.wheelPrecision = 3.0;
  46923. /**
  46924. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46925. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46926. */
  46927. this.wheelDeltaPercentage = 0;
  46928. }
  46929. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46930. var _this = this;
  46931. this._wheel = function (p, s) {
  46932. //sanity check - this should be a PointerWheel event.
  46933. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46934. return;
  46935. var event = p.event;
  46936. var delta = 0;
  46937. if (event.wheelDelta) {
  46938. if (_this.wheelDeltaPercentage) {
  46939. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46940. if (event.wheelDelta > 0) {
  46941. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46942. }
  46943. else {
  46944. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46945. }
  46946. }
  46947. else {
  46948. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46949. }
  46950. }
  46951. else if (event.detail) {
  46952. delta = -event.detail / _this.wheelPrecision;
  46953. }
  46954. if (delta)
  46955. _this.camera.inertialRadiusOffset += delta;
  46956. if (event.preventDefault) {
  46957. if (!noPreventDefault) {
  46958. event.preventDefault();
  46959. }
  46960. }
  46961. };
  46962. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46963. };
  46964. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46965. if (this._observer && element) {
  46966. this.camera.getScene().onPointerObservable.remove(this._observer);
  46967. this._observer = null;
  46968. this._wheel = null;
  46969. }
  46970. };
  46971. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46972. return "ArcRotateCameraMouseWheelInput";
  46973. };
  46974. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46975. return "mousewheel";
  46976. };
  46977. __decorate([
  46978. BABYLON.serialize()
  46979. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46980. __decorate([
  46981. BABYLON.serialize()
  46982. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46983. return ArcRotateCameraMouseWheelInput;
  46984. }());
  46985. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46986. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46987. })(BABYLON || (BABYLON = {}));
  46988. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46989. var BABYLON;
  46990. (function (BABYLON) {
  46991. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46992. function ArcRotateCameraPointersInput() {
  46993. this.buttons = [0, 1, 2];
  46994. this.angularSensibilityX = 1000.0;
  46995. this.angularSensibilityY = 1000.0;
  46996. this.pinchPrecision = 12.0;
  46997. /**
  46998. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46999. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47000. */
  47001. this.pinchDeltaPercentage = 0;
  47002. this.panningSensibility = 1000.0;
  47003. this.multiTouchPanning = true;
  47004. this.multiTouchPanAndZoom = true;
  47005. this._isPanClick = false;
  47006. this.pinchInwards = true;
  47007. }
  47008. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47009. var _this = this;
  47010. var engine = this.camera.getEngine();
  47011. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47012. var pointA = null;
  47013. var pointB = null;
  47014. var previousPinchSquaredDistance = 0;
  47015. var initialDistance = 0;
  47016. var twoFingerActivityCount = 0;
  47017. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47018. this._pointerInput = function (p, s) {
  47019. var evt = p.event;
  47020. var isTouch = p.event.pointerType === "touch";
  47021. if (engine.isInVRExclusivePointerMode) {
  47022. return;
  47023. }
  47024. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47025. return;
  47026. }
  47027. var srcElement = (evt.srcElement || evt.target);
  47028. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47029. try {
  47030. srcElement.setPointerCapture(evt.pointerId);
  47031. }
  47032. catch (e) {
  47033. //Nothing to do with the error. Execution will continue.
  47034. }
  47035. // Manage panning with pan button click
  47036. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47037. // manage pointers
  47038. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47039. if (pointA === null) {
  47040. pointA = cacheSoloPointer;
  47041. }
  47042. else if (pointB === null) {
  47043. pointB = cacheSoloPointer;
  47044. }
  47045. if (!noPreventDefault) {
  47046. evt.preventDefault();
  47047. element.focus();
  47048. }
  47049. }
  47050. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47051. _this.camera.restoreState();
  47052. }
  47053. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47054. try {
  47055. srcElement.releasePointerCapture(evt.pointerId);
  47056. }
  47057. catch (e) {
  47058. //Nothing to do with the error.
  47059. }
  47060. cacheSoloPointer = null;
  47061. previousPinchSquaredDistance = 0;
  47062. previousMultiTouchPanPosition.isPaning = false;
  47063. previousMultiTouchPanPosition.isPinching = false;
  47064. twoFingerActivityCount = 0;
  47065. initialDistance = 0;
  47066. if (!isTouch) {
  47067. pointB = null; // Mouse and pen are mono pointer
  47068. }
  47069. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47070. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47071. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47072. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47073. if (engine._badOS) {
  47074. pointA = pointB = null;
  47075. }
  47076. else {
  47077. //only remove the impacted pointer in case of multitouch allowing on most
  47078. //platforms switching from rotate to zoom and pan seamlessly.
  47079. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47080. pointA = pointB;
  47081. pointB = null;
  47082. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47083. }
  47084. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47085. pointB = null;
  47086. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47087. }
  47088. else {
  47089. pointA = pointB = null;
  47090. }
  47091. }
  47092. if (!noPreventDefault) {
  47093. evt.preventDefault();
  47094. }
  47095. }
  47096. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47097. if (!noPreventDefault) {
  47098. evt.preventDefault();
  47099. }
  47100. // One button down
  47101. if (pointA && pointB === null && cacheSoloPointer) {
  47102. if (_this.panningSensibility !== 0 &&
  47103. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47104. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47105. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47106. }
  47107. else {
  47108. var offsetX = evt.clientX - cacheSoloPointer.x;
  47109. var offsetY = evt.clientY - cacheSoloPointer.y;
  47110. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47111. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47112. }
  47113. cacheSoloPointer.x = evt.clientX;
  47114. cacheSoloPointer.y = evt.clientY;
  47115. }
  47116. // Two buttons down: pinch/pan
  47117. else if (pointA && pointB) {
  47118. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47119. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47120. ed.x = evt.clientX;
  47121. ed.y = evt.clientY;
  47122. var direction = _this.pinchInwards ? 1 : -1;
  47123. var distX = pointA.x - pointB.x;
  47124. var distY = pointA.y - pointB.y;
  47125. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47126. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47127. if (previousPinchSquaredDistance === 0) {
  47128. initialDistance = pinchDistance;
  47129. previousPinchSquaredDistance = pinchSquaredDistance;
  47130. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47131. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47132. return;
  47133. }
  47134. if (_this.multiTouchPanAndZoom) {
  47135. if (_this.pinchDeltaPercentage) {
  47136. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47137. }
  47138. else {
  47139. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47140. (_this.pinchPrecision *
  47141. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47142. direction);
  47143. }
  47144. if (_this.panningSensibility !== 0) {
  47145. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47146. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47147. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47148. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47149. previousMultiTouchPanPosition.x = pointersCenterX;
  47150. previousMultiTouchPanPosition.y = pointersCenterY;
  47151. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47152. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47153. }
  47154. }
  47155. else {
  47156. twoFingerActivityCount++;
  47157. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47158. if (_this.pinchDeltaPercentage) {
  47159. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47160. }
  47161. else {
  47162. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47163. (_this.pinchPrecision *
  47164. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47165. direction);
  47166. }
  47167. previousMultiTouchPanPosition.isPaning = false;
  47168. previousMultiTouchPanPosition.isPinching = true;
  47169. }
  47170. else {
  47171. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47172. if (!previousMultiTouchPanPosition.isPaning) {
  47173. previousMultiTouchPanPosition.isPaning = true;
  47174. previousMultiTouchPanPosition.isPinching = false;
  47175. previousMultiTouchPanPosition.x = ed.x;
  47176. previousMultiTouchPanPosition.y = ed.y;
  47177. return;
  47178. }
  47179. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47180. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47181. }
  47182. }
  47183. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47184. previousMultiTouchPanPosition.x = ed.x;
  47185. previousMultiTouchPanPosition.y = ed.y;
  47186. }
  47187. }
  47188. previousPinchSquaredDistance = pinchSquaredDistance;
  47189. }
  47190. }
  47191. };
  47192. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47193. this._onContextMenu = function (evt) {
  47194. evt.preventDefault();
  47195. };
  47196. if (!this.camera._useCtrlForPanning) {
  47197. element.addEventListener("contextmenu", this._onContextMenu, false);
  47198. }
  47199. this._onLostFocus = function () {
  47200. //this._keys = [];
  47201. pointA = pointB = null;
  47202. previousPinchSquaredDistance = 0;
  47203. previousMultiTouchPanPosition.isPaning = false;
  47204. previousMultiTouchPanPosition.isPinching = false;
  47205. twoFingerActivityCount = 0;
  47206. cacheSoloPointer = null;
  47207. initialDistance = 0;
  47208. };
  47209. this._onMouseMove = function (evt) {
  47210. if (!engine.isPointerLock) {
  47211. return;
  47212. }
  47213. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47214. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47215. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47216. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47217. if (!noPreventDefault) {
  47218. evt.preventDefault();
  47219. }
  47220. };
  47221. this._onGestureStart = function (e) {
  47222. if (window.MSGesture === undefined) {
  47223. return;
  47224. }
  47225. if (!_this._MSGestureHandler) {
  47226. _this._MSGestureHandler = new MSGesture();
  47227. _this._MSGestureHandler.target = element;
  47228. }
  47229. _this._MSGestureHandler.addPointer(e.pointerId);
  47230. };
  47231. this._onGesture = function (e) {
  47232. _this.camera.radius *= e.scale;
  47233. if (e.preventDefault) {
  47234. if (!noPreventDefault) {
  47235. e.stopPropagation();
  47236. e.preventDefault();
  47237. }
  47238. }
  47239. };
  47240. element.addEventListener("mousemove", this._onMouseMove, false);
  47241. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47242. element.addEventListener("MSGestureChange", this._onGesture, false);
  47243. BABYLON.Tools.RegisterTopRootEvents([
  47244. { name: "blur", handler: this._onLostFocus }
  47245. ]);
  47246. };
  47247. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47248. if (this._onLostFocus) {
  47249. BABYLON.Tools.UnregisterTopRootEvents([
  47250. { name: "blur", handler: this._onLostFocus }
  47251. ]);
  47252. }
  47253. if (element && this._observer) {
  47254. this.camera.getScene().onPointerObservable.remove(this._observer);
  47255. this._observer = null;
  47256. if (this._onContextMenu) {
  47257. element.removeEventListener("contextmenu", this._onContextMenu);
  47258. }
  47259. if (this._onMouseMove) {
  47260. element.removeEventListener("mousemove", this._onMouseMove);
  47261. }
  47262. if (this._onGestureStart) {
  47263. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47264. }
  47265. if (this._onGesture) {
  47266. element.removeEventListener("MSGestureChange", this._onGesture);
  47267. }
  47268. this._isPanClick = false;
  47269. this.pinchInwards = true;
  47270. this._onMouseMove = null;
  47271. this._onGestureStart = null;
  47272. this._onGesture = null;
  47273. this._MSGestureHandler = null;
  47274. this._onLostFocus = null;
  47275. this._onContextMenu = null;
  47276. }
  47277. };
  47278. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47279. return "ArcRotateCameraPointersInput";
  47280. };
  47281. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47282. return "pointers";
  47283. };
  47284. __decorate([
  47285. BABYLON.serialize()
  47286. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47287. __decorate([
  47288. BABYLON.serialize()
  47289. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47290. __decorate([
  47291. BABYLON.serialize()
  47292. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47293. __decorate([
  47294. BABYLON.serialize()
  47295. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47296. __decorate([
  47297. BABYLON.serialize()
  47298. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47299. __decorate([
  47300. BABYLON.serialize()
  47301. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47302. __decorate([
  47303. BABYLON.serialize()
  47304. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47305. __decorate([
  47306. BABYLON.serialize()
  47307. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47308. return ArcRotateCameraPointersInput;
  47309. }());
  47310. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47311. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47312. })(BABYLON || (BABYLON = {}));
  47313. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47314. var BABYLON;
  47315. (function (BABYLON) {
  47316. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47317. __extends(ArcRotateCameraInputsManager, _super);
  47318. function ArcRotateCameraInputsManager(camera) {
  47319. return _super.call(this, camera) || this;
  47320. }
  47321. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47322. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47323. return this;
  47324. };
  47325. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47326. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47327. return this;
  47328. };
  47329. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47330. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47331. return this;
  47332. };
  47333. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47334. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47335. return this;
  47336. };
  47337. return ArcRotateCameraInputsManager;
  47338. }(BABYLON.CameraInputsManager));
  47339. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47340. })(BABYLON || (BABYLON = {}));
  47341. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47342. var BABYLON;
  47343. (function (BABYLON) {
  47344. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47345. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47346. });
  47347. /**
  47348. * This represents an orbital type of camera.
  47349. *
  47350. * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
  47351. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
  47352. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  47353. */
  47354. var ArcRotateCamera = /** @class */ (function (_super) {
  47355. __extends(ArcRotateCamera, _super);
  47356. /**
  47357. * Instantiates a new ArcRotateCamera in a given scene
  47358. * @param name Defines the name of the camera
  47359. * @param alpha Defines the camera rotation along the logitudinal axis
  47360. * @param beta Defines the camera rotation along the latitudinal axis
  47361. * @param radius Defines the camera distance from its target
  47362. * @param target Defines the camera target
  47363. * @param scene Defines the scene the camera belongs to
  47364. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47365. */
  47366. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47367. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47368. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47369. /**
  47370. * Current inertia value on the longitudinal axis.
  47371. * The bigger this number the longer it will take for the camera to stop.
  47372. */
  47373. _this.inertialAlphaOffset = 0;
  47374. /**
  47375. * Current inertia value on the latitudinal axis.
  47376. * The bigger this number the longer it will take for the camera to stop.
  47377. */
  47378. _this.inertialBetaOffset = 0;
  47379. /**
  47380. * Current inertia value on the radius axis.
  47381. * The bigger this number the longer it will take for the camera to stop.
  47382. */
  47383. _this.inertialRadiusOffset = 0;
  47384. /**
  47385. * Minimum allowed angle on the longitudinal axis.
  47386. * This can help limiting how the Camera is able to move in the scene.
  47387. */
  47388. _this.lowerAlphaLimit = null;
  47389. /**
  47390. * Maximum allowed angle on the longitudinal axis.
  47391. * This can help limiting how the Camera is able to move in the scene.
  47392. */
  47393. _this.upperAlphaLimit = null;
  47394. /**
  47395. * Minimum allowed angle on the latitudinal axis.
  47396. * This can help limiting how the Camera is able to move in the scene.
  47397. */
  47398. _this.lowerBetaLimit = 0.01;
  47399. /**
  47400. * Maximum allowed angle on the latitudinal axis.
  47401. * This can help limiting how the Camera is able to move in the scene.
  47402. */
  47403. _this.upperBetaLimit = Math.PI;
  47404. /**
  47405. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  47406. * This can help limiting how the Camera is able to move in the scene.
  47407. */
  47408. _this.lowerRadiusLimit = null;
  47409. /**
  47410. * Maximum allowed distance of the camera to the target (The camera can not get further).
  47411. * This can help limiting how the Camera is able to move in the scene.
  47412. */
  47413. _this.upperRadiusLimit = null;
  47414. /**
  47415. * Defines the current inertia value used during panning of the camera along the X axis.
  47416. */
  47417. _this.inertialPanningX = 0;
  47418. /**
  47419. * Defines the current inertia value used during panning of the camera along the Y axis.
  47420. */
  47421. _this.inertialPanningY = 0;
  47422. /**
  47423. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  47424. * Basically if your fingers moves away from more than this distance you will be considered
  47425. * in pinch mode.
  47426. */
  47427. _this.pinchToPanMaxDistance = 20;
  47428. /**
  47429. * Defines the maximum distance the camera can pan.
  47430. * This could help keeping the cammera always in your scene.
  47431. */
  47432. _this.panningDistanceLimit = null;
  47433. /**
  47434. * Defines the target of the camera before paning.
  47435. */
  47436. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47437. /**
  47438. * Defines the value of the inertia used during panning.
  47439. * 0 would mean stop inertia and one would mean no decelleration at all.
  47440. */
  47441. _this.panningInertia = 0.9;
  47442. //-- end properties for backward compatibility for inputs
  47443. /**
  47444. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  47445. */
  47446. _this.zoomOnFactor = 1;
  47447. /**
  47448. * Defines a screen offset for the camera position.
  47449. */
  47450. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47451. /**
  47452. * Allows the camera to be completely reversed.
  47453. * If false the camera can not arrive upside down.
  47454. */
  47455. _this.allowUpsideDown = true;
  47456. /** @hidden */
  47457. _this._viewMatrix = new BABYLON.Matrix();
  47458. /**
  47459. * Defines the allowed panning axis.
  47460. */
  47461. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47462. /**
  47463. * Observable triggered when the mesh target has been changed on the camera.
  47464. */
  47465. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47466. /**
  47467. * Defines whether the camera should check collision with the objects oh the scene.
  47468. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  47469. */
  47470. _this.checkCollisions = false;
  47471. /**
  47472. * Defines the collision radius of the camera.
  47473. * This simulates a sphere around the camera.
  47474. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  47475. */
  47476. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47477. _this._previousPosition = BABYLON.Vector3.Zero();
  47478. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47479. _this._newPosition = BABYLON.Vector3.Zero();
  47480. _this._computationVector = BABYLON.Vector3.Zero();
  47481. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47482. if (collidedMesh === void 0) { collidedMesh = null; }
  47483. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47484. newPosition.multiplyInPlace(_this._collider._radius);
  47485. }
  47486. if (!collidedMesh) {
  47487. _this._previousPosition.copyFrom(_this.position);
  47488. }
  47489. else {
  47490. _this.setPosition(newPosition);
  47491. if (_this.onCollide) {
  47492. _this.onCollide(collidedMesh);
  47493. }
  47494. }
  47495. // Recompute because of constraints
  47496. var cosa = Math.cos(_this.alpha);
  47497. var sina = Math.sin(_this.alpha);
  47498. var cosb = Math.cos(_this.beta);
  47499. var sinb = Math.sin(_this.beta);
  47500. if (sinb === 0) {
  47501. sinb = 0.0001;
  47502. }
  47503. var target = _this._getTargetPosition();
  47504. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47505. target.addToRef(_this._computationVector, _this._newPosition);
  47506. _this.position.copyFrom(_this._newPosition);
  47507. var up = _this.upVector;
  47508. if (_this.allowUpsideDown && _this.beta < 0) {
  47509. up = up.clone();
  47510. up = up.negate();
  47511. }
  47512. _this._computeViewMatrix(_this.position, target, up);
  47513. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47514. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47515. _this._collisionTriggered = false;
  47516. };
  47517. _this._target = BABYLON.Vector3.Zero();
  47518. if (target) {
  47519. _this.setTarget(target);
  47520. }
  47521. _this.alpha = alpha;
  47522. _this.beta = beta;
  47523. _this.radius = radius;
  47524. _this.getViewMatrix();
  47525. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47526. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47527. return _this;
  47528. }
  47529. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47530. /**
  47531. * Defines the target point of the camera.
  47532. * The camera looks towards it form the radius distance.
  47533. */
  47534. get: function () {
  47535. return this._target;
  47536. },
  47537. set: function (value) {
  47538. this.setTarget(value);
  47539. },
  47540. enumerable: true,
  47541. configurable: true
  47542. });
  47543. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47544. //-- begin properties for backward compatibility for inputs
  47545. /**
  47546. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  47547. */
  47548. get: function () {
  47549. var pointers = this.inputs.attached["pointers"];
  47550. if (pointers)
  47551. return pointers.angularSensibilityX;
  47552. return 0;
  47553. },
  47554. set: function (value) {
  47555. var pointers = this.inputs.attached["pointers"];
  47556. if (pointers) {
  47557. pointers.angularSensibilityX = value;
  47558. }
  47559. },
  47560. enumerable: true,
  47561. configurable: true
  47562. });
  47563. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47564. /**
  47565. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  47566. */
  47567. get: function () {
  47568. var pointers = this.inputs.attached["pointers"];
  47569. if (pointers)
  47570. return pointers.angularSensibilityY;
  47571. return 0;
  47572. },
  47573. set: function (value) {
  47574. var pointers = this.inputs.attached["pointers"];
  47575. if (pointers) {
  47576. pointers.angularSensibilityY = value;
  47577. }
  47578. },
  47579. enumerable: true,
  47580. configurable: true
  47581. });
  47582. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47583. /**
  47584. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  47585. */
  47586. get: function () {
  47587. var pointers = this.inputs.attached["pointers"];
  47588. if (pointers)
  47589. return pointers.pinchPrecision;
  47590. return 0;
  47591. },
  47592. set: function (value) {
  47593. var pointers = this.inputs.attached["pointers"];
  47594. if (pointers) {
  47595. pointers.pinchPrecision = value;
  47596. }
  47597. },
  47598. enumerable: true,
  47599. configurable: true
  47600. });
  47601. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47602. /**
  47603. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  47604. * It will be used instead of pinchDeltaPrecision if different from 0.
  47605. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47606. */
  47607. get: function () {
  47608. var pointers = this.inputs.attached["pointers"];
  47609. if (pointers)
  47610. return pointers.pinchDeltaPercentage;
  47611. return 0;
  47612. },
  47613. set: function (value) {
  47614. var pointers = this.inputs.attached["pointers"];
  47615. if (pointers) {
  47616. pointers.pinchDeltaPercentage = value;
  47617. }
  47618. },
  47619. enumerable: true,
  47620. configurable: true
  47621. });
  47622. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47623. /**
  47624. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  47625. */
  47626. get: function () {
  47627. var pointers = this.inputs.attached["pointers"];
  47628. if (pointers)
  47629. return pointers.panningSensibility;
  47630. return 0;
  47631. },
  47632. set: function (value) {
  47633. var pointers = this.inputs.attached["pointers"];
  47634. if (pointers) {
  47635. pointers.panningSensibility = value;
  47636. }
  47637. },
  47638. enumerable: true,
  47639. configurable: true
  47640. });
  47641. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47642. /**
  47643. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  47644. */
  47645. get: function () {
  47646. var keyboard = this.inputs.attached["keyboard"];
  47647. if (keyboard)
  47648. return keyboard.keysUp;
  47649. return [];
  47650. },
  47651. set: function (value) {
  47652. var keyboard = this.inputs.attached["keyboard"];
  47653. if (keyboard)
  47654. keyboard.keysUp = value;
  47655. },
  47656. enumerable: true,
  47657. configurable: true
  47658. });
  47659. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47660. /**
  47661. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  47662. */
  47663. get: function () {
  47664. var keyboard = this.inputs.attached["keyboard"];
  47665. if (keyboard)
  47666. return keyboard.keysDown;
  47667. return [];
  47668. },
  47669. set: function (value) {
  47670. var keyboard = this.inputs.attached["keyboard"];
  47671. if (keyboard)
  47672. keyboard.keysDown = value;
  47673. },
  47674. enumerable: true,
  47675. configurable: true
  47676. });
  47677. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47678. /**
  47679. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  47680. */
  47681. get: function () {
  47682. var keyboard = this.inputs.attached["keyboard"];
  47683. if (keyboard)
  47684. return keyboard.keysLeft;
  47685. return [];
  47686. },
  47687. set: function (value) {
  47688. var keyboard = this.inputs.attached["keyboard"];
  47689. if (keyboard)
  47690. keyboard.keysLeft = value;
  47691. },
  47692. enumerable: true,
  47693. configurable: true
  47694. });
  47695. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47696. /**
  47697. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  47698. */
  47699. get: function () {
  47700. var keyboard = this.inputs.attached["keyboard"];
  47701. if (keyboard)
  47702. return keyboard.keysRight;
  47703. return [];
  47704. },
  47705. set: function (value) {
  47706. var keyboard = this.inputs.attached["keyboard"];
  47707. if (keyboard)
  47708. keyboard.keysRight = value;
  47709. },
  47710. enumerable: true,
  47711. configurable: true
  47712. });
  47713. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47714. /**
  47715. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  47716. */
  47717. get: function () {
  47718. var mousewheel = this.inputs.attached["mousewheel"];
  47719. if (mousewheel)
  47720. return mousewheel.wheelPrecision;
  47721. return 0;
  47722. },
  47723. set: function (value) {
  47724. var mousewheel = this.inputs.attached["mousewheel"];
  47725. if (mousewheel)
  47726. mousewheel.wheelPrecision = value;
  47727. },
  47728. enumerable: true,
  47729. configurable: true
  47730. });
  47731. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47732. /**
  47733. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  47734. * It will be used instead of pinchDeltaPrecision if different from 0.
  47735. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47736. */
  47737. get: function () {
  47738. var mousewheel = this.inputs.attached["mousewheel"];
  47739. if (mousewheel)
  47740. return mousewheel.wheelDeltaPercentage;
  47741. return 0;
  47742. },
  47743. set: function (value) {
  47744. var mousewheel = this.inputs.attached["mousewheel"];
  47745. if (mousewheel)
  47746. mousewheel.wheelDeltaPercentage = value;
  47747. },
  47748. enumerable: true,
  47749. configurable: true
  47750. });
  47751. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47752. /**
  47753. * Gets the bouncing behavior of the camera if it has been enabled.
  47754. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  47755. */
  47756. get: function () {
  47757. return this._bouncingBehavior;
  47758. },
  47759. enumerable: true,
  47760. configurable: true
  47761. });
  47762. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47763. /**
  47764. * Defines if the bouncing behavior of the camera is enabled on the camera.
  47765. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  47766. */
  47767. get: function () {
  47768. return this._bouncingBehavior != null;
  47769. },
  47770. set: function (value) {
  47771. if (value === this.useBouncingBehavior) {
  47772. return;
  47773. }
  47774. if (value) {
  47775. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47776. this.addBehavior(this._bouncingBehavior);
  47777. }
  47778. else if (this._bouncingBehavior) {
  47779. this.removeBehavior(this._bouncingBehavior);
  47780. this._bouncingBehavior = null;
  47781. }
  47782. },
  47783. enumerable: true,
  47784. configurable: true
  47785. });
  47786. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47787. /**
  47788. * Gets the framing behavior of the camera if it has been enabled.
  47789. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  47790. */
  47791. get: function () {
  47792. return this._framingBehavior;
  47793. },
  47794. enumerable: true,
  47795. configurable: true
  47796. });
  47797. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47798. /**
  47799. * Defines if the framing behavior of the camera is enabled on the camera.
  47800. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  47801. */
  47802. get: function () {
  47803. return this._framingBehavior != null;
  47804. },
  47805. set: function (value) {
  47806. if (value === this.useFramingBehavior) {
  47807. return;
  47808. }
  47809. if (value) {
  47810. this._framingBehavior = new BABYLON.FramingBehavior();
  47811. this.addBehavior(this._framingBehavior);
  47812. }
  47813. else if (this._framingBehavior) {
  47814. this.removeBehavior(this._framingBehavior);
  47815. this._framingBehavior = null;
  47816. }
  47817. },
  47818. enumerable: true,
  47819. configurable: true
  47820. });
  47821. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47822. /**
  47823. * Gets the auto rotation behavior of the camera if it has been enabled.
  47824. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  47825. */
  47826. get: function () {
  47827. return this._autoRotationBehavior;
  47828. },
  47829. enumerable: true,
  47830. configurable: true
  47831. });
  47832. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47833. /**
  47834. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  47835. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  47836. */
  47837. get: function () {
  47838. return this._autoRotationBehavior != null;
  47839. },
  47840. set: function (value) {
  47841. if (value === this.useAutoRotationBehavior) {
  47842. return;
  47843. }
  47844. if (value) {
  47845. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47846. this.addBehavior(this._autoRotationBehavior);
  47847. }
  47848. else if (this._autoRotationBehavior) {
  47849. this.removeBehavior(this._autoRotationBehavior);
  47850. this._autoRotationBehavior = null;
  47851. }
  47852. },
  47853. enumerable: true,
  47854. configurable: true
  47855. });
  47856. // Cache
  47857. /** @hidden */
  47858. ArcRotateCamera.prototype._initCache = function () {
  47859. _super.prototype._initCache.call(this);
  47860. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47861. this._cache.alpha = undefined;
  47862. this._cache.beta = undefined;
  47863. this._cache.radius = undefined;
  47864. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47865. };
  47866. /** @hidden */
  47867. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47868. if (!ignoreParentClass) {
  47869. _super.prototype._updateCache.call(this);
  47870. }
  47871. this._cache._target.copyFrom(this._getTargetPosition());
  47872. this._cache.alpha = this.alpha;
  47873. this._cache.beta = this.beta;
  47874. this._cache.radius = this.radius;
  47875. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47876. };
  47877. ArcRotateCamera.prototype._getTargetPosition = function () {
  47878. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47879. var pos = this._targetHost.getAbsolutePosition();
  47880. if (this._targetBoundingCenter) {
  47881. pos.addToRef(this._targetBoundingCenter, this._target);
  47882. }
  47883. else {
  47884. this._target.copyFrom(pos);
  47885. }
  47886. }
  47887. var lockedTargetPosition = this._getLockedTargetPosition();
  47888. if (lockedTargetPosition) {
  47889. return lockedTargetPosition;
  47890. }
  47891. return this._target;
  47892. };
  47893. /**
  47894. * Stores the current state of the camera (alpha, beta, radius and target)
  47895. * @returns the camera itself
  47896. */
  47897. ArcRotateCamera.prototype.storeState = function () {
  47898. this._storedAlpha = this.alpha;
  47899. this._storedBeta = this.beta;
  47900. this._storedRadius = this.radius;
  47901. this._storedTarget = this._getTargetPosition().clone();
  47902. return _super.prototype.storeState.call(this);
  47903. };
  47904. /**
  47905. * @hidden
  47906. * Restored camera state. You must call storeState() first
  47907. */
  47908. ArcRotateCamera.prototype._restoreStateValues = function () {
  47909. if (!_super.prototype._restoreStateValues.call(this)) {
  47910. return false;
  47911. }
  47912. this.alpha = this._storedAlpha;
  47913. this.beta = this._storedBeta;
  47914. this.radius = this._storedRadius;
  47915. this.setTarget(this._storedTarget.clone());
  47916. this.inertialAlphaOffset = 0;
  47917. this.inertialBetaOffset = 0;
  47918. this.inertialRadiusOffset = 0;
  47919. this.inertialPanningX = 0;
  47920. this.inertialPanningY = 0;
  47921. return true;
  47922. };
  47923. // Synchronized
  47924. /** @hidden */
  47925. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47926. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47927. return false;
  47928. return this._cache._target.equals(this._getTargetPosition())
  47929. && this._cache.alpha === this.alpha
  47930. && this._cache.beta === this.beta
  47931. && this._cache.radius === this.radius
  47932. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47933. };
  47934. /**
  47935. * Attached controls to the current camera.
  47936. * @param element Defines the element the controls should be listened from
  47937. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47938. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  47939. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  47940. */
  47941. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47942. var _this = this;
  47943. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47944. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47945. this._useCtrlForPanning = useCtrlForPanning;
  47946. this._panningMouseButton = panningMouseButton;
  47947. this.inputs.attachElement(element, noPreventDefault);
  47948. this._reset = function () {
  47949. _this.inertialAlphaOffset = 0;
  47950. _this.inertialBetaOffset = 0;
  47951. _this.inertialRadiusOffset = 0;
  47952. _this.inertialPanningX = 0;
  47953. _this.inertialPanningY = 0;
  47954. };
  47955. };
  47956. /**
  47957. * Detach the current controls from the camera.
  47958. * The camera will stop reacting to inputs.
  47959. * @param element Defines the element to stop listening the inputs from
  47960. */
  47961. ArcRotateCamera.prototype.detachControl = function (element) {
  47962. this.inputs.detachElement(element);
  47963. if (this._reset) {
  47964. this._reset();
  47965. }
  47966. };
  47967. /** @hidden */
  47968. ArcRotateCamera.prototype._checkInputs = function () {
  47969. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47970. if (this._collisionTriggered) {
  47971. return;
  47972. }
  47973. this.inputs.checkInputs();
  47974. // Inertia
  47975. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47976. var inertialAlphaOffset = this.inertialAlphaOffset;
  47977. if (this.beta <= 0)
  47978. inertialAlphaOffset *= -1;
  47979. if (this.getScene().useRightHandedSystem)
  47980. inertialAlphaOffset *= -1;
  47981. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47982. inertialAlphaOffset *= -1;
  47983. this.alpha += inertialAlphaOffset;
  47984. this.beta += this.inertialBetaOffset;
  47985. this.radius -= this.inertialRadiusOffset;
  47986. this.inertialAlphaOffset *= this.inertia;
  47987. this.inertialBetaOffset *= this.inertia;
  47988. this.inertialRadiusOffset *= this.inertia;
  47989. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47990. this.inertialAlphaOffset = 0;
  47991. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47992. this.inertialBetaOffset = 0;
  47993. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47994. this.inertialRadiusOffset = 0;
  47995. }
  47996. // Panning inertia
  47997. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47998. if (!this._localDirection) {
  47999. this._localDirection = BABYLON.Vector3.Zero();
  48000. this._transformedDirection = BABYLON.Vector3.Zero();
  48001. }
  48002. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48003. this._localDirection.multiplyInPlace(this.panningAxis);
  48004. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48005. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48006. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48007. if (!this.panningAxis.y) {
  48008. this._transformedDirection.y = 0;
  48009. }
  48010. if (!this._targetHost) {
  48011. if (this.panningDistanceLimit) {
  48012. this._transformedDirection.addInPlace(this._target);
  48013. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48014. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48015. this._target.copyFrom(this._transformedDirection);
  48016. }
  48017. }
  48018. else {
  48019. this._target.addInPlace(this._transformedDirection);
  48020. }
  48021. }
  48022. this.inertialPanningX *= this.panningInertia;
  48023. this.inertialPanningY *= this.panningInertia;
  48024. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48025. this.inertialPanningX = 0;
  48026. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48027. this.inertialPanningY = 0;
  48028. }
  48029. // Limits
  48030. this._checkLimits();
  48031. _super.prototype._checkInputs.call(this);
  48032. };
  48033. ArcRotateCamera.prototype._checkLimits = function () {
  48034. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48035. if (this.allowUpsideDown && this.beta > Math.PI) {
  48036. this.beta = this.beta - (2 * Math.PI);
  48037. }
  48038. }
  48039. else {
  48040. if (this.beta < this.lowerBetaLimit) {
  48041. this.beta = this.lowerBetaLimit;
  48042. }
  48043. }
  48044. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48045. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48046. this.beta = this.beta + (2 * Math.PI);
  48047. }
  48048. }
  48049. else {
  48050. if (this.beta > this.upperBetaLimit) {
  48051. this.beta = this.upperBetaLimit;
  48052. }
  48053. }
  48054. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48055. this.alpha = this.lowerAlphaLimit;
  48056. }
  48057. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48058. this.alpha = this.upperAlphaLimit;
  48059. }
  48060. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48061. this.radius = this.lowerRadiusLimit;
  48062. }
  48063. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48064. this.radius = this.upperRadiusLimit;
  48065. }
  48066. };
  48067. /**
  48068. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  48069. */
  48070. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48071. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48072. this.radius = this._computationVector.length();
  48073. if (this.radius === 0) {
  48074. this.radius = 0.0001; // Just to avoid division by zero
  48075. }
  48076. // Alpha
  48077. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48078. if (this._computationVector.z < 0) {
  48079. this.alpha = 2 * Math.PI - this.alpha;
  48080. }
  48081. // Beta
  48082. this.beta = Math.acos(this._computationVector.y / this.radius);
  48083. this._checkLimits();
  48084. };
  48085. /**
  48086. * Use a position to define the current camera related information like aplha, beta and radius
  48087. * @param position Defines the position to set the camera at
  48088. */
  48089. ArcRotateCamera.prototype.setPosition = function (position) {
  48090. if (this.position.equals(position)) {
  48091. return;
  48092. }
  48093. this.position.copyFrom(position);
  48094. this.rebuildAnglesAndRadius();
  48095. };
  48096. /**
  48097. * Defines the target the camera should look at.
  48098. * This will automatically adapt alpha beta and radius to fit within the new target.
  48099. * @param target Defines the new target as a Vector or a mesh
  48100. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  48101. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  48102. */
  48103. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48104. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48105. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48106. if (target.getBoundingInfo) {
  48107. if (toBoundingCenter) {
  48108. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48109. }
  48110. else {
  48111. this._targetBoundingCenter = null;
  48112. }
  48113. this._targetHost = target;
  48114. this._target = this._getTargetPosition();
  48115. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48116. }
  48117. else {
  48118. var newTarget = target;
  48119. var currentTarget = this._getTargetPosition();
  48120. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48121. return;
  48122. }
  48123. this._targetHost = null;
  48124. this._target = newTarget;
  48125. this._targetBoundingCenter = null;
  48126. this.onMeshTargetChangedObservable.notifyObservers(null);
  48127. }
  48128. this.rebuildAnglesAndRadius();
  48129. };
  48130. /** @hidden */
  48131. ArcRotateCamera.prototype._getViewMatrix = function () {
  48132. // Compute
  48133. var cosa = Math.cos(this.alpha);
  48134. var sina = Math.sin(this.alpha);
  48135. var cosb = Math.cos(this.beta);
  48136. var sinb = Math.sin(this.beta);
  48137. if (sinb === 0) {
  48138. sinb = 0.0001;
  48139. }
  48140. var target = this._getTargetPosition();
  48141. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48142. target.addToRef(this._computationVector, this._newPosition);
  48143. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48144. if (!this._collider) {
  48145. this._collider = new BABYLON.Collider();
  48146. }
  48147. this._collider._radius = this.collisionRadius;
  48148. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48149. this._collisionTriggered = true;
  48150. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48151. }
  48152. else {
  48153. this.position.copyFrom(this._newPosition);
  48154. var up = this.upVector;
  48155. if (this.allowUpsideDown && sinb < 0) {
  48156. up = up.clone();
  48157. up = up.negate();
  48158. }
  48159. this._computeViewMatrix(this.position, target, up);
  48160. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48161. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48162. }
  48163. this._currentTarget = target;
  48164. return this._viewMatrix;
  48165. };
  48166. /**
  48167. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  48168. * @param meshes Defines the mesh to zoom on
  48169. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  48170. */
  48171. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48172. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48173. meshes = meshes || this.getScene().meshes;
  48174. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48175. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48176. this.radius = distance * this.zoomOnFactor;
  48177. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48178. };
  48179. /**
  48180. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  48181. * The target will be changed but the radius
  48182. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  48183. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  48184. */
  48185. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48186. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48187. var meshesOrMinMaxVector;
  48188. var distance;
  48189. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48190. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48191. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48192. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48193. }
  48194. else { //minMaxVector and distance
  48195. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48196. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48197. distance = minMaxVectorAndDistance.distance;
  48198. }
  48199. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48200. if (!doNotUpdateMaxZ) {
  48201. this.maxZ = distance * 2;
  48202. }
  48203. };
  48204. /**
  48205. * @override
  48206. * Override Camera.createRigCamera
  48207. */
  48208. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48209. var alphaShift = 0;
  48210. switch (this.cameraRigMode) {
  48211. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48212. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48213. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48214. case BABYLON.Camera.RIG_MODE_VR:
  48215. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48216. break;
  48217. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48218. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48219. break;
  48220. }
  48221. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48222. rigCam._cameraRigParams = {};
  48223. return rigCam;
  48224. };
  48225. /**
  48226. * @hidden
  48227. * @override
  48228. * Override Camera._updateRigCameras
  48229. */
  48230. ArcRotateCamera.prototype._updateRigCameras = function () {
  48231. var camLeft = this._rigCameras[0];
  48232. var camRight = this._rigCameras[1];
  48233. camLeft.beta = camRight.beta = this.beta;
  48234. camLeft.radius = camRight.radius = this.radius;
  48235. switch (this.cameraRigMode) {
  48236. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48237. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48238. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48239. case BABYLON.Camera.RIG_MODE_VR:
  48240. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48241. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48242. break;
  48243. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48244. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48245. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48246. break;
  48247. }
  48248. _super.prototype._updateRigCameras.call(this);
  48249. };
  48250. /**
  48251. * Destroy the camera and release the current resources hold by it.
  48252. */
  48253. ArcRotateCamera.prototype.dispose = function () {
  48254. this.inputs.clear();
  48255. _super.prototype.dispose.call(this);
  48256. };
  48257. /**
  48258. * Gets the current object class name.
  48259. * @return the class name
  48260. */
  48261. ArcRotateCamera.prototype.getClassName = function () {
  48262. return "ArcRotateCamera";
  48263. };
  48264. __decorate([
  48265. BABYLON.serialize()
  48266. ], ArcRotateCamera.prototype, "alpha", void 0);
  48267. __decorate([
  48268. BABYLON.serialize()
  48269. ], ArcRotateCamera.prototype, "beta", void 0);
  48270. __decorate([
  48271. BABYLON.serialize()
  48272. ], ArcRotateCamera.prototype, "radius", void 0);
  48273. __decorate([
  48274. BABYLON.serializeAsVector3("target")
  48275. ], ArcRotateCamera.prototype, "_target", void 0);
  48276. __decorate([
  48277. BABYLON.serialize()
  48278. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48279. __decorate([
  48280. BABYLON.serialize()
  48281. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48282. __decorate([
  48283. BABYLON.serialize()
  48284. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48285. __decorate([
  48286. BABYLON.serialize()
  48287. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48288. __decorate([
  48289. BABYLON.serialize()
  48290. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48291. __decorate([
  48292. BABYLON.serialize()
  48293. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48294. __decorate([
  48295. BABYLON.serialize()
  48296. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48297. __decorate([
  48298. BABYLON.serialize()
  48299. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48300. __decorate([
  48301. BABYLON.serialize()
  48302. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48303. __decorate([
  48304. BABYLON.serialize()
  48305. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48306. __decorate([
  48307. BABYLON.serialize()
  48308. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48309. __decorate([
  48310. BABYLON.serialize()
  48311. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48312. __decorate([
  48313. BABYLON.serialize()
  48314. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48315. __decorate([
  48316. BABYLON.serializeAsVector3()
  48317. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48318. __decorate([
  48319. BABYLON.serialize()
  48320. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48321. __decorate([
  48322. BABYLON.serialize()
  48323. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48324. __decorate([
  48325. BABYLON.serialize()
  48326. ], ArcRotateCamera.prototype, "targetScreenOffset", 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. * Computes the world matrix of the node
  48412. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  48413. * @param useWasUpdatedFlag defines a reserved property
  48414. * @returns the world matrix
  48415. */
  48416. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  48417. if (!this._worldMatrix) {
  48418. this._worldMatrix = BABYLON.Matrix.Identity();
  48419. }
  48420. return this._worldMatrix;
  48421. };
  48422. /**
  48423. * Returns the integer 3.
  48424. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48425. */
  48426. HemisphericLight.prototype.getTypeID = function () {
  48427. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48428. };
  48429. /**
  48430. * Prepares the list of defines specific to the light type.
  48431. * @param defines the list of defines
  48432. * @param lightIndex defines the index of the light for the effect
  48433. */
  48434. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48435. defines["HEMILIGHT" + lightIndex] = true;
  48436. };
  48437. __decorate([
  48438. BABYLON.serializeAsColor3()
  48439. ], HemisphericLight.prototype, "groundColor", void 0);
  48440. __decorate([
  48441. BABYLON.serializeAsVector3()
  48442. ], HemisphericLight.prototype, "direction", void 0);
  48443. return HemisphericLight;
  48444. }(BABYLON.Light));
  48445. BABYLON.HemisphericLight = HemisphericLight;
  48446. })(BABYLON || (BABYLON = {}));
  48447. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48448. var BABYLON;
  48449. (function (BABYLON) {
  48450. /**
  48451. * Base implementation IShadowLight
  48452. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48453. */
  48454. var ShadowLight = /** @class */ (function (_super) {
  48455. __extends(ShadowLight, _super);
  48456. function ShadowLight() {
  48457. var _this = _super !== null && _super.apply(this, arguments) || this;
  48458. _this._needProjectionMatrixCompute = true;
  48459. return _this;
  48460. }
  48461. ShadowLight.prototype._setPosition = function (value) {
  48462. this._position = value;
  48463. };
  48464. Object.defineProperty(ShadowLight.prototype, "position", {
  48465. /**
  48466. * Sets the position the shadow will be casted from. Also use as the light position for both
  48467. * point and spot lights.
  48468. */
  48469. get: function () {
  48470. return this._position;
  48471. },
  48472. /**
  48473. * Sets the position the shadow will be casted from. Also use as the light position for both
  48474. * point and spot lights.
  48475. */
  48476. set: function (value) {
  48477. this._setPosition(value);
  48478. },
  48479. enumerable: true,
  48480. configurable: true
  48481. });
  48482. ShadowLight.prototype._setDirection = function (value) {
  48483. this._direction = value;
  48484. };
  48485. Object.defineProperty(ShadowLight.prototype, "direction", {
  48486. /**
  48487. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48488. * Also use as the light direction on spot and directional lights.
  48489. */
  48490. get: function () {
  48491. return this._direction;
  48492. },
  48493. /**
  48494. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48495. * Also use as the light direction on spot and directional lights.
  48496. */
  48497. set: function (value) {
  48498. this._setDirection(value);
  48499. },
  48500. enumerable: true,
  48501. configurable: true
  48502. });
  48503. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48504. /**
  48505. * Gets the shadow projection clipping minimum z value.
  48506. */
  48507. get: function () {
  48508. return this._shadowMinZ;
  48509. },
  48510. /**
  48511. * Sets the shadow projection clipping minimum z value.
  48512. */
  48513. set: function (value) {
  48514. this._shadowMinZ = value;
  48515. this.forceProjectionMatrixCompute();
  48516. },
  48517. enumerable: true,
  48518. configurable: true
  48519. });
  48520. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48521. /**
  48522. * Sets the shadow projection clipping maximum z value.
  48523. */
  48524. get: function () {
  48525. return this._shadowMaxZ;
  48526. },
  48527. /**
  48528. * Gets the shadow projection clipping maximum z value.
  48529. */
  48530. set: function (value) {
  48531. this._shadowMaxZ = value;
  48532. this.forceProjectionMatrixCompute();
  48533. },
  48534. enumerable: true,
  48535. configurable: true
  48536. });
  48537. /**
  48538. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48539. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48540. */
  48541. ShadowLight.prototype.computeTransformedInformation = function () {
  48542. if (this.parent && this.parent.getWorldMatrix) {
  48543. if (!this.transformedPosition) {
  48544. this.transformedPosition = BABYLON.Vector3.Zero();
  48545. }
  48546. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48547. // In case the direction is present.
  48548. if (this.direction) {
  48549. if (!this.transformedDirection) {
  48550. this.transformedDirection = BABYLON.Vector3.Zero();
  48551. }
  48552. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48553. }
  48554. return true;
  48555. }
  48556. return false;
  48557. };
  48558. /**
  48559. * Return the depth scale used for the shadow map.
  48560. * @returns the depth scale.
  48561. */
  48562. ShadowLight.prototype.getDepthScale = function () {
  48563. return 50.0;
  48564. };
  48565. /**
  48566. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48567. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48568. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48569. */
  48570. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48571. return this.transformedDirection ? this.transformedDirection : this.direction;
  48572. };
  48573. /**
  48574. * Returns the ShadowLight absolute position in the World.
  48575. * @returns the position vector in world space
  48576. */
  48577. ShadowLight.prototype.getAbsolutePosition = function () {
  48578. return this.transformedPosition ? this.transformedPosition : this.position;
  48579. };
  48580. /**
  48581. * Sets the ShadowLight direction toward the passed target.
  48582. * @param target The point tot target in local space
  48583. * @returns the updated ShadowLight direction
  48584. */
  48585. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48586. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48587. return this.direction;
  48588. };
  48589. /**
  48590. * Returns the light rotation in euler definition.
  48591. * @returns the x y z rotation in local space.
  48592. */
  48593. ShadowLight.prototype.getRotation = function () {
  48594. this.direction.normalize();
  48595. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48596. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48597. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48598. };
  48599. /**
  48600. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48601. * @returns true if a cube texture needs to be use
  48602. */
  48603. ShadowLight.prototype.needCube = function () {
  48604. return false;
  48605. };
  48606. /**
  48607. * Detects if the projection matrix requires to be recomputed this frame.
  48608. * @returns true if it requires to be recomputed otherwise, false.
  48609. */
  48610. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48611. return this._needProjectionMatrixCompute;
  48612. };
  48613. /**
  48614. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48615. */
  48616. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48617. this._needProjectionMatrixCompute = true;
  48618. };
  48619. /** @hidden */
  48620. ShadowLight.prototype._initCache = function () {
  48621. _super.prototype._initCache.call(this);
  48622. this._cache.position = BABYLON.Vector3.Zero();
  48623. };
  48624. /** @hidden */
  48625. ShadowLight.prototype._isSynchronized = function () {
  48626. if (!this._cache.position.equals(this.position))
  48627. return false;
  48628. return true;
  48629. };
  48630. /**
  48631. * Computes the world matrix of the node
  48632. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  48633. * @returns the world matrix
  48634. */
  48635. ShadowLight.prototype.computeWorldMatrix = function (force) {
  48636. if (!force && this.isSynchronized()) {
  48637. this._currentRenderId = this.getScene().getRenderId();
  48638. return this._worldMatrix;
  48639. }
  48640. this._updateCache();
  48641. this._cache.position.copyFrom(this.position);
  48642. if (!this._worldMatrix) {
  48643. this._worldMatrix = BABYLON.Matrix.Identity();
  48644. }
  48645. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48646. if (this.parent && this.parent.getWorldMatrix) {
  48647. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  48648. this._markSyncedWithParent();
  48649. }
  48650. // Cache the determinant
  48651. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  48652. return this._worldMatrix;
  48653. };
  48654. /**
  48655. * Gets the minZ used for shadow according to both the scene and the light.
  48656. * @param activeCamera The camera we are returning the min for
  48657. * @returns the depth min z
  48658. */
  48659. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48660. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48661. };
  48662. /**
  48663. * Gets the maxZ used for shadow according to both the scene and the light.
  48664. * @param activeCamera The camera we are returning the max for
  48665. * @returns the depth max z
  48666. */
  48667. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48668. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48669. };
  48670. /**
  48671. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48672. * @param matrix The materix to updated with the projection information
  48673. * @param viewMatrix The transform matrix of the light
  48674. * @param renderList The list of mesh to render in the map
  48675. * @returns The current light
  48676. */
  48677. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48678. if (this.customProjectionMatrixBuilder) {
  48679. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48680. }
  48681. else {
  48682. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48683. }
  48684. return this;
  48685. };
  48686. __decorate([
  48687. BABYLON.serializeAsVector3()
  48688. ], ShadowLight.prototype, "position", null);
  48689. __decorate([
  48690. BABYLON.serializeAsVector3()
  48691. ], ShadowLight.prototype, "direction", null);
  48692. __decorate([
  48693. BABYLON.serialize()
  48694. ], ShadowLight.prototype, "shadowMinZ", null);
  48695. __decorate([
  48696. BABYLON.serialize()
  48697. ], ShadowLight.prototype, "shadowMaxZ", null);
  48698. return ShadowLight;
  48699. }(BABYLON.Light));
  48700. BABYLON.ShadowLight = ShadowLight;
  48701. })(BABYLON || (BABYLON = {}));
  48702. //# sourceMappingURL=babylon.shadowLight.js.map
  48703. var BABYLON;
  48704. (function (BABYLON) {
  48705. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48706. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48707. });
  48708. /**
  48709. * A point light is a light defined by an unique point in world space.
  48710. * The light is emitted in every direction from this point.
  48711. * A good example of a point light is a standard light bulb.
  48712. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48713. */
  48714. var PointLight = /** @class */ (function (_super) {
  48715. __extends(PointLight, _super);
  48716. /**
  48717. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48718. * A PointLight emits the light in every direction.
  48719. * It can cast shadows.
  48720. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48721. * ```javascript
  48722. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48723. * ```
  48724. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48725. * @param name The light friendly name
  48726. * @param position The position of the point light in the scene
  48727. * @param scene The scene the lights belongs to
  48728. */
  48729. function PointLight(name, position, scene) {
  48730. var _this = _super.call(this, name, scene) || this;
  48731. _this._shadowAngle = Math.PI / 2;
  48732. _this.position = position;
  48733. return _this;
  48734. }
  48735. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48736. /**
  48737. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48738. * This specifies what angle the shadow will use to be created.
  48739. *
  48740. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48741. */
  48742. get: function () {
  48743. return this._shadowAngle;
  48744. },
  48745. /**
  48746. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48747. * This specifies what angle the shadow will use to be created.
  48748. *
  48749. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48750. */
  48751. set: function (value) {
  48752. this._shadowAngle = value;
  48753. this.forceProjectionMatrixCompute();
  48754. },
  48755. enumerable: true,
  48756. configurable: true
  48757. });
  48758. Object.defineProperty(PointLight.prototype, "direction", {
  48759. /**
  48760. * Gets the direction if it has been set.
  48761. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48762. */
  48763. get: function () {
  48764. return this._direction;
  48765. },
  48766. /**
  48767. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48768. */
  48769. set: function (value) {
  48770. var previousNeedCube = this.needCube();
  48771. this._direction = value;
  48772. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48773. this._shadowGenerator.recreateShadowMap();
  48774. }
  48775. },
  48776. enumerable: true,
  48777. configurable: true
  48778. });
  48779. /**
  48780. * Returns the string "PointLight"
  48781. * @returns the class name
  48782. */
  48783. PointLight.prototype.getClassName = function () {
  48784. return "PointLight";
  48785. };
  48786. /**
  48787. * Returns the integer 0.
  48788. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48789. */
  48790. PointLight.prototype.getTypeID = function () {
  48791. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48792. };
  48793. /**
  48794. * Specifies wether or not the shadowmap should be a cube texture.
  48795. * @returns true if the shadowmap needs to be a cube texture.
  48796. */
  48797. PointLight.prototype.needCube = function () {
  48798. return !this.direction;
  48799. };
  48800. /**
  48801. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48802. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48803. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48804. */
  48805. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48806. if (this.direction) {
  48807. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48808. }
  48809. else {
  48810. switch (faceIndex) {
  48811. case 0:
  48812. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48813. case 1:
  48814. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48815. case 2:
  48816. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48817. case 3:
  48818. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48819. case 4:
  48820. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48821. case 5:
  48822. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48823. }
  48824. }
  48825. return BABYLON.Vector3.Zero();
  48826. };
  48827. /**
  48828. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48829. * - fov = PI / 2
  48830. * - aspect ratio : 1.0
  48831. * - z-near and far equal to the active camera minZ and maxZ.
  48832. * Returns the PointLight.
  48833. */
  48834. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48835. var activeCamera = this.getScene().activeCamera;
  48836. if (!activeCamera) {
  48837. return;
  48838. }
  48839. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48840. };
  48841. PointLight.prototype._buildUniformLayout = function () {
  48842. this._uniformBuffer.addUniform("vLightData", 4);
  48843. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48844. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48845. this._uniformBuffer.addUniform("vLightFalloff", 4);
  48846. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48847. this._uniformBuffer.addUniform("depthValues", 2);
  48848. this._uniformBuffer.create();
  48849. };
  48850. /**
  48851. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48852. * @param effect The effect to update
  48853. * @param lightIndex The index of the light in the effect to update
  48854. * @returns The point light
  48855. */
  48856. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48857. if (this.computeTransformedInformation()) {
  48858. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48859. }
  48860. else {
  48861. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48862. }
  48863. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  48864. return this;
  48865. };
  48866. /**
  48867. * Prepares the list of defines specific to the light type.
  48868. * @param defines the list of defines
  48869. * @param lightIndex defines the index of the light for the effect
  48870. */
  48871. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48872. defines["POINTLIGHT" + lightIndex] = true;
  48873. };
  48874. __decorate([
  48875. BABYLON.serialize()
  48876. ], PointLight.prototype, "shadowAngle", null);
  48877. return PointLight;
  48878. }(BABYLON.ShadowLight));
  48879. BABYLON.PointLight = PointLight;
  48880. })(BABYLON || (BABYLON = {}));
  48881. //# sourceMappingURL=babylon.pointLight.js.map
  48882. var BABYLON;
  48883. (function (BABYLON) {
  48884. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48885. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48886. });
  48887. /**
  48888. * A directional light is defined by a direction (what a surprise!).
  48889. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48890. * 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.
  48891. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48892. */
  48893. var DirectionalLight = /** @class */ (function (_super) {
  48894. __extends(DirectionalLight, _super);
  48895. /**
  48896. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48897. * The directional light is emitted from everywhere in the given direction.
  48898. * It can cast shawdows.
  48899. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48900. * @param name The friendly name of the light
  48901. * @param direction The direction of the light
  48902. * @param scene The scene the light belongs to
  48903. */
  48904. function DirectionalLight(name, direction, scene) {
  48905. var _this = _super.call(this, name, scene) || this;
  48906. _this._shadowFrustumSize = 0;
  48907. _this._shadowOrthoScale = 0.1;
  48908. /**
  48909. * Automatically compute the projection matrix to best fit (including all the casters)
  48910. * on each frame.
  48911. */
  48912. _this.autoUpdateExtends = true;
  48913. // Cache
  48914. _this._orthoLeft = Number.MAX_VALUE;
  48915. _this._orthoRight = Number.MIN_VALUE;
  48916. _this._orthoTop = Number.MIN_VALUE;
  48917. _this._orthoBottom = Number.MAX_VALUE;
  48918. _this.position = direction.scale(-1.0);
  48919. _this.direction = direction;
  48920. return _this;
  48921. }
  48922. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48923. /**
  48924. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48925. */
  48926. get: function () {
  48927. return this._shadowFrustumSize;
  48928. },
  48929. /**
  48930. * Specifies a fix frustum size for the shadow generation.
  48931. */
  48932. set: function (value) {
  48933. this._shadowFrustumSize = value;
  48934. this.forceProjectionMatrixCompute();
  48935. },
  48936. enumerable: true,
  48937. configurable: true
  48938. });
  48939. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48940. /**
  48941. * Gets the shadow projection scale against the optimal computed one.
  48942. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48943. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48944. */
  48945. get: function () {
  48946. return this._shadowOrthoScale;
  48947. },
  48948. /**
  48949. * Sets the shadow projection scale against the optimal computed one.
  48950. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48951. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48952. */
  48953. set: function (value) {
  48954. this._shadowOrthoScale = value;
  48955. this.forceProjectionMatrixCompute();
  48956. },
  48957. enumerable: true,
  48958. configurable: true
  48959. });
  48960. /**
  48961. * Returns the string "DirectionalLight".
  48962. * @return The class name
  48963. */
  48964. DirectionalLight.prototype.getClassName = function () {
  48965. return "DirectionalLight";
  48966. };
  48967. /**
  48968. * Returns the integer 1.
  48969. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48970. */
  48971. DirectionalLight.prototype.getTypeID = function () {
  48972. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48973. };
  48974. /**
  48975. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48976. * Returns the DirectionalLight Shadow projection matrix.
  48977. */
  48978. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48979. if (this.shadowFrustumSize > 0) {
  48980. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48981. }
  48982. else {
  48983. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48984. }
  48985. };
  48986. /**
  48987. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48988. * Returns the DirectionalLight Shadow projection matrix.
  48989. */
  48990. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48991. var activeCamera = this.getScene().activeCamera;
  48992. if (!activeCamera) {
  48993. return;
  48994. }
  48995. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48996. };
  48997. /**
  48998. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48999. * Returns the DirectionalLight Shadow projection matrix.
  49000. */
  49001. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49002. var activeCamera = this.getScene().activeCamera;
  49003. if (!activeCamera) {
  49004. return;
  49005. }
  49006. // Check extends
  49007. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49008. var tempVector3 = BABYLON.Vector3.Zero();
  49009. this._orthoLeft = Number.MAX_VALUE;
  49010. this._orthoRight = Number.MIN_VALUE;
  49011. this._orthoTop = Number.MIN_VALUE;
  49012. this._orthoBottom = Number.MAX_VALUE;
  49013. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49014. var mesh = renderList[meshIndex];
  49015. if (!mesh) {
  49016. continue;
  49017. }
  49018. var boundingInfo = mesh.getBoundingInfo();
  49019. var boundingBox = boundingInfo.boundingBox;
  49020. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49021. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49022. if (tempVector3.x < this._orthoLeft)
  49023. this._orthoLeft = tempVector3.x;
  49024. if (tempVector3.y < this._orthoBottom)
  49025. this._orthoBottom = tempVector3.y;
  49026. if (tempVector3.x > this._orthoRight)
  49027. this._orthoRight = tempVector3.x;
  49028. if (tempVector3.y > this._orthoTop)
  49029. this._orthoTop = tempVector3.y;
  49030. }
  49031. }
  49032. }
  49033. var xOffset = this._orthoRight - this._orthoLeft;
  49034. var yOffset = this._orthoTop - this._orthoBottom;
  49035. 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);
  49036. };
  49037. DirectionalLight.prototype._buildUniformLayout = function () {
  49038. this._uniformBuffer.addUniform("vLightData", 4);
  49039. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49040. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49041. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49042. this._uniformBuffer.addUniform("depthValues", 2);
  49043. this._uniformBuffer.create();
  49044. };
  49045. /**
  49046. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49047. * @param effect The effect to update
  49048. * @param lightIndex The index of the light in the effect to update
  49049. * @returns The directional light
  49050. */
  49051. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49052. if (this.computeTransformedInformation()) {
  49053. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49054. return this;
  49055. }
  49056. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49057. return this;
  49058. };
  49059. /**
  49060. * Gets the minZ used for shadow according to both the scene and the light.
  49061. *
  49062. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49063. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49064. * @param activeCamera The camera we are returning the min for
  49065. * @returns the depth min z
  49066. */
  49067. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49068. return 1;
  49069. };
  49070. /**
  49071. * Gets the maxZ used for shadow according to both the scene and the light.
  49072. *
  49073. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49074. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49075. * @param activeCamera The camera we are returning the max for
  49076. * @returns the depth max z
  49077. */
  49078. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49079. return 1;
  49080. };
  49081. /**
  49082. * Prepares the list of defines specific to the light type.
  49083. * @param defines the list of defines
  49084. * @param lightIndex defines the index of the light for the effect
  49085. */
  49086. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49087. defines["DIRLIGHT" + lightIndex] = true;
  49088. };
  49089. __decorate([
  49090. BABYLON.serialize()
  49091. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49092. __decorate([
  49093. BABYLON.serialize()
  49094. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49095. __decorate([
  49096. BABYLON.serialize()
  49097. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49098. return DirectionalLight;
  49099. }(BABYLON.ShadowLight));
  49100. BABYLON.DirectionalLight = DirectionalLight;
  49101. })(BABYLON || (BABYLON = {}));
  49102. //# sourceMappingURL=babylon.directionalLight.js.map
  49103. var BABYLON;
  49104. (function (BABYLON) {
  49105. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49106. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49107. });
  49108. /**
  49109. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49110. * These values define a cone of light starting from the position, emitting toward the direction.
  49111. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49112. * and the exponent defines the speed of the decay of the light with distance (reach).
  49113. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49114. */
  49115. var SpotLight = /** @class */ (function (_super) {
  49116. __extends(SpotLight, _super);
  49117. /**
  49118. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49119. * It can cast shadows.
  49120. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49121. * @param name The light friendly name
  49122. * @param position The position of the spot light in the scene
  49123. * @param direction The direction of the light in the scene
  49124. * @param angle The cone angle of the light in Radians
  49125. * @param exponent The light decay speed with the distance from the emission spot
  49126. * @param scene The scene the lights belongs to
  49127. */
  49128. function SpotLight(name, position, direction, angle, exponent, scene) {
  49129. var _this = _super.call(this, name, scene) || this;
  49130. _this._innerAngle = 0;
  49131. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49132. _this._projectionTextureLightNear = 1e-6;
  49133. _this._projectionTextureLightFar = 1000.0;
  49134. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49135. _this._projectionTextureViewLightDirty = true;
  49136. _this._projectionTextureProjectionLightDirty = true;
  49137. _this._projectionTextureDirty = true;
  49138. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49139. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49140. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49141. _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);
  49142. _this.position = position;
  49143. _this.direction = direction;
  49144. _this.angle = angle;
  49145. _this.exponent = exponent;
  49146. return _this;
  49147. }
  49148. Object.defineProperty(SpotLight.prototype, "angle", {
  49149. /**
  49150. * Gets the cone angle of the spot light in Radians.
  49151. */
  49152. get: function () {
  49153. return this._angle;
  49154. },
  49155. /**
  49156. * Sets the cone angle of the spot light in Radians.
  49157. */
  49158. set: function (value) {
  49159. this._angle = value;
  49160. this._cosHalfAngle = Math.cos(value * 0.5);
  49161. this._projectionTextureProjectionLightDirty = true;
  49162. this.forceProjectionMatrixCompute();
  49163. this._computeAngleValues();
  49164. },
  49165. enumerable: true,
  49166. configurable: true
  49167. });
  49168. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49169. /**
  49170. * Only used in gltf falloff mode, this defines the angle where
  49171. * the directional falloff will start before cutting at angle which could be seen
  49172. * as outer angle.
  49173. */
  49174. get: function () {
  49175. return this._angle;
  49176. },
  49177. /**
  49178. * Only used in gltf falloff mode, this defines the angle where
  49179. * the directional falloff will start before cutting at angle which could be seen
  49180. * as outer angle.
  49181. */
  49182. set: function (value) {
  49183. this._innerAngle = value;
  49184. this._computeAngleValues();
  49185. },
  49186. enumerable: true,
  49187. configurable: true
  49188. });
  49189. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49190. /**
  49191. * Allows scaling the angle of the light for shadow generation only.
  49192. */
  49193. get: function () {
  49194. return this._shadowAngleScale;
  49195. },
  49196. /**
  49197. * Allows scaling the angle of the light for shadow generation only.
  49198. */
  49199. set: function (value) {
  49200. this._shadowAngleScale = value;
  49201. this.forceProjectionMatrixCompute();
  49202. },
  49203. enumerable: true,
  49204. configurable: true
  49205. });
  49206. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49207. /**
  49208. * Allows reading the projecton texture
  49209. */
  49210. get: function () {
  49211. return this._projectionTextureMatrix;
  49212. },
  49213. enumerable: true,
  49214. configurable: true
  49215. });
  49216. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49217. /**
  49218. * Gets the near clip of the Spotlight for texture projection.
  49219. */
  49220. get: function () {
  49221. return this._projectionTextureLightNear;
  49222. },
  49223. /**
  49224. * Sets the near clip of the Spotlight for texture projection.
  49225. */
  49226. set: function (value) {
  49227. this._projectionTextureLightNear = value;
  49228. this._projectionTextureProjectionLightDirty = true;
  49229. },
  49230. enumerable: true,
  49231. configurable: true
  49232. });
  49233. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49234. /**
  49235. * Gets the far clip of the Spotlight for texture projection.
  49236. */
  49237. get: function () {
  49238. return this._projectionTextureLightFar;
  49239. },
  49240. /**
  49241. * Sets the far clip of the Spotlight for texture projection.
  49242. */
  49243. set: function (value) {
  49244. this._projectionTextureLightFar = value;
  49245. this._projectionTextureProjectionLightDirty = true;
  49246. },
  49247. enumerable: true,
  49248. configurable: true
  49249. });
  49250. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49251. /**
  49252. * Gets the Up vector of the Spotlight for texture projection.
  49253. */
  49254. get: function () {
  49255. return this._projectionTextureUpDirection;
  49256. },
  49257. /**
  49258. * Sets the Up vector of the Spotlight for texture projection.
  49259. */
  49260. set: function (value) {
  49261. this._projectionTextureUpDirection = value;
  49262. this._projectionTextureProjectionLightDirty = true;
  49263. },
  49264. enumerable: true,
  49265. configurable: true
  49266. });
  49267. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49268. /**
  49269. * Gets the projection texture of the light.
  49270. */
  49271. get: function () {
  49272. return this._projectionTexture;
  49273. },
  49274. /**
  49275. * Sets the projection texture of the light.
  49276. */
  49277. set: function (value) {
  49278. this._projectionTexture = value;
  49279. this._projectionTextureDirty = true;
  49280. },
  49281. enumerable: true,
  49282. configurable: true
  49283. });
  49284. /**
  49285. * Returns the string "SpotLight".
  49286. * @returns the class name
  49287. */
  49288. SpotLight.prototype.getClassName = function () {
  49289. return "SpotLight";
  49290. };
  49291. /**
  49292. * Returns the integer 2.
  49293. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49294. */
  49295. SpotLight.prototype.getTypeID = function () {
  49296. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49297. };
  49298. /**
  49299. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49300. */
  49301. SpotLight.prototype._setDirection = function (value) {
  49302. _super.prototype._setDirection.call(this, value);
  49303. this._projectionTextureViewLightDirty = true;
  49304. };
  49305. /**
  49306. * Overrides the position setter to recompute the projection texture view light Matrix.
  49307. */
  49308. SpotLight.prototype._setPosition = function (value) {
  49309. _super.prototype._setPosition.call(this, value);
  49310. this._projectionTextureViewLightDirty = true;
  49311. };
  49312. /**
  49313. * 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.
  49314. * Returns the SpotLight.
  49315. */
  49316. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49317. var activeCamera = this.getScene().activeCamera;
  49318. if (!activeCamera) {
  49319. return;
  49320. }
  49321. this._shadowAngleScale = this._shadowAngleScale || 1;
  49322. var angle = this._shadowAngleScale * this._angle;
  49323. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49324. };
  49325. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49326. this._projectionTextureViewLightDirty = false;
  49327. this._projectionTextureDirty = true;
  49328. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49329. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49330. };
  49331. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49332. this._projectionTextureProjectionLightDirty = false;
  49333. this._projectionTextureDirty = true;
  49334. var light_far = this.projectionTextureLightFar;
  49335. var light_near = this.projectionTextureLightNear;
  49336. var P = light_far / (light_far - light_near);
  49337. var Q = -P * light_near;
  49338. var S = 1.0 / Math.tan(this._angle / 2.0);
  49339. var A = 1.0;
  49340. 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);
  49341. };
  49342. /**
  49343. * Main function for light texture projection matrix computing.
  49344. */
  49345. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49346. this._projectionTextureDirty = false;
  49347. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49348. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49349. };
  49350. SpotLight.prototype._buildUniformLayout = function () {
  49351. this._uniformBuffer.addUniform("vLightData", 4);
  49352. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49353. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49354. this._uniformBuffer.addUniform("vLightDirection", 3);
  49355. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49356. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49357. this._uniformBuffer.addUniform("depthValues", 2);
  49358. this._uniformBuffer.create();
  49359. };
  49360. SpotLight.prototype._computeAngleValues = function () {
  49361. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49362. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49363. };
  49364. /**
  49365. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49366. * @param effect The effect to update
  49367. * @param lightIndex The index of the light in the effect to update
  49368. * @returns The spot light
  49369. */
  49370. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49371. var normalizeDirection;
  49372. if (this.computeTransformedInformation()) {
  49373. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49374. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49375. }
  49376. else {
  49377. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49378. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49379. }
  49380. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49381. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49382. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49383. if (this._projectionTextureViewLightDirty) {
  49384. this._computeProjectionTextureViewLightMatrix();
  49385. }
  49386. if (this._projectionTextureProjectionLightDirty) {
  49387. this._computeProjectionTextureProjectionLightMatrix();
  49388. }
  49389. if (this._projectionTextureDirty) {
  49390. this._computeProjectionTextureMatrix();
  49391. }
  49392. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49393. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49394. }
  49395. return this;
  49396. };
  49397. /**
  49398. * Disposes the light and the associated resources.
  49399. */
  49400. SpotLight.prototype.dispose = function () {
  49401. _super.prototype.dispose.call(this);
  49402. if (this._projectionTexture) {
  49403. this._projectionTexture.dispose();
  49404. }
  49405. };
  49406. /**
  49407. * Prepares the list of defines specific to the light type.
  49408. * @param defines the list of defines
  49409. * @param lightIndex defines the index of the light for the effect
  49410. */
  49411. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49412. defines["SPOTLIGHT" + lightIndex] = true;
  49413. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49414. };
  49415. __decorate([
  49416. BABYLON.serialize()
  49417. ], SpotLight.prototype, "angle", null);
  49418. __decorate([
  49419. BABYLON.serialize()
  49420. ], SpotLight.prototype, "innerAngle", null);
  49421. __decorate([
  49422. BABYLON.serialize()
  49423. ], SpotLight.prototype, "shadowAngleScale", null);
  49424. __decorate([
  49425. BABYLON.serialize()
  49426. ], SpotLight.prototype, "exponent", void 0);
  49427. __decorate([
  49428. BABYLON.serialize()
  49429. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49430. __decorate([
  49431. BABYLON.serialize()
  49432. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49433. __decorate([
  49434. BABYLON.serialize()
  49435. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49436. __decorate([
  49437. BABYLON.serializeAsTexture("projectedLightTexture")
  49438. ], SpotLight.prototype, "_projectionTexture", void 0);
  49439. return SpotLight;
  49440. }(BABYLON.ShadowLight));
  49441. BABYLON.SpotLight = SpotLight;
  49442. })(BABYLON || (BABYLON = {}));
  49443. //# sourceMappingURL=babylon.spotLight.js.map
  49444. var BABYLON;
  49445. (function (BABYLON) {
  49446. /**
  49447. * Class used to override all child animations of a given target
  49448. */
  49449. var AnimationPropertiesOverride = /** @class */ (function () {
  49450. function AnimationPropertiesOverride() {
  49451. /**
  49452. * Gets or sets a value indicating if animation blending must be used
  49453. */
  49454. this.enableBlending = false;
  49455. /**
  49456. * Gets or sets the blending speed to use when enableBlending is true
  49457. */
  49458. this.blendingSpeed = 0.01;
  49459. /**
  49460. * Gets or sets the default loop mode to use
  49461. */
  49462. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49463. }
  49464. return AnimationPropertiesOverride;
  49465. }());
  49466. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49467. })(BABYLON || (BABYLON = {}));
  49468. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49469. var BABYLON;
  49470. (function (BABYLON) {
  49471. /**
  49472. * Represents the range of an animation
  49473. */
  49474. var AnimationRange = /** @class */ (function () {
  49475. /**
  49476. * Initializes the range of an animation
  49477. * @param name The name of the animation range
  49478. * @param from The starting frame of the animation
  49479. * @param to The ending frame of the animation
  49480. */
  49481. function AnimationRange(
  49482. /**The name of the animation range**/
  49483. name,
  49484. /**The starting frame of the animation */
  49485. from,
  49486. /**The ending frame of the animation*/
  49487. to) {
  49488. this.name = name;
  49489. this.from = from;
  49490. this.to = to;
  49491. }
  49492. /**
  49493. * Makes a copy of the animation range
  49494. * @returns A copy of the animation range
  49495. */
  49496. AnimationRange.prototype.clone = function () {
  49497. return new AnimationRange(this.name, this.from, this.to);
  49498. };
  49499. return AnimationRange;
  49500. }());
  49501. BABYLON.AnimationRange = AnimationRange;
  49502. /**
  49503. * Composed of a frame, and an action function
  49504. */
  49505. var AnimationEvent = /** @class */ (function () {
  49506. /**
  49507. * Initializes the animation event
  49508. * @param frame The frame for which the event is triggered
  49509. * @param action The event to perform when triggered
  49510. * @param onlyOnce Specifies if the event should be triggered only once
  49511. */
  49512. function AnimationEvent(
  49513. /** The frame for which the event is triggered **/
  49514. frame,
  49515. /** The event to perform when triggered **/
  49516. action,
  49517. /** Specifies if the event should be triggered only once**/
  49518. onlyOnce) {
  49519. this.frame = frame;
  49520. this.action = action;
  49521. this.onlyOnce = onlyOnce;
  49522. /**
  49523. * Specifies if the animation event is done
  49524. */
  49525. this.isDone = false;
  49526. }
  49527. /** @hidden */
  49528. AnimationEvent.prototype._clone = function () {
  49529. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49530. };
  49531. return AnimationEvent;
  49532. }());
  49533. BABYLON.AnimationEvent = AnimationEvent;
  49534. /**
  49535. * A cursor which tracks a point on a path
  49536. */
  49537. var PathCursor = /** @class */ (function () {
  49538. /**
  49539. * Initializes the path cursor
  49540. * @param path The path to track
  49541. */
  49542. function PathCursor(path) {
  49543. this.path = path;
  49544. /**
  49545. * Stores path cursor callbacks for when an onchange event is triggered
  49546. */
  49547. this._onchange = new Array();
  49548. /**
  49549. * The value of the path cursor
  49550. */
  49551. this.value = 0;
  49552. /**
  49553. * The animation array of the path cursor
  49554. */
  49555. this.animations = new Array();
  49556. }
  49557. /**
  49558. * Gets the cursor point on the path
  49559. * @returns A point on the path cursor at the cursor location
  49560. */
  49561. PathCursor.prototype.getPoint = function () {
  49562. var point = this.path.getPointAtLengthPosition(this.value);
  49563. return new BABYLON.Vector3(point.x, 0, point.y);
  49564. };
  49565. /**
  49566. * Moves the cursor ahead by the step amount
  49567. * @param step The amount to move the cursor forward
  49568. * @returns This path cursor
  49569. */
  49570. PathCursor.prototype.moveAhead = function (step) {
  49571. if (step === void 0) { step = 0.002; }
  49572. this.move(step);
  49573. return this;
  49574. };
  49575. /**
  49576. * Moves the cursor behind by the step amount
  49577. * @param step The amount to move the cursor back
  49578. * @returns This path cursor
  49579. */
  49580. PathCursor.prototype.moveBack = function (step) {
  49581. if (step === void 0) { step = 0.002; }
  49582. this.move(-step);
  49583. return this;
  49584. };
  49585. /**
  49586. * Moves the cursor by the step amount
  49587. * If the step amount is greater than one, an exception is thrown
  49588. * @param step The amount to move the cursor
  49589. * @returns This path cursor
  49590. */
  49591. PathCursor.prototype.move = function (step) {
  49592. if (Math.abs(step) > 1) {
  49593. throw "step size should be less than 1.";
  49594. }
  49595. this.value += step;
  49596. this.ensureLimits();
  49597. this.raiseOnChange();
  49598. return this;
  49599. };
  49600. /**
  49601. * Ensures that the value is limited between zero and one
  49602. * @returns This path cursor
  49603. */
  49604. PathCursor.prototype.ensureLimits = function () {
  49605. while (this.value > 1) {
  49606. this.value -= 1;
  49607. }
  49608. while (this.value < 0) {
  49609. this.value += 1;
  49610. }
  49611. return this;
  49612. };
  49613. /**
  49614. * Runs onchange callbacks on change (used by the animation engine)
  49615. * @returns This path cursor
  49616. */
  49617. PathCursor.prototype.raiseOnChange = function () {
  49618. var _this = this;
  49619. this._onchange.forEach(function (f) { return f(_this); });
  49620. return this;
  49621. };
  49622. /**
  49623. * Executes a function on change
  49624. * @param f A path cursor onchange callback
  49625. * @returns This path cursor
  49626. */
  49627. PathCursor.prototype.onchange = function (f) {
  49628. this._onchange.push(f);
  49629. return this;
  49630. };
  49631. return PathCursor;
  49632. }());
  49633. BABYLON.PathCursor = PathCursor;
  49634. /**
  49635. * Enum for the animation key frame interpolation type
  49636. */
  49637. var AnimationKeyInterpolation;
  49638. (function (AnimationKeyInterpolation) {
  49639. /**
  49640. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49641. */
  49642. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49643. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49644. /**
  49645. * Class used to store any kind of animation
  49646. */
  49647. var Animation = /** @class */ (function () {
  49648. /**
  49649. * Initializes the animation
  49650. * @param name Name of the animation
  49651. * @param targetProperty Property to animate
  49652. * @param framePerSecond The frames per second of the animation
  49653. * @param dataType The data type of the animation
  49654. * @param loopMode The loop mode of the animation
  49655. * @param enableBlendings Specifies if blending should be enabled
  49656. */
  49657. function Animation(
  49658. /**Name of the animation */
  49659. name,
  49660. /**Property to animate */
  49661. targetProperty,
  49662. /**The frames per second of the animation */
  49663. framePerSecond,
  49664. /**The data type of the animation */
  49665. dataType,
  49666. /**The loop mode of the animation */
  49667. loopMode,
  49668. /**Specifies if blending should be enabled */
  49669. enableBlending) {
  49670. this.name = name;
  49671. this.targetProperty = targetProperty;
  49672. this.framePerSecond = framePerSecond;
  49673. this.dataType = dataType;
  49674. this.loopMode = loopMode;
  49675. this.enableBlending = enableBlending;
  49676. /**
  49677. * @hidden Internal use only
  49678. */
  49679. this._runtimeAnimations = new Array();
  49680. /**
  49681. * The set of event that will be linked to this animation
  49682. */
  49683. this._events = new Array();
  49684. /**
  49685. * Stores the blending speed of the animation
  49686. */
  49687. this.blendingSpeed = 0.01;
  49688. /**
  49689. * Stores the animation ranges for the animation
  49690. */
  49691. this._ranges = {};
  49692. this.targetPropertyPath = targetProperty.split(".");
  49693. this.dataType = dataType;
  49694. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49695. }
  49696. /**
  49697. * @hidden Internal use
  49698. */
  49699. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49700. var dataType = undefined;
  49701. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49702. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49703. }
  49704. else if (from instanceof BABYLON.Quaternion) {
  49705. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49706. }
  49707. else if (from instanceof BABYLON.Vector3) {
  49708. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49709. }
  49710. else if (from instanceof BABYLON.Vector2) {
  49711. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49712. }
  49713. else if (from instanceof BABYLON.Color3) {
  49714. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49715. }
  49716. else if (from instanceof BABYLON.Size) {
  49717. dataType = Animation.ANIMATIONTYPE_SIZE;
  49718. }
  49719. if (dataType == undefined) {
  49720. return null;
  49721. }
  49722. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49723. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49724. animation.setKeys(keys);
  49725. if (easingFunction !== undefined) {
  49726. animation.setEasingFunction(easingFunction);
  49727. }
  49728. return animation;
  49729. };
  49730. /**
  49731. * Sets up an animation
  49732. * @param property The property to animate
  49733. * @param animationType The animation type to apply
  49734. * @param framePerSecond The frames per second of the animation
  49735. * @param easingFunction The easing function used in the animation
  49736. * @returns The created animation
  49737. */
  49738. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49739. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49740. animation.setEasingFunction(easingFunction);
  49741. return animation;
  49742. };
  49743. /**
  49744. * Create and start an animation on a node
  49745. * @param name defines the name of the global animation that will be run on all nodes
  49746. * @param node defines the root node where the animation will take place
  49747. * @param targetProperty defines property to animate
  49748. * @param framePerSecond defines the number of frame per second yo use
  49749. * @param totalFrame defines the number of frames in total
  49750. * @param from defines the initial value
  49751. * @param to defines the final value
  49752. * @param loopMode defines which loop mode you want to use (off by default)
  49753. * @param easingFunction defines the easing function to use (linear by default)
  49754. * @param onAnimationEnd defines the callback to call when animation end
  49755. * @returns the animatable created for this animation
  49756. */
  49757. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49758. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49759. if (!animation) {
  49760. return null;
  49761. }
  49762. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49763. };
  49764. /**
  49765. * Create and start an animation on a node and its descendants
  49766. * @param name defines the name of the global animation that will be run on all nodes
  49767. * @param node defines the root node where the animation will take place
  49768. * @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
  49769. * @param targetProperty defines property to animate
  49770. * @param framePerSecond defines the number of frame per second to use
  49771. * @param totalFrame defines the number of frames in total
  49772. * @param from defines the initial value
  49773. * @param to defines the final value
  49774. * @param loopMode defines which loop mode you want to use (off by default)
  49775. * @param easingFunction defines the easing function to use (linear by default)
  49776. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49777. * @returns the list of animatables created for all nodes
  49778. * @example https://www.babylonjs-playground.com/#MH0VLI
  49779. */
  49780. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49781. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49782. if (!animation) {
  49783. return null;
  49784. }
  49785. var scene = node.getScene();
  49786. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49787. };
  49788. /**
  49789. * Creates a new animation, merges it with the existing animations and starts it
  49790. * @param name Name of the animation
  49791. * @param node Node which contains the scene that begins the animations
  49792. * @param targetProperty Specifies which property to animate
  49793. * @param framePerSecond The frames per second of the animation
  49794. * @param totalFrame The total number of frames
  49795. * @param from The frame at the beginning of the animation
  49796. * @param to The frame at the end of the animation
  49797. * @param loopMode Specifies the loop mode of the animation
  49798. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49799. * @param onAnimationEnd Callback to run once the animation is complete
  49800. * @returns Nullable animation
  49801. */
  49802. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49803. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49804. if (!animation) {
  49805. return null;
  49806. }
  49807. node.animations.push(animation);
  49808. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49809. };
  49810. /**
  49811. * Transition property of an host to the target Value
  49812. * @param property The property to transition
  49813. * @param targetValue The target Value of the property
  49814. * @param host The object where the property to animate belongs
  49815. * @param scene Scene used to run the animation
  49816. * @param frameRate Framerate (in frame/s) to use
  49817. * @param transition The transition type we want to use
  49818. * @param duration The duration of the animation, in milliseconds
  49819. * @param onAnimationEnd Callback trigger at the end of the animation
  49820. * @returns Nullable animation
  49821. */
  49822. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49823. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49824. if (duration <= 0) {
  49825. host[property] = targetValue;
  49826. if (onAnimationEnd) {
  49827. onAnimationEnd();
  49828. }
  49829. return null;
  49830. }
  49831. var endFrame = frameRate * (duration / 1000);
  49832. transition.setKeys([{
  49833. frame: 0,
  49834. value: host[property].clone ? host[property].clone() : host[property]
  49835. },
  49836. {
  49837. frame: endFrame,
  49838. value: targetValue
  49839. }]);
  49840. if (!host.animations) {
  49841. host.animations = [];
  49842. }
  49843. host.animations.push(transition);
  49844. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49845. animation.onAnimationEnd = onAnimationEnd;
  49846. return animation;
  49847. };
  49848. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49849. /**
  49850. * Return the array of runtime animations currently using this animation
  49851. */
  49852. get: function () {
  49853. return this._runtimeAnimations;
  49854. },
  49855. enumerable: true,
  49856. configurable: true
  49857. });
  49858. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49859. /**
  49860. * Specifies if any of the runtime animations are currently running
  49861. */
  49862. get: function () {
  49863. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49864. var runtimeAnimation = _a[_i];
  49865. if (!runtimeAnimation.isStopped) {
  49866. return true;
  49867. }
  49868. }
  49869. return false;
  49870. },
  49871. enumerable: true,
  49872. configurable: true
  49873. });
  49874. // Methods
  49875. /**
  49876. * Converts the animation to a string
  49877. * @param fullDetails support for multiple levels of logging within scene loading
  49878. * @returns String form of the animation
  49879. */
  49880. Animation.prototype.toString = function (fullDetails) {
  49881. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49882. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49883. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49884. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49885. if (fullDetails) {
  49886. ret += ", Ranges: {";
  49887. var first = true;
  49888. for (var name in this._ranges) {
  49889. if (first) {
  49890. ret += ", ";
  49891. first = false;
  49892. }
  49893. ret += name;
  49894. }
  49895. ret += "}";
  49896. }
  49897. return ret;
  49898. };
  49899. /**
  49900. * Add an event to this animation
  49901. * @param event Event to add
  49902. */
  49903. Animation.prototype.addEvent = function (event) {
  49904. this._events.push(event);
  49905. };
  49906. /**
  49907. * Remove all events found at the given frame
  49908. * @param frame The frame to remove events from
  49909. */
  49910. Animation.prototype.removeEvents = function (frame) {
  49911. for (var index = 0; index < this._events.length; index++) {
  49912. if (this._events[index].frame === frame) {
  49913. this._events.splice(index, 1);
  49914. index--;
  49915. }
  49916. }
  49917. };
  49918. /**
  49919. * Retrieves all the events from the animation
  49920. * @returns Events from the animation
  49921. */
  49922. Animation.prototype.getEvents = function () {
  49923. return this._events;
  49924. };
  49925. /**
  49926. * Creates an animation range
  49927. * @param name Name of the animation range
  49928. * @param from Starting frame of the animation range
  49929. * @param to Ending frame of the animation
  49930. */
  49931. Animation.prototype.createRange = function (name, from, to) {
  49932. // check name not already in use; could happen for bones after serialized
  49933. if (!this._ranges[name]) {
  49934. this._ranges[name] = new AnimationRange(name, from, to);
  49935. }
  49936. };
  49937. /**
  49938. * Deletes an animation range by name
  49939. * @param name Name of the animation range to delete
  49940. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49941. */
  49942. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49943. if (deleteFrames === void 0) { deleteFrames = true; }
  49944. var range = this._ranges[name];
  49945. if (!range) {
  49946. return;
  49947. }
  49948. if (deleteFrames) {
  49949. var from = range.from;
  49950. var to = range.to;
  49951. // this loop MUST go high to low for multiple splices to work
  49952. for (var key = this._keys.length - 1; key >= 0; key--) {
  49953. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49954. this._keys.splice(key, 1);
  49955. }
  49956. }
  49957. }
  49958. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49959. };
  49960. /**
  49961. * Gets the animation range by name, or null if not defined
  49962. * @param name Name of the animation range
  49963. * @returns Nullable animation range
  49964. */
  49965. Animation.prototype.getRange = function (name) {
  49966. return this._ranges[name];
  49967. };
  49968. /**
  49969. * Gets the key frames from the animation
  49970. * @returns The key frames of the animation
  49971. */
  49972. Animation.prototype.getKeys = function () {
  49973. return this._keys;
  49974. };
  49975. /**
  49976. * Gets the highest frame rate of the animation
  49977. * @returns Highest frame rate of the animation
  49978. */
  49979. Animation.prototype.getHighestFrame = function () {
  49980. var ret = 0;
  49981. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49982. if (ret < this._keys[key].frame) {
  49983. ret = this._keys[key].frame;
  49984. }
  49985. }
  49986. return ret;
  49987. };
  49988. /**
  49989. * Gets the easing function of the animation
  49990. * @returns Easing function of the animation
  49991. */
  49992. Animation.prototype.getEasingFunction = function () {
  49993. return this._easingFunction;
  49994. };
  49995. /**
  49996. * Sets the easing function of the animation
  49997. * @param easingFunction A custom mathematical formula for animation
  49998. */
  49999. Animation.prototype.setEasingFunction = function (easingFunction) {
  50000. this._easingFunction = easingFunction;
  50001. };
  50002. /**
  50003. * Interpolates a scalar linearly
  50004. * @param startValue Start value of the animation curve
  50005. * @param endValue End value of the animation curve
  50006. * @param gradient Scalar amount to interpolate
  50007. * @returns Interpolated scalar value
  50008. */
  50009. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50010. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50011. };
  50012. /**
  50013. * Interpolates a scalar cubically
  50014. * @param startValue Start value of the animation curve
  50015. * @param outTangent End tangent of the animation
  50016. * @param endValue End value of the animation curve
  50017. * @param inTangent Start tangent of the animation curve
  50018. * @param gradient Scalar amount to interpolate
  50019. * @returns Interpolated scalar value
  50020. */
  50021. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50022. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50023. };
  50024. /**
  50025. * Interpolates a quaternion using a spherical linear interpolation
  50026. * @param startValue Start value of the animation curve
  50027. * @param endValue End value of the animation curve
  50028. * @param gradient Scalar amount to interpolate
  50029. * @returns Interpolated quaternion value
  50030. */
  50031. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50032. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50033. };
  50034. /**
  50035. * Interpolates a quaternion cubically
  50036. * @param startValue Start value of the animation curve
  50037. * @param outTangent End tangent of the animation curve
  50038. * @param endValue End value of the animation curve
  50039. * @param inTangent Start tangent of the animation curve
  50040. * @param gradient Scalar amount to interpolate
  50041. * @returns Interpolated quaternion value
  50042. */
  50043. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50044. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50045. };
  50046. /**
  50047. * Interpolates a Vector3 linearl
  50048. * @param startValue Start value of the animation curve
  50049. * @param endValue End value of the animation curve
  50050. * @param gradient Scalar amount to interpolate
  50051. * @returns Interpolated scalar value
  50052. */
  50053. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50054. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50055. };
  50056. /**
  50057. * Interpolates a Vector3 cubically
  50058. * @param startValue Start value of the animation curve
  50059. * @param outTangent End tangent of the animation
  50060. * @param endValue End value of the animation curve
  50061. * @param inTangent Start tangent of the animation curve
  50062. * @param gradient Scalar amount to interpolate
  50063. * @returns InterpolatedVector3 value
  50064. */
  50065. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50066. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50067. };
  50068. /**
  50069. * Interpolates a Vector2 linearly
  50070. * @param startValue Start value of the animation curve
  50071. * @param endValue End value of the animation curve
  50072. * @param gradient Scalar amount to interpolate
  50073. * @returns Interpolated Vector2 value
  50074. */
  50075. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50076. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50077. };
  50078. /**
  50079. * Interpolates a Vector2 cubically
  50080. * @param startValue Start value of the animation curve
  50081. * @param outTangent End tangent of the animation
  50082. * @param endValue End value of the animation curve
  50083. * @param inTangent Start tangent of the animation curve
  50084. * @param gradient Scalar amount to interpolate
  50085. * @returns Interpolated Vector2 value
  50086. */
  50087. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50088. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50089. };
  50090. /**
  50091. * Interpolates a size linearly
  50092. * @param startValue Start value of the animation curve
  50093. * @param endValue End value of the animation curve
  50094. * @param gradient Scalar amount to interpolate
  50095. * @returns Interpolated Size value
  50096. */
  50097. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50098. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50099. };
  50100. /**
  50101. * Interpolates a Color3 linearly
  50102. * @param startValue Start value of the animation curve
  50103. * @param endValue End value of the animation curve
  50104. * @param gradient Scalar amount to interpolate
  50105. * @returns Interpolated Color3 value
  50106. */
  50107. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50108. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50109. };
  50110. /**
  50111. * @hidden Internal use only
  50112. */
  50113. Animation.prototype._getKeyValue = function (value) {
  50114. if (typeof value === "function") {
  50115. return value();
  50116. }
  50117. return value;
  50118. };
  50119. /**
  50120. * @hidden Internal use only
  50121. */
  50122. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50123. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50124. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50125. }
  50126. var keys = this.getKeys();
  50127. // Try to get a hash to find the right key
  50128. 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));
  50129. if (keys[startKeyIndex].frame >= currentFrame) {
  50130. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50131. startKeyIndex--;
  50132. }
  50133. }
  50134. for (var key = startKeyIndex; key < keys.length; key++) {
  50135. var endKey = keys[key + 1];
  50136. if (endKey.frame >= currentFrame) {
  50137. var startKey = keys[key];
  50138. var startValue = this._getKeyValue(startKey.value);
  50139. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50140. return startValue;
  50141. }
  50142. var endValue = this._getKeyValue(endKey.value);
  50143. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50144. var frameDelta = endKey.frame - startKey.frame;
  50145. // gradient : percent of currentFrame between the frame inf and the frame sup
  50146. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50147. // check for easingFunction and correction of gradient
  50148. var easingFunction = this.getEasingFunction();
  50149. if (easingFunction != null) {
  50150. gradient = easingFunction.ease(gradient);
  50151. }
  50152. switch (this.dataType) {
  50153. // Float
  50154. case Animation.ANIMATIONTYPE_FLOAT:
  50155. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50156. switch (loopMode) {
  50157. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50158. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50159. return floatValue;
  50160. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50161. return offsetValue * repeatCount + floatValue;
  50162. }
  50163. break;
  50164. // Quaternion
  50165. case Animation.ANIMATIONTYPE_QUATERNION:
  50166. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50167. switch (loopMode) {
  50168. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50169. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50170. return quatValue;
  50171. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50172. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50173. }
  50174. return quatValue;
  50175. // Vector3
  50176. case Animation.ANIMATIONTYPE_VECTOR3:
  50177. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50178. switch (loopMode) {
  50179. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50180. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50181. return vec3Value;
  50182. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50183. return vec3Value.add(offsetValue.scale(repeatCount));
  50184. }
  50185. // Vector2
  50186. case Animation.ANIMATIONTYPE_VECTOR2:
  50187. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50188. switch (loopMode) {
  50189. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50190. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50191. return vec2Value;
  50192. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50193. return vec2Value.add(offsetValue.scale(repeatCount));
  50194. }
  50195. // Size
  50196. case Animation.ANIMATIONTYPE_SIZE:
  50197. switch (loopMode) {
  50198. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50199. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50200. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50201. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50202. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50203. }
  50204. // Color3
  50205. case Animation.ANIMATIONTYPE_COLOR3:
  50206. switch (loopMode) {
  50207. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50208. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50209. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50210. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50211. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50212. }
  50213. // Matrix
  50214. case Animation.ANIMATIONTYPE_MATRIX:
  50215. switch (loopMode) {
  50216. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50217. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50218. if (Animation.AllowMatricesInterpolation) {
  50219. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50220. }
  50221. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50222. return startValue;
  50223. }
  50224. default:
  50225. break;
  50226. }
  50227. break;
  50228. }
  50229. }
  50230. return this._getKeyValue(keys[keys.length - 1].value);
  50231. };
  50232. /**
  50233. * Defines the function to use to interpolate matrices
  50234. * @param startValue defines the start matrix
  50235. * @param endValue defines the end matrix
  50236. * @param gradient defines the gradient between both matrices
  50237. * @param result defines an optional target matrix where to store the interpolation
  50238. * @returns the interpolated matrix
  50239. */
  50240. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50241. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50242. if (result) {
  50243. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50244. return result;
  50245. }
  50246. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50247. }
  50248. if (result) {
  50249. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50250. return result;
  50251. }
  50252. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50253. };
  50254. /**
  50255. * Makes a copy of the animation
  50256. * @returns Cloned animation
  50257. */
  50258. Animation.prototype.clone = function () {
  50259. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50260. clone.enableBlending = this.enableBlending;
  50261. clone.blendingSpeed = this.blendingSpeed;
  50262. if (this._keys) {
  50263. clone.setKeys(this._keys);
  50264. }
  50265. if (this._ranges) {
  50266. clone._ranges = {};
  50267. for (var name in this._ranges) {
  50268. var range = this._ranges[name];
  50269. if (!range) {
  50270. continue;
  50271. }
  50272. clone._ranges[name] = range.clone();
  50273. }
  50274. }
  50275. return clone;
  50276. };
  50277. /**
  50278. * Sets the key frames of the animation
  50279. * @param values The animation key frames to set
  50280. */
  50281. Animation.prototype.setKeys = function (values) {
  50282. this._keys = values.slice(0);
  50283. };
  50284. /**
  50285. * Serializes the animation to an object
  50286. * @returns Serialized object
  50287. */
  50288. Animation.prototype.serialize = function () {
  50289. var serializationObject = {};
  50290. serializationObject.name = this.name;
  50291. serializationObject.property = this.targetProperty;
  50292. serializationObject.framePerSecond = this.framePerSecond;
  50293. serializationObject.dataType = this.dataType;
  50294. serializationObject.loopBehavior = this.loopMode;
  50295. serializationObject.enableBlending = this.enableBlending;
  50296. serializationObject.blendingSpeed = this.blendingSpeed;
  50297. var dataType = this.dataType;
  50298. serializationObject.keys = [];
  50299. var keys = this.getKeys();
  50300. for (var index = 0; index < keys.length; index++) {
  50301. var animationKey = keys[index];
  50302. var key = {};
  50303. key.frame = animationKey.frame;
  50304. switch (dataType) {
  50305. case Animation.ANIMATIONTYPE_FLOAT:
  50306. key.values = [animationKey.value];
  50307. break;
  50308. case Animation.ANIMATIONTYPE_QUATERNION:
  50309. case Animation.ANIMATIONTYPE_MATRIX:
  50310. case Animation.ANIMATIONTYPE_VECTOR3:
  50311. case Animation.ANIMATIONTYPE_COLOR3:
  50312. key.values = animationKey.value.asArray();
  50313. break;
  50314. }
  50315. serializationObject.keys.push(key);
  50316. }
  50317. serializationObject.ranges = [];
  50318. for (var name in this._ranges) {
  50319. var source = this._ranges[name];
  50320. if (!source) {
  50321. continue;
  50322. }
  50323. var range = {};
  50324. range.name = name;
  50325. range.from = source.from;
  50326. range.to = source.to;
  50327. serializationObject.ranges.push(range);
  50328. }
  50329. return serializationObject;
  50330. };
  50331. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50332. /**
  50333. * Get the float animation type
  50334. */
  50335. get: function () {
  50336. return Animation._ANIMATIONTYPE_FLOAT;
  50337. },
  50338. enumerable: true,
  50339. configurable: true
  50340. });
  50341. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50342. /**
  50343. * Get the Vector3 animation type
  50344. */
  50345. get: function () {
  50346. return Animation._ANIMATIONTYPE_VECTOR3;
  50347. },
  50348. enumerable: true,
  50349. configurable: true
  50350. });
  50351. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50352. /**
  50353. * Get the Vector2 animation type
  50354. */
  50355. get: function () {
  50356. return Animation._ANIMATIONTYPE_VECTOR2;
  50357. },
  50358. enumerable: true,
  50359. configurable: true
  50360. });
  50361. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50362. /**
  50363. * Get the Size animation type
  50364. */
  50365. get: function () {
  50366. return Animation._ANIMATIONTYPE_SIZE;
  50367. },
  50368. enumerable: true,
  50369. configurable: true
  50370. });
  50371. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50372. /**
  50373. * Get the Quaternion animation type
  50374. */
  50375. get: function () {
  50376. return Animation._ANIMATIONTYPE_QUATERNION;
  50377. },
  50378. enumerable: true,
  50379. configurable: true
  50380. });
  50381. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50382. /**
  50383. * Get the Matrix animation type
  50384. */
  50385. get: function () {
  50386. return Animation._ANIMATIONTYPE_MATRIX;
  50387. },
  50388. enumerable: true,
  50389. configurable: true
  50390. });
  50391. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50392. /**
  50393. * Get the Color3 animation type
  50394. */
  50395. get: function () {
  50396. return Animation._ANIMATIONTYPE_COLOR3;
  50397. },
  50398. enumerable: true,
  50399. configurable: true
  50400. });
  50401. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50402. /**
  50403. * Get the Relative Loop Mode
  50404. */
  50405. get: function () {
  50406. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50407. },
  50408. enumerable: true,
  50409. configurable: true
  50410. });
  50411. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50412. /**
  50413. * Get the Cycle Loop Mode
  50414. */
  50415. get: function () {
  50416. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50417. },
  50418. enumerable: true,
  50419. configurable: true
  50420. });
  50421. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50422. /**
  50423. * Get the Constant Loop Mode
  50424. */
  50425. get: function () {
  50426. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50427. },
  50428. enumerable: true,
  50429. configurable: true
  50430. });
  50431. /** @hidden */
  50432. Animation._UniversalLerp = function (left, right, amount) {
  50433. var constructor = left.constructor;
  50434. if (constructor.Lerp) { // Lerp supported
  50435. return constructor.Lerp(left, right, amount);
  50436. }
  50437. else if (constructor.Slerp) { // Slerp supported
  50438. return constructor.Slerp(left, right, amount);
  50439. }
  50440. else if (left.toFixed) { // Number
  50441. return left * (1.0 - amount) + amount * right;
  50442. }
  50443. else { // Blending not supported
  50444. return right;
  50445. }
  50446. };
  50447. /**
  50448. * Parses an animation object and creates an animation
  50449. * @param parsedAnimation Parsed animation object
  50450. * @returns Animation object
  50451. */
  50452. Animation.Parse = function (parsedAnimation) {
  50453. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50454. var dataType = parsedAnimation.dataType;
  50455. var keys = [];
  50456. var data;
  50457. var index;
  50458. if (parsedAnimation.enableBlending) {
  50459. animation.enableBlending = parsedAnimation.enableBlending;
  50460. }
  50461. if (parsedAnimation.blendingSpeed) {
  50462. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50463. }
  50464. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50465. var key = parsedAnimation.keys[index];
  50466. var inTangent;
  50467. var outTangent;
  50468. switch (dataType) {
  50469. case Animation.ANIMATIONTYPE_FLOAT:
  50470. data = key.values[0];
  50471. if (key.values.length >= 1) {
  50472. inTangent = key.values[1];
  50473. }
  50474. if (key.values.length >= 2) {
  50475. outTangent = key.values[2];
  50476. }
  50477. break;
  50478. case Animation.ANIMATIONTYPE_QUATERNION:
  50479. data = BABYLON.Quaternion.FromArray(key.values);
  50480. if (key.values.length >= 8) {
  50481. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50482. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50483. inTangent = _inTangent;
  50484. }
  50485. }
  50486. if (key.values.length >= 12) {
  50487. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50488. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50489. outTangent = _outTangent;
  50490. }
  50491. }
  50492. break;
  50493. case Animation.ANIMATIONTYPE_MATRIX:
  50494. data = BABYLON.Matrix.FromArray(key.values);
  50495. break;
  50496. case Animation.ANIMATIONTYPE_COLOR3:
  50497. data = BABYLON.Color3.FromArray(key.values);
  50498. break;
  50499. case Animation.ANIMATIONTYPE_VECTOR3:
  50500. default:
  50501. data = BABYLON.Vector3.FromArray(key.values);
  50502. break;
  50503. }
  50504. var keyData = {};
  50505. keyData.frame = key.frame;
  50506. keyData.value = data;
  50507. if (inTangent != undefined) {
  50508. keyData.inTangent = inTangent;
  50509. }
  50510. if (outTangent != undefined) {
  50511. keyData.outTangent = outTangent;
  50512. }
  50513. keys.push(keyData);
  50514. }
  50515. animation.setKeys(keys);
  50516. if (parsedAnimation.ranges) {
  50517. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50518. data = parsedAnimation.ranges[index];
  50519. animation.createRange(data.name, data.from, data.to);
  50520. }
  50521. }
  50522. return animation;
  50523. };
  50524. /**
  50525. * Appends the serialized animations from the source animations
  50526. * @param source Source containing the animations
  50527. * @param destination Target to store the animations
  50528. */
  50529. Animation.AppendSerializedAnimations = function (source, destination) {
  50530. if (source.animations) {
  50531. destination.animations = [];
  50532. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50533. var animation = source.animations[animationIndex];
  50534. destination.animations.push(animation.serialize());
  50535. }
  50536. }
  50537. };
  50538. /**
  50539. * Use matrix interpolation instead of using direct key value when animating matrices
  50540. */
  50541. Animation.AllowMatricesInterpolation = false;
  50542. /**
  50543. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50544. */
  50545. Animation.AllowMatrixDecomposeForInterpolation = true;
  50546. // Statics
  50547. /**
  50548. * Float animation type
  50549. */
  50550. Animation._ANIMATIONTYPE_FLOAT = 0;
  50551. /**
  50552. * Vector3 animation type
  50553. */
  50554. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50555. /**
  50556. * Quaternion animation type
  50557. */
  50558. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50559. /**
  50560. * Matrix animation type
  50561. */
  50562. Animation._ANIMATIONTYPE_MATRIX = 3;
  50563. /**
  50564. * Color3 animation type
  50565. */
  50566. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50567. /**
  50568. * Vector2 animation type
  50569. */
  50570. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50571. /**
  50572. * Size animation type
  50573. */
  50574. Animation._ANIMATIONTYPE_SIZE = 6;
  50575. /**
  50576. * Relative Loop Mode
  50577. */
  50578. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50579. /**
  50580. * Cycle Loop Mode
  50581. */
  50582. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50583. /**
  50584. * Constant Loop Mode
  50585. */
  50586. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50587. return Animation;
  50588. }());
  50589. BABYLON.Animation = Animation;
  50590. })(BABYLON || (BABYLON = {}));
  50591. //# sourceMappingURL=babylon.animation.js.map
  50592. var BABYLON;
  50593. (function (BABYLON) {
  50594. /**
  50595. * This class defines the direct association between an animation and a target
  50596. */
  50597. var TargetedAnimation = /** @class */ (function () {
  50598. function TargetedAnimation() {
  50599. }
  50600. return TargetedAnimation;
  50601. }());
  50602. BABYLON.TargetedAnimation = TargetedAnimation;
  50603. /**
  50604. * Use this class to create coordinated animations on multiple targets
  50605. */
  50606. var AnimationGroup = /** @class */ (function () {
  50607. /**
  50608. * Instantiates a new Animation Group.
  50609. * This helps managing several animations at once.
  50610. * @see http://doc.babylonjs.com/how_to/group
  50611. * @param name Defines the name of the group
  50612. * @param scene Defines the scene the group belongs to
  50613. */
  50614. function AnimationGroup(
  50615. /** The name of the animation group */
  50616. name, scene) {
  50617. if (scene === void 0) { scene = null; }
  50618. this.name = name;
  50619. this._targetedAnimations = new Array();
  50620. this._animatables = new Array();
  50621. this._from = Number.MAX_VALUE;
  50622. this._to = -Number.MAX_VALUE;
  50623. this._speedRatio = 1;
  50624. /**
  50625. * This observable will notify when one animation have ended.
  50626. */
  50627. this.onAnimationEndObservable = new BABYLON.Observable();
  50628. /**
  50629. * This observable will notify when all animations have ended.
  50630. */
  50631. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50632. /**
  50633. * This observable will notify when all animations have paused.
  50634. */
  50635. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50636. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50637. this._scene.animationGroups.push(this);
  50638. }
  50639. Object.defineProperty(AnimationGroup.prototype, "from", {
  50640. /**
  50641. * Gets the first frame
  50642. */
  50643. get: function () {
  50644. return this._from;
  50645. },
  50646. enumerable: true,
  50647. configurable: true
  50648. });
  50649. Object.defineProperty(AnimationGroup.prototype, "to", {
  50650. /**
  50651. * Gets the last frame
  50652. */
  50653. get: function () {
  50654. return this._to;
  50655. },
  50656. enumerable: true,
  50657. configurable: true
  50658. });
  50659. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50660. /**
  50661. * Define if the animations are started
  50662. */
  50663. get: function () {
  50664. return this._isStarted;
  50665. },
  50666. enumerable: true,
  50667. configurable: true
  50668. });
  50669. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50670. /**
  50671. * Gets or sets the speed ratio to use for all animations
  50672. */
  50673. get: function () {
  50674. return this._speedRatio;
  50675. },
  50676. /**
  50677. * Gets or sets the speed ratio to use for all animations
  50678. */
  50679. set: function (value) {
  50680. if (this._speedRatio === value) {
  50681. return;
  50682. }
  50683. this._speedRatio = value;
  50684. for (var index = 0; index < this._animatables.length; index++) {
  50685. var animatable = this._animatables[index];
  50686. animatable.speedRatio = this._speedRatio;
  50687. }
  50688. },
  50689. enumerable: true,
  50690. configurable: true
  50691. });
  50692. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50693. /**
  50694. * Gets the targeted animations for this animation group
  50695. */
  50696. get: function () {
  50697. return this._targetedAnimations;
  50698. },
  50699. enumerable: true,
  50700. configurable: true
  50701. });
  50702. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50703. /**
  50704. * returning the list of animatables controlled by this animation group.
  50705. */
  50706. get: function () {
  50707. return this._animatables;
  50708. },
  50709. enumerable: true,
  50710. configurable: true
  50711. });
  50712. /**
  50713. * Add an animation (with its target) in the group
  50714. * @param animation defines the animation we want to add
  50715. * @param target defines the target of the animation
  50716. * @returns the {BABYLON.TargetedAnimation} object
  50717. */
  50718. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50719. var targetedAnimation = {
  50720. animation: animation,
  50721. target: target
  50722. };
  50723. var keys = animation.getKeys();
  50724. if (this._from > keys[0].frame) {
  50725. this._from = keys[0].frame;
  50726. }
  50727. if (this._to < keys[keys.length - 1].frame) {
  50728. this._to = keys[keys.length - 1].frame;
  50729. }
  50730. this._targetedAnimations.push(targetedAnimation);
  50731. return targetedAnimation;
  50732. };
  50733. /**
  50734. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50735. * It can add constant keys at begin or end
  50736. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50737. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50738. * @returns the animation group
  50739. */
  50740. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50741. if (beginFrame === void 0) { beginFrame = null; }
  50742. if (endFrame === void 0) { endFrame = null; }
  50743. if (beginFrame == null)
  50744. beginFrame = this._from;
  50745. if (endFrame == null)
  50746. endFrame = this._to;
  50747. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50748. var targetedAnimation = this._targetedAnimations[index];
  50749. var keys = targetedAnimation.animation.getKeys();
  50750. var startKey = keys[0];
  50751. var endKey = keys[keys.length - 1];
  50752. if (startKey.frame > beginFrame) {
  50753. var newKey = {
  50754. frame: beginFrame,
  50755. value: startKey.value,
  50756. inTangent: startKey.inTangent,
  50757. outTangent: startKey.outTangent,
  50758. interpolation: startKey.interpolation
  50759. };
  50760. keys.splice(0, 0, newKey);
  50761. }
  50762. if (endKey.frame < endFrame) {
  50763. var newKey = {
  50764. frame: endFrame,
  50765. value: endKey.value,
  50766. inTangent: endKey.outTangent,
  50767. outTangent: endKey.outTangent,
  50768. interpolation: endKey.interpolation
  50769. };
  50770. keys.push(newKey);
  50771. }
  50772. }
  50773. this._from = beginFrame;
  50774. this._to = endFrame;
  50775. return this;
  50776. };
  50777. /**
  50778. * Start all animations on given targets
  50779. * @param loop defines if animations must loop
  50780. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50781. * @param from defines the from key (optional)
  50782. * @param to defines the to key (optional)
  50783. * @returns the current animation group
  50784. */
  50785. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50786. var _this = this;
  50787. if (loop === void 0) { loop = false; }
  50788. if (speedRatio === void 0) { speedRatio = 1; }
  50789. if (this._isStarted || this._targetedAnimations.length === 0) {
  50790. return this;
  50791. }
  50792. var _loop_1 = function (targetedAnimation) {
  50793. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50794. animatable.onAnimationEnd = function () {
  50795. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50796. _this._checkAnimationGroupEnded(animatable);
  50797. };
  50798. this_1._animatables.push(animatable);
  50799. };
  50800. var this_1 = this;
  50801. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50802. var targetedAnimation = _a[_i];
  50803. _loop_1(targetedAnimation);
  50804. }
  50805. this._speedRatio = speedRatio;
  50806. this._isStarted = true;
  50807. return this;
  50808. };
  50809. /**
  50810. * Pause all animations
  50811. * @returns the animation group
  50812. */
  50813. AnimationGroup.prototype.pause = function () {
  50814. if (!this._isStarted) {
  50815. return this;
  50816. }
  50817. for (var index = 0; index < this._animatables.length; index++) {
  50818. var animatable = this._animatables[index];
  50819. animatable.pause();
  50820. }
  50821. this.onAnimationGroupPauseObservable.notifyObservers(this);
  50822. return this;
  50823. };
  50824. /**
  50825. * Play all animations to initial state
  50826. * This function will start() the animations if they were not started or will restart() them if they were paused
  50827. * @param loop defines if animations must loop
  50828. * @returns the animation group
  50829. */
  50830. AnimationGroup.prototype.play = function (loop) {
  50831. // only if all animatables are ready and exist
  50832. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50833. if (loop !== undefined) {
  50834. for (var index = 0; index < this._animatables.length; index++) {
  50835. var animatable = this._animatables[index];
  50836. animatable.loopAnimation = loop;
  50837. }
  50838. }
  50839. this.restart();
  50840. }
  50841. else {
  50842. this.stop();
  50843. this.start(loop, this._speedRatio);
  50844. }
  50845. return this;
  50846. };
  50847. /**
  50848. * Reset all animations to initial state
  50849. * @returns the animation group
  50850. */
  50851. AnimationGroup.prototype.reset = function () {
  50852. if (!this._isStarted) {
  50853. return this;
  50854. }
  50855. for (var index = 0; index < this._animatables.length; index++) {
  50856. var animatable = this._animatables[index];
  50857. animatable.reset();
  50858. }
  50859. return this;
  50860. };
  50861. /**
  50862. * Restart animations from key 0
  50863. * @returns the animation group
  50864. */
  50865. AnimationGroup.prototype.restart = function () {
  50866. if (!this._isStarted) {
  50867. return this;
  50868. }
  50869. for (var index = 0; index < this._animatables.length; index++) {
  50870. var animatable = this._animatables[index];
  50871. animatable.restart();
  50872. }
  50873. return this;
  50874. };
  50875. /**
  50876. * Stop all animations
  50877. * @returns the animation group
  50878. */
  50879. AnimationGroup.prototype.stop = function () {
  50880. if (!this._isStarted) {
  50881. return this;
  50882. }
  50883. var list = this._animatables.slice();
  50884. for (var index = 0; index < list.length; index++) {
  50885. list[index].stop();
  50886. }
  50887. this._isStarted = false;
  50888. return this;
  50889. };
  50890. /**
  50891. * Set animation weight for all animatables
  50892. * @param weight defines the weight to use
  50893. * @return the animationGroup
  50894. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50895. */
  50896. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50897. for (var index = 0; index < this._animatables.length; index++) {
  50898. var animatable = this._animatables[index];
  50899. animatable.weight = weight;
  50900. }
  50901. return this;
  50902. };
  50903. /**
  50904. * Synchronize and normalize all animatables with a source animatable
  50905. * @param root defines the root animatable to synchronize with
  50906. * @return the animationGroup
  50907. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50908. */
  50909. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50910. for (var index = 0; index < this._animatables.length; index++) {
  50911. var animatable = this._animatables[index];
  50912. animatable.syncWith(root);
  50913. }
  50914. return this;
  50915. };
  50916. /**
  50917. * Goes to a specific frame in this animation group
  50918. * @param frame the frame number to go to
  50919. * @return the animationGroup
  50920. */
  50921. AnimationGroup.prototype.goToFrame = function (frame) {
  50922. if (!this._isStarted) {
  50923. return this;
  50924. }
  50925. for (var index = 0; index < this._animatables.length; index++) {
  50926. var animatable = this._animatables[index];
  50927. animatable.goToFrame(frame);
  50928. }
  50929. return this;
  50930. };
  50931. /**
  50932. * Dispose all associated resources
  50933. */
  50934. AnimationGroup.prototype.dispose = function () {
  50935. this._targetedAnimations = [];
  50936. this._animatables = [];
  50937. var index = this._scene.animationGroups.indexOf(this);
  50938. if (index > -1) {
  50939. this._scene.animationGroups.splice(index, 1);
  50940. }
  50941. };
  50942. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50943. // animatable should be taken out of the array
  50944. var idx = this._animatables.indexOf(animatable);
  50945. if (idx > -1) {
  50946. this._animatables.splice(idx, 1);
  50947. }
  50948. // all animatables were removed? animation group ended!
  50949. if (this._animatables.length === 0) {
  50950. this._isStarted = false;
  50951. this.onAnimationGroupEndObservable.notifyObservers(this);
  50952. }
  50953. };
  50954. // Statics
  50955. /**
  50956. * Returns a new AnimationGroup object parsed from the source provided.
  50957. * @param parsedAnimationGroup defines the source
  50958. * @param scene defines the scene that will receive the animationGroup
  50959. * @returns a new AnimationGroup
  50960. */
  50961. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  50962. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  50963. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  50964. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  50965. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  50966. var id = targetedAnimation.targetId;
  50967. var targetNode = scene.getNodeByID(id);
  50968. if (targetNode != null)
  50969. animationGroup.addTargetedAnimation(animation, targetNode);
  50970. }
  50971. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  50972. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  50973. return animationGroup;
  50974. };
  50975. /**
  50976. * Returns the string "AnimationGroup"
  50977. * @returns "AnimationGroup"
  50978. */
  50979. AnimationGroup.prototype.getClassName = function () {
  50980. return "AnimationGroup";
  50981. };
  50982. /**
  50983. * Creates a detailled string about the object
  50984. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  50985. * @returns a string representing the object
  50986. */
  50987. AnimationGroup.prototype.toString = function (fullDetails) {
  50988. var ret = "Name: " + this.name;
  50989. ret += ", type: " + this.getClassName();
  50990. if (fullDetails) {
  50991. ret += ", from: " + this._from;
  50992. ret += ", to: " + this._to;
  50993. ret += ", isStarted: " + this._isStarted;
  50994. ret += ", speedRatio: " + this._speedRatio;
  50995. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  50996. ret += ", animatables length: " + this._animatables;
  50997. }
  50998. return ret;
  50999. };
  51000. return AnimationGroup;
  51001. }());
  51002. BABYLON.AnimationGroup = AnimationGroup;
  51003. })(BABYLON || (BABYLON = {}));
  51004. //# sourceMappingURL=babylon.animationGroup.js.map
  51005. var BABYLON;
  51006. (function (BABYLON) {
  51007. // Static values to help the garbage collector
  51008. // Quaternion
  51009. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51010. // Vector3
  51011. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51012. // Vector2
  51013. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51014. // Size
  51015. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51016. // Color3
  51017. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51018. /**
  51019. * Defines a runtime animation
  51020. */
  51021. var RuntimeAnimation = /** @class */ (function () {
  51022. /**
  51023. * Create a new RuntimeAnimation object
  51024. * @param target defines the target of the animation
  51025. * @param animation defines the source animation object
  51026. * @param scene defines the hosting scene
  51027. * @param host defines the initiating Animatable
  51028. */
  51029. function RuntimeAnimation(target, animation, scene, host) {
  51030. var _this = this;
  51031. this._events = new Array();
  51032. /**
  51033. * The current frame of the runtime animation
  51034. */
  51035. this._currentFrame = 0;
  51036. /**
  51037. * The original value of the runtime animation
  51038. */
  51039. this._originalValue = new Array();
  51040. /**
  51041. * The offsets cache of the runtime animation
  51042. */
  51043. this._offsetsCache = {};
  51044. /**
  51045. * The high limits cache of the runtime animation
  51046. */
  51047. this._highLimitsCache = {};
  51048. /**
  51049. * Specifies if the runtime animation has been stopped
  51050. */
  51051. this._stopped = false;
  51052. /**
  51053. * The blending factor of the runtime animation
  51054. */
  51055. this._blendingFactor = 0;
  51056. /**
  51057. * The target path of the runtime animation
  51058. */
  51059. this._targetPath = "";
  51060. /**
  51061. * The weight of the runtime animation
  51062. */
  51063. this._weight = 1.0;
  51064. /**
  51065. * The ratio offset of the runtime animation
  51066. */
  51067. this._ratioOffset = 0;
  51068. /**
  51069. * The previous delay of the runtime animation
  51070. */
  51071. this._previousDelay = 0;
  51072. /**
  51073. * The previous ratio of the runtime animation
  51074. */
  51075. this._previousRatio = 0;
  51076. this._animation = animation;
  51077. this._target = target;
  51078. this._scene = scene;
  51079. this._host = host;
  51080. animation._runtimeAnimations.push(this);
  51081. // Cloning events locally
  51082. var events = animation.getEvents();
  51083. if (events && events.length > 0) {
  51084. events.forEach(function (e) {
  51085. _this._events.push(e._clone());
  51086. });
  51087. }
  51088. }
  51089. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51090. /**
  51091. * Gets the current frame of the runtime animation
  51092. */
  51093. get: function () {
  51094. return this._currentFrame;
  51095. },
  51096. enumerable: true,
  51097. configurable: true
  51098. });
  51099. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51100. /**
  51101. * Gets the weight of the runtime animation
  51102. */
  51103. get: function () {
  51104. return this._weight;
  51105. },
  51106. enumerable: true,
  51107. configurable: true
  51108. });
  51109. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51110. /**
  51111. * Gets the current value of the runtime animation
  51112. */
  51113. get: function () {
  51114. return this._currentValue;
  51115. },
  51116. enumerable: true,
  51117. configurable: true
  51118. });
  51119. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51120. /**
  51121. * Gets the target path of the runtime animation
  51122. */
  51123. get: function () {
  51124. return this._targetPath;
  51125. },
  51126. enumerable: true,
  51127. configurable: true
  51128. });
  51129. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51130. /**
  51131. * Gets the actual target of the runtime animation
  51132. */
  51133. get: function () {
  51134. return this._activeTarget;
  51135. },
  51136. enumerable: true,
  51137. configurable: true
  51138. });
  51139. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51140. /**
  51141. * Gets the animation from the runtime animation
  51142. */
  51143. get: function () {
  51144. return this._animation;
  51145. },
  51146. enumerable: true,
  51147. configurable: true
  51148. });
  51149. /**
  51150. * Resets the runtime animation to the beginning
  51151. * @param restoreOriginal defines whether to restore the target property to the original value
  51152. */
  51153. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51154. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51155. if (restoreOriginal) {
  51156. if (this._target instanceof Array) {
  51157. var index = 0;
  51158. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51159. var target = _a[_i];
  51160. if (this._originalValue[index] !== undefined) {
  51161. this._setValue(target, this._originalValue[index], -1);
  51162. }
  51163. index++;
  51164. }
  51165. }
  51166. else {
  51167. if (this._originalValue[0] !== undefined) {
  51168. this._setValue(this._target, this._originalValue[0], -1);
  51169. }
  51170. }
  51171. }
  51172. this._offsetsCache = {};
  51173. this._highLimitsCache = {};
  51174. this._currentFrame = 0;
  51175. this._blendingFactor = 0;
  51176. this._originalValue = new Array();
  51177. // Events
  51178. for (var index = 0; index < this._events.length; index++) {
  51179. this._events[index].isDone = false;
  51180. }
  51181. };
  51182. /**
  51183. * Specifies if the runtime animation is stopped
  51184. * @returns Boolean specifying if the runtime animation is stopped
  51185. */
  51186. RuntimeAnimation.prototype.isStopped = function () {
  51187. return this._stopped;
  51188. };
  51189. /**
  51190. * Disposes of the runtime animation
  51191. */
  51192. RuntimeAnimation.prototype.dispose = function () {
  51193. var index = this._animation.runtimeAnimations.indexOf(this);
  51194. if (index > -1) {
  51195. this._animation.runtimeAnimations.splice(index, 1);
  51196. }
  51197. };
  51198. /**
  51199. * Interpolates the animation from the current frame
  51200. * @param currentFrame The frame to interpolate the animation to
  51201. * @param repeatCount The number of times that the animation should loop
  51202. * @param loopMode The type of looping mode to use
  51203. * @param offsetValue Animation offset value
  51204. * @param highLimitValue The high limit value
  51205. * @returns The interpolated value
  51206. */
  51207. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51208. this._currentFrame = currentFrame;
  51209. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51210. this._workValue = BABYLON.Matrix.Zero();
  51211. }
  51212. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51213. };
  51214. /**
  51215. * Apply the interpolated value to the target
  51216. * @param currentValue defines the value computed by the animation
  51217. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51218. */
  51219. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51220. if (weight === void 0) { weight = 1.0; }
  51221. if (this._target instanceof Array) {
  51222. var index = 0;
  51223. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51224. var target = _a[_i];
  51225. this._setValue(target, currentValue, weight, index);
  51226. index++;
  51227. }
  51228. }
  51229. else {
  51230. this._setValue(this._target, currentValue, weight);
  51231. }
  51232. };
  51233. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51234. if (targetIndex === void 0) { targetIndex = 0; }
  51235. // Set value
  51236. var path;
  51237. var destination;
  51238. var targetPropertyPath = this._animation.targetPropertyPath;
  51239. if (targetPropertyPath.length > 1) {
  51240. var property = target[targetPropertyPath[0]];
  51241. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51242. property = property[targetPropertyPath[index]];
  51243. }
  51244. path = targetPropertyPath[targetPropertyPath.length - 1];
  51245. destination = property;
  51246. }
  51247. else {
  51248. path = targetPropertyPath[0];
  51249. destination = target;
  51250. }
  51251. this._targetPath = path;
  51252. this._activeTarget = destination;
  51253. this._weight = weight;
  51254. if (this._originalValue[targetIndex] === undefined) {
  51255. var originalValue = void 0;
  51256. if (destination.getRestPose && path === "_matrix") { // For bones
  51257. originalValue = destination.getRestPose();
  51258. }
  51259. else {
  51260. originalValue = destination[path];
  51261. }
  51262. if (originalValue && originalValue.clone) {
  51263. this._originalValue[targetIndex] = originalValue.clone();
  51264. }
  51265. else {
  51266. this._originalValue[targetIndex] = originalValue;
  51267. }
  51268. }
  51269. // Blending
  51270. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51271. if (enableBlending && this._blendingFactor <= 1.0) {
  51272. if (!this._originalBlendValue) {
  51273. var originalValue = destination[path];
  51274. if (originalValue.clone) {
  51275. this._originalBlendValue = originalValue.clone();
  51276. }
  51277. else {
  51278. this._originalBlendValue = originalValue;
  51279. }
  51280. }
  51281. if (this._originalBlendValue.m) { // Matrix
  51282. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51283. if (this._currentValue) {
  51284. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51285. }
  51286. else {
  51287. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51288. }
  51289. }
  51290. else {
  51291. if (this._currentValue) {
  51292. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51293. }
  51294. else {
  51295. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51296. }
  51297. }
  51298. }
  51299. else {
  51300. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51301. }
  51302. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51303. this._blendingFactor += blendingSpeed;
  51304. }
  51305. else {
  51306. this._currentValue = currentValue;
  51307. }
  51308. if (weight !== -1.0) {
  51309. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51310. }
  51311. else {
  51312. destination[path] = this._currentValue;
  51313. }
  51314. if (target.markAsDirty) {
  51315. target.markAsDirty(this._animation.targetProperty);
  51316. }
  51317. };
  51318. /**
  51319. * Gets the loop pmode of the runtime animation
  51320. * @returns Loop Mode
  51321. */
  51322. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51323. if (this._target && this._target.animationPropertiesOverride) {
  51324. return this._target.animationPropertiesOverride.loopMode;
  51325. }
  51326. return this._animation.loopMode;
  51327. };
  51328. /**
  51329. * Move the current animation to a given frame
  51330. * @param frame defines the frame to move to
  51331. */
  51332. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51333. var keys = this._animation.getKeys();
  51334. if (frame < keys[0].frame) {
  51335. frame = keys[0].frame;
  51336. }
  51337. else if (frame > keys[keys.length - 1].frame) {
  51338. frame = keys[keys.length - 1].frame;
  51339. }
  51340. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51341. this.setValue(currentValue, -1);
  51342. };
  51343. /**
  51344. * @hidden Internal use only
  51345. */
  51346. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51347. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51348. this._ratioOffset = this._previousRatio - newRatio;
  51349. };
  51350. /**
  51351. * Execute the current animation
  51352. * @param delay defines the delay to add to the current frame
  51353. * @param from defines the lower bound of the animation range
  51354. * @param to defines the upper bound of the animation range
  51355. * @param loop defines if the current animation must loop
  51356. * @param speedRatio defines the current speed ratio
  51357. * @param weight defines the weight of the animation (default is -1 so no weight)
  51358. * @returns a boolean indicating if the animation is running
  51359. */
  51360. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51361. if (weight === void 0) { weight = -1.0; }
  51362. var targetPropertyPath = this._animation.targetPropertyPath;
  51363. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51364. this._stopped = true;
  51365. return false;
  51366. }
  51367. var returnValue = true;
  51368. var keys = this._animation.getKeys();
  51369. // Adding a start key at frame 0 if missing
  51370. if (keys[0].frame !== 0) {
  51371. var newKey = { frame: 0, value: keys[0].value };
  51372. keys.splice(0, 0, newKey);
  51373. }
  51374. // Adding a duplicate key when there is only one key at frame zero
  51375. else if (keys.length === 1) {
  51376. var newKey = { frame: 0.001, value: keys[0].value };
  51377. keys.push(newKey);
  51378. }
  51379. // Check limits
  51380. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51381. from = keys[0].frame;
  51382. }
  51383. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51384. to = keys[keys.length - 1].frame;
  51385. }
  51386. //to and from cannot be the same key
  51387. if (from === to) {
  51388. if (from > keys[0].frame) {
  51389. from--;
  51390. }
  51391. else if (to < keys[keys.length - 1].frame) {
  51392. to++;
  51393. }
  51394. }
  51395. // Compute ratio
  51396. var range = to - from;
  51397. var offsetValue;
  51398. // ratio represents the frame delta between from and to
  51399. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51400. var highLimitValue = 0;
  51401. this._previousDelay = delay;
  51402. this._previousRatio = ratio;
  51403. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51404. returnValue = false;
  51405. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51406. }
  51407. else {
  51408. // Get max value if required
  51409. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51410. var keyOffset = to.toString() + from.toString();
  51411. if (!this._offsetsCache[keyOffset]) {
  51412. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51413. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51414. switch (this._animation.dataType) {
  51415. // Float
  51416. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51417. this._offsetsCache[keyOffset] = toValue - fromValue;
  51418. break;
  51419. // Quaternion
  51420. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51421. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51422. break;
  51423. // Vector3
  51424. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51425. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51426. // Vector2
  51427. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51428. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51429. // Size
  51430. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51431. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51432. // Color3
  51433. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51434. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51435. default:
  51436. break;
  51437. }
  51438. this._highLimitsCache[keyOffset] = toValue;
  51439. }
  51440. highLimitValue = this._highLimitsCache[keyOffset];
  51441. offsetValue = this._offsetsCache[keyOffset];
  51442. }
  51443. }
  51444. if (offsetValue === undefined) {
  51445. switch (this._animation.dataType) {
  51446. // Float
  51447. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51448. offsetValue = 0;
  51449. break;
  51450. // Quaternion
  51451. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51452. offsetValue = _staticOffsetValueQuaternion;
  51453. break;
  51454. // Vector3
  51455. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51456. offsetValue = _staticOffsetValueVector3;
  51457. break;
  51458. // Vector2
  51459. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51460. offsetValue = _staticOffsetValueVector2;
  51461. break;
  51462. // Size
  51463. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51464. offsetValue = _staticOffsetValueSize;
  51465. break;
  51466. // Color3
  51467. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51468. offsetValue = _staticOffsetValueColor3;
  51469. }
  51470. }
  51471. // Compute value
  51472. var repeatCount = (ratio / range) >> 0;
  51473. var currentFrame = returnValue ? from + ratio % range : to;
  51474. // Need to normalize?
  51475. if (this._host && this._host.syncRoot) {
  51476. var syncRoot = this._host.syncRoot;
  51477. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51478. currentFrame = from + (to - from) * hostNormalizedFrame;
  51479. }
  51480. // Reset events if looping
  51481. var events = this._events;
  51482. if (range > 0 && this.currentFrame > currentFrame ||
  51483. range < 0 && this.currentFrame < currentFrame) {
  51484. // Need to reset animation events
  51485. for (var index = 0; index < events.length; index++) {
  51486. if (!events[index].onlyOnce) {
  51487. // reset event, the animation is looping
  51488. events[index].isDone = false;
  51489. }
  51490. }
  51491. }
  51492. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51493. // Set value
  51494. this.setValue(currentValue, weight);
  51495. // Check events
  51496. for (var index = 0; index < events.length; index++) {
  51497. // Make sure current frame has passed event frame and that event frame is within the current range
  51498. // Also, handle both forward and reverse animations
  51499. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51500. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51501. var event = events[index];
  51502. if (!event.isDone) {
  51503. // If event should be done only once, remove it.
  51504. if (event.onlyOnce) {
  51505. events.splice(index, 1);
  51506. index--;
  51507. }
  51508. event.isDone = true;
  51509. event.action(currentFrame);
  51510. } // Don't do anything if the event has already be done.
  51511. }
  51512. }
  51513. if (!returnValue) {
  51514. this._stopped = true;
  51515. }
  51516. return returnValue;
  51517. };
  51518. return RuntimeAnimation;
  51519. }());
  51520. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51521. })(BABYLON || (BABYLON = {}));
  51522. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51523. var BABYLON;
  51524. (function (BABYLON) {
  51525. /**
  51526. * Class used to store an actual running animation
  51527. */
  51528. var Animatable = /** @class */ (function () {
  51529. /**
  51530. * Creates a new Animatable
  51531. * @param scene defines the hosting scene
  51532. * @param target defines the target object
  51533. * @param fromFrame defines the starting frame number (default is 0)
  51534. * @param toFrame defines the ending frame number (default is 100)
  51535. * @param loopAnimation defines if the animation must loop (default is false)
  51536. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51537. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51538. * @param animations defines a group of animation to add to the new Animatable
  51539. */
  51540. function Animatable(scene,
  51541. /** defines the target object */
  51542. target,
  51543. /** defines the starting frame number (default is 0) */
  51544. fromFrame,
  51545. /** defines the ending frame number (default is 100) */
  51546. toFrame,
  51547. /** defines if the animation must loop (default is false) */
  51548. loopAnimation, speedRatio,
  51549. /** defines a callback to call when animation ends if it is not looping */
  51550. onAnimationEnd, animations) {
  51551. if (fromFrame === void 0) { fromFrame = 0; }
  51552. if (toFrame === void 0) { toFrame = 100; }
  51553. if (loopAnimation === void 0) { loopAnimation = false; }
  51554. if (speedRatio === void 0) { speedRatio = 1.0; }
  51555. this.target = target;
  51556. this.fromFrame = fromFrame;
  51557. this.toFrame = toFrame;
  51558. this.loopAnimation = loopAnimation;
  51559. this.onAnimationEnd = onAnimationEnd;
  51560. this._localDelayOffset = null;
  51561. this._pausedDelay = null;
  51562. this._runtimeAnimations = new Array();
  51563. this._paused = false;
  51564. this._speedRatio = 1;
  51565. this._weight = -1.0;
  51566. /**
  51567. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51568. * This will only apply for non looping animation (default is true)
  51569. */
  51570. this.disposeOnEnd = true;
  51571. /**
  51572. * Gets a boolean indicating if the animation has started
  51573. */
  51574. this.animationStarted = false;
  51575. /**
  51576. * Observer raised when the animation ends
  51577. */
  51578. this.onAnimationEndObservable = new BABYLON.Observable();
  51579. this._scene = scene;
  51580. if (animations) {
  51581. this.appendAnimations(target, animations);
  51582. }
  51583. this._speedRatio = speedRatio;
  51584. scene._activeAnimatables.push(this);
  51585. }
  51586. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51587. /**
  51588. * Gets the root Animatable used to synchronize and normalize animations
  51589. */
  51590. get: function () {
  51591. return this._syncRoot;
  51592. },
  51593. enumerable: true,
  51594. configurable: true
  51595. });
  51596. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51597. /**
  51598. * Gets the current frame of the first RuntimeAnimation
  51599. * Used to synchronize Animatables
  51600. */
  51601. get: function () {
  51602. if (this._runtimeAnimations.length === 0) {
  51603. return 0;
  51604. }
  51605. return this._runtimeAnimations[0].currentFrame;
  51606. },
  51607. enumerable: true,
  51608. configurable: true
  51609. });
  51610. Object.defineProperty(Animatable.prototype, "weight", {
  51611. /**
  51612. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51613. */
  51614. get: function () {
  51615. return this._weight;
  51616. },
  51617. set: function (value) {
  51618. if (value === -1) { // -1 is ok and means no weight
  51619. this._weight = -1;
  51620. return;
  51621. }
  51622. // Else weight must be in [0, 1] range
  51623. this._weight = Math.min(Math.max(value, 0), 1.0);
  51624. },
  51625. enumerable: true,
  51626. configurable: true
  51627. });
  51628. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51629. /**
  51630. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51631. */
  51632. get: function () {
  51633. return this._speedRatio;
  51634. },
  51635. set: function (value) {
  51636. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51637. var animation = this._runtimeAnimations[index];
  51638. animation._prepareForSpeedRatioChange(value);
  51639. }
  51640. this._speedRatio = value;
  51641. },
  51642. enumerable: true,
  51643. configurable: true
  51644. });
  51645. // Methods
  51646. /**
  51647. * Synchronize and normalize current Animatable with a source Animatable
  51648. * This is useful when using animation weights and when animations are not of the same length
  51649. * @param root defines the root Animatable to synchronize with
  51650. * @returns the current Animatable
  51651. */
  51652. Animatable.prototype.syncWith = function (root) {
  51653. this._syncRoot = root;
  51654. if (root) {
  51655. // Make sure this animatable will animate after the root
  51656. var index = this._scene._activeAnimatables.indexOf(this);
  51657. if (index > -1) {
  51658. this._scene._activeAnimatables.splice(index, 1);
  51659. this._scene._activeAnimatables.push(this);
  51660. }
  51661. }
  51662. return this;
  51663. };
  51664. /**
  51665. * Gets the list of runtime animations
  51666. * @returns an array of RuntimeAnimation
  51667. */
  51668. Animatable.prototype.getAnimations = function () {
  51669. return this._runtimeAnimations;
  51670. };
  51671. /**
  51672. * Adds more animations to the current animatable
  51673. * @param target defines the target of the animations
  51674. * @param animations defines the new animations to add
  51675. */
  51676. Animatable.prototype.appendAnimations = function (target, animations) {
  51677. for (var index = 0; index < animations.length; index++) {
  51678. var animation = animations[index];
  51679. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51680. }
  51681. };
  51682. /**
  51683. * Gets the source animation for a specific property
  51684. * @param property defines the propertyu to look for
  51685. * @returns null or the source animation for the given property
  51686. */
  51687. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51688. var runtimeAnimations = this._runtimeAnimations;
  51689. for (var index = 0; index < runtimeAnimations.length; index++) {
  51690. if (runtimeAnimations[index].animation.targetProperty === property) {
  51691. return runtimeAnimations[index].animation;
  51692. }
  51693. }
  51694. return null;
  51695. };
  51696. /**
  51697. * Gets the runtime animation for a specific property
  51698. * @param property defines the propertyu to look for
  51699. * @returns null or the runtime animation for the given property
  51700. */
  51701. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51702. var runtimeAnimations = this._runtimeAnimations;
  51703. for (var index = 0; index < runtimeAnimations.length; index++) {
  51704. if (runtimeAnimations[index].animation.targetProperty === property) {
  51705. return runtimeAnimations[index];
  51706. }
  51707. }
  51708. return null;
  51709. };
  51710. /**
  51711. * Resets the animatable to its original state
  51712. */
  51713. Animatable.prototype.reset = function () {
  51714. var runtimeAnimations = this._runtimeAnimations;
  51715. for (var index = 0; index < runtimeAnimations.length; index++) {
  51716. runtimeAnimations[index].reset(true);
  51717. }
  51718. this._localDelayOffset = null;
  51719. this._pausedDelay = null;
  51720. };
  51721. /**
  51722. * Allows the animatable to blend with current running animations
  51723. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51724. * @param blendingSpeed defines the blending speed to use
  51725. */
  51726. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51727. var runtimeAnimations = this._runtimeAnimations;
  51728. for (var index = 0; index < runtimeAnimations.length; index++) {
  51729. runtimeAnimations[index].animation.enableBlending = true;
  51730. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51731. }
  51732. };
  51733. /**
  51734. * Disable animation blending
  51735. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51736. */
  51737. Animatable.prototype.disableBlending = function () {
  51738. var runtimeAnimations = this._runtimeAnimations;
  51739. for (var index = 0; index < runtimeAnimations.length; index++) {
  51740. runtimeAnimations[index].animation.enableBlending = false;
  51741. }
  51742. };
  51743. /**
  51744. * Jump directly to a given frame
  51745. * @param frame defines the frame to jump to
  51746. */
  51747. Animatable.prototype.goToFrame = function (frame) {
  51748. var runtimeAnimations = this._runtimeAnimations;
  51749. if (runtimeAnimations[0]) {
  51750. var fps = runtimeAnimations[0].animation.framePerSecond;
  51751. var currentFrame = runtimeAnimations[0].currentFrame;
  51752. var adjustTime = frame - currentFrame;
  51753. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51754. if (this._localDelayOffset === null) {
  51755. this._localDelayOffset = 0;
  51756. }
  51757. this._localDelayOffset -= delay;
  51758. }
  51759. for (var index = 0; index < runtimeAnimations.length; index++) {
  51760. runtimeAnimations[index].goToFrame(frame);
  51761. }
  51762. };
  51763. /**
  51764. * Pause the animation
  51765. */
  51766. Animatable.prototype.pause = function () {
  51767. if (this._paused) {
  51768. return;
  51769. }
  51770. this._paused = true;
  51771. };
  51772. /**
  51773. * Restart the animation
  51774. */
  51775. Animatable.prototype.restart = function () {
  51776. this._paused = false;
  51777. };
  51778. Animatable.prototype._raiseOnAnimationEnd = function () {
  51779. if (this.onAnimationEnd) {
  51780. this.onAnimationEnd();
  51781. }
  51782. this.onAnimationEndObservable.notifyObservers(this);
  51783. };
  51784. /**
  51785. * Stop and delete the current animation
  51786. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51787. * @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)
  51788. */
  51789. Animatable.prototype.stop = function (animationName, targetMask) {
  51790. if (animationName || targetMask) {
  51791. var idx = this._scene._activeAnimatables.indexOf(this);
  51792. if (idx > -1) {
  51793. var runtimeAnimations = this._runtimeAnimations;
  51794. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51795. var runtimeAnimation = runtimeAnimations[index];
  51796. if (animationName && runtimeAnimation.animation.name != animationName) {
  51797. continue;
  51798. }
  51799. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51800. continue;
  51801. }
  51802. runtimeAnimation.dispose();
  51803. runtimeAnimations.splice(index, 1);
  51804. }
  51805. if (runtimeAnimations.length == 0) {
  51806. this._scene._activeAnimatables.splice(idx, 1);
  51807. this._raiseOnAnimationEnd();
  51808. }
  51809. }
  51810. }
  51811. else {
  51812. var index = this._scene._activeAnimatables.indexOf(this);
  51813. if (index > -1) {
  51814. this._scene._activeAnimatables.splice(index, 1);
  51815. var runtimeAnimations = this._runtimeAnimations;
  51816. for (var index = 0; index < runtimeAnimations.length; index++) {
  51817. runtimeAnimations[index].dispose();
  51818. }
  51819. this._raiseOnAnimationEnd();
  51820. }
  51821. }
  51822. };
  51823. /**
  51824. * Wait asynchronously for the animation to end
  51825. * @returns a promise which will be fullfilled when the animation ends
  51826. */
  51827. Animatable.prototype.waitAsync = function () {
  51828. var _this = this;
  51829. return new Promise(function (resolve, reject) {
  51830. _this.onAnimationEndObservable.add(function () {
  51831. resolve(_this);
  51832. }, undefined, undefined, _this, true);
  51833. });
  51834. };
  51835. /** @hidden */
  51836. Animatable.prototype._animate = function (delay) {
  51837. if (this._paused) {
  51838. this.animationStarted = false;
  51839. if (this._pausedDelay === null) {
  51840. this._pausedDelay = delay;
  51841. }
  51842. return true;
  51843. }
  51844. if (this._localDelayOffset === null) {
  51845. this._localDelayOffset = delay;
  51846. this._pausedDelay = null;
  51847. }
  51848. else if (this._pausedDelay !== null) {
  51849. this._localDelayOffset += delay - this._pausedDelay;
  51850. this._pausedDelay = null;
  51851. }
  51852. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51853. return true;
  51854. }
  51855. // Animating
  51856. var running = false;
  51857. var runtimeAnimations = this._runtimeAnimations;
  51858. var index;
  51859. for (index = 0; index < runtimeAnimations.length; index++) {
  51860. var animation = runtimeAnimations[index];
  51861. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51862. running = running || isRunning;
  51863. }
  51864. this.animationStarted = running;
  51865. if (!running) {
  51866. if (this.disposeOnEnd) {
  51867. // Remove from active animatables
  51868. index = this._scene._activeAnimatables.indexOf(this);
  51869. this._scene._activeAnimatables.splice(index, 1);
  51870. // Dispose all runtime animations
  51871. for (index = 0; index < runtimeAnimations.length; index++) {
  51872. runtimeAnimations[index].dispose();
  51873. }
  51874. }
  51875. this._raiseOnAnimationEnd();
  51876. if (this.disposeOnEnd) {
  51877. this.onAnimationEnd = null;
  51878. this.onAnimationEndObservable.clear();
  51879. }
  51880. }
  51881. return running;
  51882. };
  51883. return Animatable;
  51884. }());
  51885. BABYLON.Animatable = Animatable;
  51886. })(BABYLON || (BABYLON = {}));
  51887. //# sourceMappingURL=babylon.animatable.js.map
  51888. var BABYLON;
  51889. (function (BABYLON) {
  51890. var EasingFunction = /** @class */ (function () {
  51891. function EasingFunction() {
  51892. // Properties
  51893. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51894. }
  51895. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51896. get: function () {
  51897. return EasingFunction._EASINGMODE_EASEIN;
  51898. },
  51899. enumerable: true,
  51900. configurable: true
  51901. });
  51902. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51903. get: function () {
  51904. return EasingFunction._EASINGMODE_EASEOUT;
  51905. },
  51906. enumerable: true,
  51907. configurable: true
  51908. });
  51909. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51910. get: function () {
  51911. return EasingFunction._EASINGMODE_EASEINOUT;
  51912. },
  51913. enumerable: true,
  51914. configurable: true
  51915. });
  51916. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51917. var n = Math.min(Math.max(easingMode, 0), 2);
  51918. this._easingMode = n;
  51919. };
  51920. EasingFunction.prototype.getEasingMode = function () {
  51921. return this._easingMode;
  51922. };
  51923. EasingFunction.prototype.easeInCore = function (gradient) {
  51924. throw new Error('You must implement this method');
  51925. };
  51926. EasingFunction.prototype.ease = function (gradient) {
  51927. switch (this._easingMode) {
  51928. case EasingFunction.EASINGMODE_EASEIN:
  51929. return this.easeInCore(gradient);
  51930. case EasingFunction.EASINGMODE_EASEOUT:
  51931. return (1 - this.easeInCore(1 - gradient));
  51932. }
  51933. if (gradient >= 0.5) {
  51934. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51935. }
  51936. return (this.easeInCore(gradient * 2) * 0.5);
  51937. };
  51938. //Statics
  51939. EasingFunction._EASINGMODE_EASEIN = 0;
  51940. EasingFunction._EASINGMODE_EASEOUT = 1;
  51941. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51942. return EasingFunction;
  51943. }());
  51944. BABYLON.EasingFunction = EasingFunction;
  51945. var CircleEase = /** @class */ (function (_super) {
  51946. __extends(CircleEase, _super);
  51947. function CircleEase() {
  51948. return _super !== null && _super.apply(this, arguments) || this;
  51949. }
  51950. CircleEase.prototype.easeInCore = function (gradient) {
  51951. gradient = Math.max(0, Math.min(1, gradient));
  51952. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51953. };
  51954. return CircleEase;
  51955. }(EasingFunction));
  51956. BABYLON.CircleEase = CircleEase;
  51957. var BackEase = /** @class */ (function (_super) {
  51958. __extends(BackEase, _super);
  51959. function BackEase(amplitude) {
  51960. if (amplitude === void 0) { amplitude = 1; }
  51961. var _this = _super.call(this) || this;
  51962. _this.amplitude = amplitude;
  51963. return _this;
  51964. }
  51965. BackEase.prototype.easeInCore = function (gradient) {
  51966. var num = Math.max(0, this.amplitude);
  51967. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51968. };
  51969. return BackEase;
  51970. }(EasingFunction));
  51971. BABYLON.BackEase = BackEase;
  51972. var BounceEase = /** @class */ (function (_super) {
  51973. __extends(BounceEase, _super);
  51974. function BounceEase(bounces, bounciness) {
  51975. if (bounces === void 0) { bounces = 3; }
  51976. if (bounciness === void 0) { bounciness = 2; }
  51977. var _this = _super.call(this) || this;
  51978. _this.bounces = bounces;
  51979. _this.bounciness = bounciness;
  51980. return _this;
  51981. }
  51982. BounceEase.prototype.easeInCore = function (gradient) {
  51983. var y = Math.max(0.0, this.bounces);
  51984. var bounciness = this.bounciness;
  51985. if (bounciness <= 1.0) {
  51986. bounciness = 1.001;
  51987. }
  51988. var num9 = Math.pow(bounciness, y);
  51989. var num5 = 1.0 - bounciness;
  51990. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51991. var num15 = gradient * num4;
  51992. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51993. var num3 = Math.floor(num65);
  51994. var num13 = num3 + 1.0;
  51995. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51996. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51997. var num7 = (num8 + num12) * 0.5;
  51998. var num6 = gradient - num7;
  51999. var num2 = num7 - num8;
  52000. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52001. };
  52002. return BounceEase;
  52003. }(EasingFunction));
  52004. BABYLON.BounceEase = BounceEase;
  52005. var CubicEase = /** @class */ (function (_super) {
  52006. __extends(CubicEase, _super);
  52007. function CubicEase() {
  52008. return _super !== null && _super.apply(this, arguments) || this;
  52009. }
  52010. CubicEase.prototype.easeInCore = function (gradient) {
  52011. return (gradient * gradient * gradient);
  52012. };
  52013. return CubicEase;
  52014. }(EasingFunction));
  52015. BABYLON.CubicEase = CubicEase;
  52016. var ElasticEase = /** @class */ (function (_super) {
  52017. __extends(ElasticEase, _super);
  52018. function ElasticEase(oscillations, springiness) {
  52019. if (oscillations === void 0) { oscillations = 3; }
  52020. if (springiness === void 0) { springiness = 3; }
  52021. var _this = _super.call(this) || this;
  52022. _this.oscillations = oscillations;
  52023. _this.springiness = springiness;
  52024. return _this;
  52025. }
  52026. ElasticEase.prototype.easeInCore = function (gradient) {
  52027. var num2;
  52028. var num3 = Math.max(0.0, this.oscillations);
  52029. var num = Math.max(0.0, this.springiness);
  52030. if (num == 0) {
  52031. num2 = gradient;
  52032. }
  52033. else {
  52034. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52035. }
  52036. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52037. };
  52038. return ElasticEase;
  52039. }(EasingFunction));
  52040. BABYLON.ElasticEase = ElasticEase;
  52041. var ExponentialEase = /** @class */ (function (_super) {
  52042. __extends(ExponentialEase, _super);
  52043. function ExponentialEase(exponent) {
  52044. if (exponent === void 0) { exponent = 2; }
  52045. var _this = _super.call(this) || this;
  52046. _this.exponent = exponent;
  52047. return _this;
  52048. }
  52049. ExponentialEase.prototype.easeInCore = function (gradient) {
  52050. if (this.exponent <= 0) {
  52051. return gradient;
  52052. }
  52053. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52054. };
  52055. return ExponentialEase;
  52056. }(EasingFunction));
  52057. BABYLON.ExponentialEase = ExponentialEase;
  52058. var PowerEase = /** @class */ (function (_super) {
  52059. __extends(PowerEase, _super);
  52060. function PowerEase(power) {
  52061. if (power === void 0) { power = 2; }
  52062. var _this = _super.call(this) || this;
  52063. _this.power = power;
  52064. return _this;
  52065. }
  52066. PowerEase.prototype.easeInCore = function (gradient) {
  52067. var y = Math.max(0.0, this.power);
  52068. return Math.pow(gradient, y);
  52069. };
  52070. return PowerEase;
  52071. }(EasingFunction));
  52072. BABYLON.PowerEase = PowerEase;
  52073. var QuadraticEase = /** @class */ (function (_super) {
  52074. __extends(QuadraticEase, _super);
  52075. function QuadraticEase() {
  52076. return _super !== null && _super.apply(this, arguments) || this;
  52077. }
  52078. QuadraticEase.prototype.easeInCore = function (gradient) {
  52079. return (gradient * gradient);
  52080. };
  52081. return QuadraticEase;
  52082. }(EasingFunction));
  52083. BABYLON.QuadraticEase = QuadraticEase;
  52084. var QuarticEase = /** @class */ (function (_super) {
  52085. __extends(QuarticEase, _super);
  52086. function QuarticEase() {
  52087. return _super !== null && _super.apply(this, arguments) || this;
  52088. }
  52089. QuarticEase.prototype.easeInCore = function (gradient) {
  52090. return (gradient * gradient * gradient * gradient);
  52091. };
  52092. return QuarticEase;
  52093. }(EasingFunction));
  52094. BABYLON.QuarticEase = QuarticEase;
  52095. var QuinticEase = /** @class */ (function (_super) {
  52096. __extends(QuinticEase, _super);
  52097. function QuinticEase() {
  52098. return _super !== null && _super.apply(this, arguments) || this;
  52099. }
  52100. QuinticEase.prototype.easeInCore = function (gradient) {
  52101. return (gradient * gradient * gradient * gradient * gradient);
  52102. };
  52103. return QuinticEase;
  52104. }(EasingFunction));
  52105. BABYLON.QuinticEase = QuinticEase;
  52106. var SineEase = /** @class */ (function (_super) {
  52107. __extends(SineEase, _super);
  52108. function SineEase() {
  52109. return _super !== null && _super.apply(this, arguments) || this;
  52110. }
  52111. SineEase.prototype.easeInCore = function (gradient) {
  52112. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52113. };
  52114. return SineEase;
  52115. }(EasingFunction));
  52116. BABYLON.SineEase = SineEase;
  52117. var BezierCurveEase = /** @class */ (function (_super) {
  52118. __extends(BezierCurveEase, _super);
  52119. function BezierCurveEase(x1, y1, x2, y2) {
  52120. if (x1 === void 0) { x1 = 0; }
  52121. if (y1 === void 0) { y1 = 0; }
  52122. if (x2 === void 0) { x2 = 1; }
  52123. if (y2 === void 0) { y2 = 1; }
  52124. var _this = _super.call(this) || this;
  52125. _this.x1 = x1;
  52126. _this.y1 = y1;
  52127. _this.x2 = x2;
  52128. _this.y2 = y2;
  52129. return _this;
  52130. }
  52131. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52132. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52133. };
  52134. return BezierCurveEase;
  52135. }(EasingFunction));
  52136. BABYLON.BezierCurveEase = BezierCurveEase;
  52137. })(BABYLON || (BABYLON = {}));
  52138. //# sourceMappingURL=babylon.easing.js.map
  52139. var BABYLON;
  52140. (function (BABYLON) {
  52141. /**
  52142. * A Condition applied to an Action
  52143. */
  52144. var Condition = /** @class */ (function () {
  52145. /**
  52146. * Creates a new Condition
  52147. * @param actionManager the manager of the action the condition is applied to
  52148. */
  52149. function Condition(actionManager) {
  52150. this._actionManager = actionManager;
  52151. }
  52152. /**
  52153. * Check if the current condition is valid
  52154. * @returns a boolean
  52155. */
  52156. Condition.prototype.isValid = function () {
  52157. return true;
  52158. };
  52159. /**
  52160. * Internal only
  52161. * @hidden
  52162. */
  52163. Condition.prototype._getProperty = function (propertyPath) {
  52164. return this._actionManager._getProperty(propertyPath);
  52165. };
  52166. /**
  52167. * Internal only
  52168. * @hidden
  52169. */
  52170. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52171. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52172. };
  52173. /**
  52174. * Serialize placeholder for child classes
  52175. * @returns the serialized object
  52176. */
  52177. Condition.prototype.serialize = function () {
  52178. };
  52179. /**
  52180. * Internal only
  52181. * @hidden
  52182. */
  52183. Condition.prototype._serialize = function (serializedCondition) {
  52184. return {
  52185. type: 2,
  52186. children: [],
  52187. name: serializedCondition.name,
  52188. properties: serializedCondition.properties
  52189. };
  52190. };
  52191. return Condition;
  52192. }());
  52193. BABYLON.Condition = Condition;
  52194. /**
  52195. * Defines specific conditional operators as extensions of Condition
  52196. */
  52197. var ValueCondition = /** @class */ (function (_super) {
  52198. __extends(ValueCondition, _super);
  52199. /**
  52200. * Creates a new ValueCondition
  52201. * @param actionManager manager for the action the condition applies to
  52202. * @param target for the action
  52203. * @param propertyPath path to specify the property of the target the conditional operator uses
  52204. * @param value the value compared by the conditional operator against the current value of the property
  52205. * @param operator the conditional operator, default ValueCondition.IsEqual
  52206. */
  52207. function ValueCondition(actionManager, target,
  52208. /** path to specify the property of the target the conditional operator uses */
  52209. propertyPath,
  52210. /** the value compared by the conditional operator against the current value of the property */
  52211. value,
  52212. /** the conditional operator, default ValueCondition.IsEqual */
  52213. operator) {
  52214. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52215. var _this = _super.call(this, actionManager) || this;
  52216. _this.propertyPath = propertyPath;
  52217. _this.value = value;
  52218. _this.operator = operator;
  52219. _this._target = target;
  52220. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52221. _this._property = _this._getProperty(_this.propertyPath);
  52222. return _this;
  52223. }
  52224. Object.defineProperty(ValueCondition, "IsEqual", {
  52225. /**
  52226. * returns the number for IsEqual
  52227. */
  52228. get: function () {
  52229. return ValueCondition._IsEqual;
  52230. },
  52231. enumerable: true,
  52232. configurable: true
  52233. });
  52234. Object.defineProperty(ValueCondition, "IsDifferent", {
  52235. /**
  52236. * Returns the number for IsDifferent
  52237. */
  52238. get: function () {
  52239. return ValueCondition._IsDifferent;
  52240. },
  52241. enumerable: true,
  52242. configurable: true
  52243. });
  52244. Object.defineProperty(ValueCondition, "IsGreater", {
  52245. /**
  52246. * Returns the number for IsGreater
  52247. */
  52248. get: function () {
  52249. return ValueCondition._IsGreater;
  52250. },
  52251. enumerable: true,
  52252. configurable: true
  52253. });
  52254. Object.defineProperty(ValueCondition, "IsLesser", {
  52255. /**
  52256. * Returns the number for IsLesser
  52257. */
  52258. get: function () {
  52259. return ValueCondition._IsLesser;
  52260. },
  52261. enumerable: true,
  52262. configurable: true
  52263. });
  52264. /**
  52265. * Compares the given value with the property value for the specified conditional operator
  52266. * @returns the result of the comparison
  52267. */
  52268. ValueCondition.prototype.isValid = function () {
  52269. switch (this.operator) {
  52270. case ValueCondition.IsGreater:
  52271. return this._effectiveTarget[this._property] > this.value;
  52272. case ValueCondition.IsLesser:
  52273. return this._effectiveTarget[this._property] < this.value;
  52274. case ValueCondition.IsEqual:
  52275. case ValueCondition.IsDifferent:
  52276. var check;
  52277. if (this.value.equals) {
  52278. check = this.value.equals(this._effectiveTarget[this._property]);
  52279. }
  52280. else {
  52281. check = this.value === this._effectiveTarget[this._property];
  52282. }
  52283. return this.operator === ValueCondition.IsEqual ? check : !check;
  52284. }
  52285. return false;
  52286. };
  52287. /**
  52288. * Serialize the ValueCondition into a JSON compatible object
  52289. * @returns serialization object
  52290. */
  52291. ValueCondition.prototype.serialize = function () {
  52292. return this._serialize({
  52293. name: "ValueCondition",
  52294. properties: [
  52295. BABYLON.Action._GetTargetProperty(this._target),
  52296. { name: "propertyPath", value: this.propertyPath },
  52297. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52298. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52299. ]
  52300. });
  52301. };
  52302. /**
  52303. * Gets the name of the conditional operator for the ValueCondition
  52304. * @param operator the conditional operator
  52305. * @returns the name
  52306. */
  52307. ValueCondition.GetOperatorName = function (operator) {
  52308. switch (operator) {
  52309. case ValueCondition._IsEqual: return "IsEqual";
  52310. case ValueCondition._IsDifferent: return "IsDifferent";
  52311. case ValueCondition._IsGreater: return "IsGreater";
  52312. case ValueCondition._IsLesser: return "IsLesser";
  52313. default: return "";
  52314. }
  52315. };
  52316. /**
  52317. * Internal only
  52318. * @hidden
  52319. */
  52320. ValueCondition._IsEqual = 0;
  52321. /**
  52322. * Internal only
  52323. * @hidden
  52324. */
  52325. ValueCondition._IsDifferent = 1;
  52326. /**
  52327. * Internal only
  52328. * @hidden
  52329. */
  52330. ValueCondition._IsGreater = 2;
  52331. /**
  52332. * Internal only
  52333. * @hidden
  52334. */
  52335. ValueCondition._IsLesser = 3;
  52336. return ValueCondition;
  52337. }(Condition));
  52338. BABYLON.ValueCondition = ValueCondition;
  52339. /**
  52340. * Defines a predicate condition as an extension of Condition
  52341. */
  52342. var PredicateCondition = /** @class */ (function (_super) {
  52343. __extends(PredicateCondition, _super);
  52344. /**
  52345. * Creates a new PredicateCondition
  52346. * @param actionManager manager for the action the condition applies to
  52347. * @param predicate defines the predicate function used to validate the condition
  52348. */
  52349. function PredicateCondition(actionManager,
  52350. /** defines the predicate function used to validate the condition */
  52351. predicate) {
  52352. var _this = _super.call(this, actionManager) || this;
  52353. _this.predicate = predicate;
  52354. return _this;
  52355. }
  52356. /**
  52357. * @returns the validity of the predicate condition
  52358. */
  52359. PredicateCondition.prototype.isValid = function () {
  52360. return this.predicate();
  52361. };
  52362. return PredicateCondition;
  52363. }(Condition));
  52364. BABYLON.PredicateCondition = PredicateCondition;
  52365. /**
  52366. * Defines a state condition as an extension of Condition
  52367. */
  52368. var StateCondition = /** @class */ (function (_super) {
  52369. __extends(StateCondition, _super);
  52370. /**
  52371. * Creates a new StateCondition
  52372. * @param actionManager manager for the action the condition applies to
  52373. * @param target of the condition
  52374. * @param value to compare with target state
  52375. */
  52376. function StateCondition(actionManager, target, value) {
  52377. var _this = _super.call(this, actionManager) || this;
  52378. _this.value = value;
  52379. _this._target = target;
  52380. return _this;
  52381. }
  52382. /**
  52383. * @returns the validity of the state
  52384. */
  52385. StateCondition.prototype.isValid = function () {
  52386. return this._target.state === this.value;
  52387. };
  52388. /**
  52389. * Serialize the StateCondition into a JSON compatible object
  52390. * @returns serialization object
  52391. */
  52392. StateCondition.prototype.serialize = function () {
  52393. return this._serialize({
  52394. name: "StateCondition",
  52395. properties: [
  52396. BABYLON.Action._GetTargetProperty(this._target),
  52397. { name: "value", value: this.value }
  52398. ]
  52399. });
  52400. };
  52401. return StateCondition;
  52402. }(Condition));
  52403. BABYLON.StateCondition = StateCondition;
  52404. })(BABYLON || (BABYLON = {}));
  52405. //# sourceMappingURL=babylon.condition.js.map
  52406. var BABYLON;
  52407. (function (BABYLON) {
  52408. /**
  52409. * The action to be carried out following a trigger
  52410. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52411. */
  52412. var Action = /** @class */ (function () {
  52413. /**
  52414. * Creates a new Action
  52415. * @param triggerOptions the trigger, with or without parameters, for the action
  52416. * @param condition an optional determinant of action
  52417. */
  52418. function Action(
  52419. /** the trigger, with or without parameters, for the action */
  52420. triggerOptions, condition) {
  52421. this.triggerOptions = triggerOptions;
  52422. /**
  52423. * An event triggered prior to action being executed.
  52424. */
  52425. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52426. if (triggerOptions.parameter) {
  52427. this.trigger = triggerOptions.trigger;
  52428. this._triggerParameter = triggerOptions.parameter;
  52429. }
  52430. else if (triggerOptions.trigger) {
  52431. this.trigger = triggerOptions.trigger;
  52432. }
  52433. else {
  52434. this.trigger = triggerOptions;
  52435. }
  52436. this._nextActiveAction = this;
  52437. this._condition = condition;
  52438. }
  52439. /**
  52440. * Internal only
  52441. * @hidden
  52442. */
  52443. Action.prototype._prepare = function () {
  52444. };
  52445. /**
  52446. * Gets the trigger parameters
  52447. * @returns the trigger parameters
  52448. */
  52449. Action.prototype.getTriggerParameter = function () {
  52450. return this._triggerParameter;
  52451. };
  52452. /**
  52453. * Internal only - executes current action event
  52454. * @hidden
  52455. */
  52456. Action.prototype._executeCurrent = function (evt) {
  52457. if (this._nextActiveAction._condition) {
  52458. var condition = this._nextActiveAction._condition;
  52459. var currentRenderId = this._actionManager.getScene().getRenderId();
  52460. // We cache the current evaluation for the current frame
  52461. if (condition._evaluationId === currentRenderId) {
  52462. if (!condition._currentResult) {
  52463. return;
  52464. }
  52465. }
  52466. else {
  52467. condition._evaluationId = currentRenderId;
  52468. if (!condition.isValid()) {
  52469. condition._currentResult = false;
  52470. return;
  52471. }
  52472. condition._currentResult = true;
  52473. }
  52474. }
  52475. this.onBeforeExecuteObservable.notifyObservers(this);
  52476. this._nextActiveAction.execute(evt);
  52477. this.skipToNextActiveAction();
  52478. };
  52479. /**
  52480. * Execute placeholder for child classes
  52481. * @param evt optional action event
  52482. */
  52483. Action.prototype.execute = function (evt) {
  52484. };
  52485. /**
  52486. * Skips to next active action
  52487. */
  52488. Action.prototype.skipToNextActiveAction = function () {
  52489. if (this._nextActiveAction._child) {
  52490. if (!this._nextActiveAction._child._actionManager) {
  52491. this._nextActiveAction._child._actionManager = this._actionManager;
  52492. }
  52493. this._nextActiveAction = this._nextActiveAction._child;
  52494. }
  52495. else {
  52496. this._nextActiveAction = this;
  52497. }
  52498. };
  52499. /**
  52500. * Adds action to chain of actions, may be a DoNothingAction
  52501. * @param action defines the next action to execute
  52502. * @returns The action passed in
  52503. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52504. */
  52505. Action.prototype.then = function (action) {
  52506. this._child = action;
  52507. action._actionManager = this._actionManager;
  52508. action._prepare();
  52509. return action;
  52510. };
  52511. /**
  52512. * Internal only
  52513. * @hidden
  52514. */
  52515. Action.prototype._getProperty = function (propertyPath) {
  52516. return this._actionManager._getProperty(propertyPath);
  52517. };
  52518. /**
  52519. * Internal only
  52520. * @hidden
  52521. */
  52522. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52523. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52524. };
  52525. /**
  52526. * Serialize placeholder for child classes
  52527. * @param parent of child
  52528. * @returns the serialized object
  52529. */
  52530. Action.prototype.serialize = function (parent) {
  52531. };
  52532. /**
  52533. * Internal only called by serialize
  52534. * @hidden
  52535. */
  52536. Action.prototype._serialize = function (serializedAction, parent) {
  52537. var serializationObject = {
  52538. type: 1,
  52539. children: [],
  52540. name: serializedAction.name,
  52541. properties: serializedAction.properties || []
  52542. };
  52543. // Serialize child
  52544. if (this._child) {
  52545. this._child.serialize(serializationObject);
  52546. }
  52547. // Check if "this" has a condition
  52548. if (this._condition) {
  52549. var serializedCondition = this._condition.serialize();
  52550. serializedCondition.children.push(serializationObject);
  52551. if (parent) {
  52552. parent.children.push(serializedCondition);
  52553. }
  52554. return serializedCondition;
  52555. }
  52556. if (parent) {
  52557. parent.children.push(serializationObject);
  52558. }
  52559. return serializationObject;
  52560. };
  52561. /**
  52562. * Internal only
  52563. * @hidden
  52564. */
  52565. Action._SerializeValueAsString = function (value) {
  52566. if (typeof value === "number") {
  52567. return value.toString();
  52568. }
  52569. if (typeof value === "boolean") {
  52570. return value ? "true" : "false";
  52571. }
  52572. if (value instanceof BABYLON.Vector2) {
  52573. return value.x + ", " + value.y;
  52574. }
  52575. if (value instanceof BABYLON.Vector3) {
  52576. return value.x + ", " + value.y + ", " + value.z;
  52577. }
  52578. if (value instanceof BABYLON.Color3) {
  52579. return value.r + ", " + value.g + ", " + value.b;
  52580. }
  52581. if (value instanceof BABYLON.Color4) {
  52582. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52583. }
  52584. return value; // string
  52585. };
  52586. /**
  52587. * Internal only
  52588. * @hidden
  52589. */
  52590. Action._GetTargetProperty = function (target) {
  52591. return {
  52592. name: "target",
  52593. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52594. : target instanceof BABYLON.Light ? "LightProperties"
  52595. : target instanceof BABYLON.Camera ? "CameraProperties"
  52596. : "SceneProperties",
  52597. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52598. };
  52599. };
  52600. return Action;
  52601. }());
  52602. BABYLON.Action = Action;
  52603. })(BABYLON || (BABYLON = {}));
  52604. //# sourceMappingURL=babylon.action.js.map
  52605. var BABYLON;
  52606. (function (BABYLON) {
  52607. /**
  52608. * ActionEvent is the event being sent when an action is triggered.
  52609. */
  52610. var ActionEvent = /** @class */ (function () {
  52611. /**
  52612. * Creates a new ActionEvent
  52613. * @param source The mesh or sprite that triggered the action
  52614. * @param pointerX The X mouse cursor position at the time of the event
  52615. * @param pointerY The Y mouse cursor position at the time of the event
  52616. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52617. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52618. * @param additionalData additional data for the event
  52619. */
  52620. function ActionEvent(
  52621. /** The mesh or sprite that triggered the action */
  52622. source,
  52623. /** The X mouse cursor position at the time of the event */
  52624. pointerX,
  52625. /** The Y mouse cursor position at the time of the event */
  52626. pointerY,
  52627. /** The mesh that is currently pointed at (can be null) */
  52628. meshUnderPointer,
  52629. /** the original (browser) event that triggered the ActionEvent */
  52630. sourceEvent,
  52631. /** additional data for the event */
  52632. additionalData) {
  52633. this.source = source;
  52634. this.pointerX = pointerX;
  52635. this.pointerY = pointerY;
  52636. this.meshUnderPointer = meshUnderPointer;
  52637. this.sourceEvent = sourceEvent;
  52638. this.additionalData = additionalData;
  52639. }
  52640. /**
  52641. * Helper function to auto-create an ActionEvent from a source mesh.
  52642. * @param source The source mesh that triggered the event
  52643. * @param evt The original (browser) event
  52644. * @param additionalData additional data for the event
  52645. * @returns the new ActionEvent
  52646. */
  52647. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52648. var scene = source.getScene();
  52649. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52650. };
  52651. /**
  52652. * Helper function to auto-create an ActionEvent from a source sprite
  52653. * @param source The source sprite that triggered the event
  52654. * @param scene Scene associated with the sprite
  52655. * @param evt The original (browser) event
  52656. * @param additionalData additional data for the event
  52657. * @returns the new ActionEvent
  52658. */
  52659. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52660. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52661. };
  52662. /**
  52663. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52664. * @param scene the scene where the event occurred
  52665. * @param evt The original (browser) event
  52666. * @returns the new ActionEvent
  52667. */
  52668. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52669. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52670. };
  52671. /**
  52672. * Helper function to auto-create an ActionEvent from a primitive
  52673. * @param prim defines the target primitive
  52674. * @param pointerPos defines the pointer position
  52675. * @param evt The original (browser) event
  52676. * @param additionalData additional data for the event
  52677. * @returns the new ActionEvent
  52678. */
  52679. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52680. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52681. };
  52682. return ActionEvent;
  52683. }());
  52684. BABYLON.ActionEvent = ActionEvent;
  52685. /**
  52686. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52687. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52688. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52689. */
  52690. var ActionManager = /** @class */ (function () {
  52691. /**
  52692. * Creates a new action manager
  52693. * @param scene defines the hosting scene
  52694. */
  52695. function ActionManager(scene) {
  52696. // Members
  52697. /** Gets the list of actions */
  52698. this.actions = new Array();
  52699. /** Gets the cursor to use when hovering items */
  52700. this.hoverCursor = '';
  52701. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52702. scene.actionManagers.push(this);
  52703. }
  52704. Object.defineProperty(ActionManager, "NothingTrigger", {
  52705. /**
  52706. * Nothing
  52707. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52708. */
  52709. get: function () {
  52710. return ActionManager._NothingTrigger;
  52711. },
  52712. enumerable: true,
  52713. configurable: true
  52714. });
  52715. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52716. /**
  52717. * On pick
  52718. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52719. */
  52720. get: function () {
  52721. return ActionManager._OnPickTrigger;
  52722. },
  52723. enumerable: true,
  52724. configurable: true
  52725. });
  52726. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52727. /**
  52728. * On left pick
  52729. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52730. */
  52731. get: function () {
  52732. return ActionManager._OnLeftPickTrigger;
  52733. },
  52734. enumerable: true,
  52735. configurable: true
  52736. });
  52737. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52738. /**
  52739. * On right pick
  52740. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52741. */
  52742. get: function () {
  52743. return ActionManager._OnRightPickTrigger;
  52744. },
  52745. enumerable: true,
  52746. configurable: true
  52747. });
  52748. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52749. /**
  52750. * On center pick
  52751. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52752. */
  52753. get: function () {
  52754. return ActionManager._OnCenterPickTrigger;
  52755. },
  52756. enumerable: true,
  52757. configurable: true
  52758. });
  52759. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52760. /**
  52761. * On pick down
  52762. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52763. */
  52764. get: function () {
  52765. return ActionManager._OnPickDownTrigger;
  52766. },
  52767. enumerable: true,
  52768. configurable: true
  52769. });
  52770. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52771. /**
  52772. * On double pick
  52773. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52774. */
  52775. get: function () {
  52776. return ActionManager._OnDoublePickTrigger;
  52777. },
  52778. enumerable: true,
  52779. configurable: true
  52780. });
  52781. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52782. /**
  52783. * On pick up
  52784. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52785. */
  52786. get: function () {
  52787. return ActionManager._OnPickUpTrigger;
  52788. },
  52789. enumerable: true,
  52790. configurable: true
  52791. });
  52792. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52793. /**
  52794. * On pick out.
  52795. * This trigger will only be raised if you also declared a OnPickDown
  52796. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52797. */
  52798. get: function () {
  52799. return ActionManager._OnPickOutTrigger;
  52800. },
  52801. enumerable: true,
  52802. configurable: true
  52803. });
  52804. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52805. /**
  52806. * On long press
  52807. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52808. */
  52809. get: function () {
  52810. return ActionManager._OnLongPressTrigger;
  52811. },
  52812. enumerable: true,
  52813. configurable: true
  52814. });
  52815. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52816. /**
  52817. * On pointer over
  52818. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52819. */
  52820. get: function () {
  52821. return ActionManager._OnPointerOverTrigger;
  52822. },
  52823. enumerable: true,
  52824. configurable: true
  52825. });
  52826. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52827. /**
  52828. * On pointer out
  52829. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52830. */
  52831. get: function () {
  52832. return ActionManager._OnPointerOutTrigger;
  52833. },
  52834. enumerable: true,
  52835. configurable: true
  52836. });
  52837. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52838. /**
  52839. * On every frame
  52840. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52841. */
  52842. get: function () {
  52843. return ActionManager._OnEveryFrameTrigger;
  52844. },
  52845. enumerable: true,
  52846. configurable: true
  52847. });
  52848. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52849. /**
  52850. * On intersection enter
  52851. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52852. */
  52853. get: function () {
  52854. return ActionManager._OnIntersectionEnterTrigger;
  52855. },
  52856. enumerable: true,
  52857. configurable: true
  52858. });
  52859. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52860. /**
  52861. * On intersection exit
  52862. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52863. */
  52864. get: function () {
  52865. return ActionManager._OnIntersectionExitTrigger;
  52866. },
  52867. enumerable: true,
  52868. configurable: true
  52869. });
  52870. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52871. /**
  52872. * On key down
  52873. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52874. */
  52875. get: function () {
  52876. return ActionManager._OnKeyDownTrigger;
  52877. },
  52878. enumerable: true,
  52879. configurable: true
  52880. });
  52881. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52882. /**
  52883. * On key up
  52884. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52885. */
  52886. get: function () {
  52887. return ActionManager._OnKeyUpTrigger;
  52888. },
  52889. enumerable: true,
  52890. configurable: true
  52891. });
  52892. // Methods
  52893. /**
  52894. * Releases all associated resources
  52895. */
  52896. ActionManager.prototype.dispose = function () {
  52897. var index = this._scene.actionManagers.indexOf(this);
  52898. for (var i = 0; i < this.actions.length; i++) {
  52899. var action = this.actions[i];
  52900. ActionManager.Triggers[action.trigger]--;
  52901. if (ActionManager.Triggers[action.trigger] === 0) {
  52902. delete ActionManager.Triggers[action.trigger];
  52903. }
  52904. }
  52905. if (index > -1) {
  52906. this._scene.actionManagers.splice(index, 1);
  52907. }
  52908. };
  52909. /**
  52910. * Gets hosting scene
  52911. * @returns the hosting scene
  52912. */
  52913. ActionManager.prototype.getScene = function () {
  52914. return this._scene;
  52915. };
  52916. /**
  52917. * Does this action manager handles actions of any of the given triggers
  52918. * @param triggers defines the triggers to be tested
  52919. * @return a boolean indicating whether one (or more) of the triggers is handled
  52920. */
  52921. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52922. for (var index = 0; index < this.actions.length; index++) {
  52923. var action = this.actions[index];
  52924. if (triggers.indexOf(action.trigger) > -1) {
  52925. return true;
  52926. }
  52927. }
  52928. return false;
  52929. };
  52930. /**
  52931. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  52932. * speed.
  52933. * @param triggerA defines the trigger to be tested
  52934. * @param triggerB defines the trigger to be tested
  52935. * @return a boolean indicating whether one (or more) of the triggers is handled
  52936. */
  52937. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  52938. for (var index = 0; index < this.actions.length; index++) {
  52939. var action = this.actions[index];
  52940. if (triggerA == action.trigger || triggerB == action.trigger) {
  52941. return true;
  52942. }
  52943. }
  52944. return false;
  52945. };
  52946. /**
  52947. * Does this action manager handles actions of a given trigger
  52948. * @param trigger defines the trigger to be tested
  52949. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52950. * @return whether the trigger is handled
  52951. */
  52952. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52953. for (var index = 0; index < this.actions.length; index++) {
  52954. var action = this.actions[index];
  52955. if (action.trigger === trigger) {
  52956. if (parameterPredicate) {
  52957. if (parameterPredicate(action.getTriggerParameter())) {
  52958. return true;
  52959. }
  52960. }
  52961. else {
  52962. return true;
  52963. }
  52964. }
  52965. }
  52966. return false;
  52967. };
  52968. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52969. /**
  52970. * Does this action manager has pointer triggers
  52971. */
  52972. get: function () {
  52973. for (var index = 0; index < this.actions.length; index++) {
  52974. var action = this.actions[index];
  52975. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52976. return true;
  52977. }
  52978. }
  52979. return false;
  52980. },
  52981. enumerable: true,
  52982. configurable: true
  52983. });
  52984. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52985. /**
  52986. * Does this action manager has pick triggers
  52987. */
  52988. get: function () {
  52989. for (var index = 0; index < this.actions.length; index++) {
  52990. var action = this.actions[index];
  52991. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52992. return true;
  52993. }
  52994. }
  52995. return false;
  52996. },
  52997. enumerable: true,
  52998. configurable: true
  52999. });
  53000. Object.defineProperty(ActionManager, "HasTriggers", {
  53001. /**
  53002. * Does exist one action manager with at least one trigger
  53003. **/
  53004. get: function () {
  53005. for (var t in ActionManager.Triggers) {
  53006. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53007. return true;
  53008. }
  53009. }
  53010. return false;
  53011. },
  53012. enumerable: true,
  53013. configurable: true
  53014. });
  53015. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53016. /**
  53017. * Does exist one action manager with at least one pick trigger
  53018. **/
  53019. get: function () {
  53020. for (var t in ActionManager.Triggers) {
  53021. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53022. var t_int = parseInt(t);
  53023. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53024. return true;
  53025. }
  53026. }
  53027. }
  53028. return false;
  53029. },
  53030. enumerable: true,
  53031. configurable: true
  53032. });
  53033. /**
  53034. * Does exist one action manager that handles actions of a given trigger
  53035. * @param trigger defines the trigger to be tested
  53036. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53037. **/
  53038. ActionManager.HasSpecificTrigger = function (trigger) {
  53039. for (var t in ActionManager.Triggers) {
  53040. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53041. var t_int = parseInt(t);
  53042. if (t_int === trigger) {
  53043. return true;
  53044. }
  53045. }
  53046. }
  53047. return false;
  53048. };
  53049. /**
  53050. * Registers an action to this action manager
  53051. * @param action defines the action to be registered
  53052. * @return the action amended (prepared) after registration
  53053. */
  53054. ActionManager.prototype.registerAction = function (action) {
  53055. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53056. if (this.getScene().actionManager !== this) {
  53057. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53058. return null;
  53059. }
  53060. }
  53061. this.actions.push(action);
  53062. if (ActionManager.Triggers[action.trigger]) {
  53063. ActionManager.Triggers[action.trigger]++;
  53064. }
  53065. else {
  53066. ActionManager.Triggers[action.trigger] = 1;
  53067. }
  53068. action._actionManager = this;
  53069. action._prepare();
  53070. return action;
  53071. };
  53072. /**
  53073. * Unregisters an action to this action manager
  53074. * @param action defines the action to be unregistered
  53075. * @return a boolean indicating whether the action has been unregistered
  53076. */
  53077. ActionManager.prototype.unregisterAction = function (action) {
  53078. var index = this.actions.indexOf(action);
  53079. if (index !== -1) {
  53080. this.actions.splice(index, 1);
  53081. ActionManager.Triggers[action.trigger] -= 1;
  53082. if (ActionManager.Triggers[action.trigger] === 0) {
  53083. delete ActionManager.Triggers[action.trigger];
  53084. }
  53085. delete action._actionManager;
  53086. return true;
  53087. }
  53088. return false;
  53089. };
  53090. /**
  53091. * Process a specific trigger
  53092. * @param trigger defines the trigger to process
  53093. * @param evt defines the event details to be processed
  53094. */
  53095. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53096. for (var index = 0; index < this.actions.length; index++) {
  53097. var action = this.actions[index];
  53098. if (action.trigger === trigger) {
  53099. if (evt) {
  53100. if (trigger === ActionManager.OnKeyUpTrigger
  53101. || trigger === ActionManager.OnKeyDownTrigger) {
  53102. var parameter = action.getTriggerParameter();
  53103. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53104. if (!parameter.toLowerCase) {
  53105. continue;
  53106. }
  53107. var lowerCase = parameter.toLowerCase();
  53108. if (lowerCase !== evt.sourceEvent.key) {
  53109. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53110. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53111. if (actualkey !== lowerCase) {
  53112. continue;
  53113. }
  53114. }
  53115. }
  53116. }
  53117. }
  53118. action._executeCurrent(evt);
  53119. }
  53120. }
  53121. };
  53122. /** @hidden */
  53123. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53124. var properties = propertyPath.split(".");
  53125. for (var index = 0; index < properties.length - 1; index++) {
  53126. target = target[properties[index]];
  53127. }
  53128. return target;
  53129. };
  53130. /** @hidden */
  53131. ActionManager.prototype._getProperty = function (propertyPath) {
  53132. var properties = propertyPath.split(".");
  53133. return properties[properties.length - 1];
  53134. };
  53135. /**
  53136. * Serialize this manager to a JSON object
  53137. * @param name defines the property name to store this manager
  53138. * @returns a JSON representation of this manager
  53139. */
  53140. ActionManager.prototype.serialize = function (name) {
  53141. var root = {
  53142. children: new Array(),
  53143. name: name,
  53144. type: 3,
  53145. properties: new Array() // Empty for root but required
  53146. };
  53147. for (var i = 0; i < this.actions.length; i++) {
  53148. var triggerObject = {
  53149. type: 0,
  53150. children: new Array(),
  53151. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53152. properties: new Array()
  53153. };
  53154. var triggerOptions = this.actions[i].triggerOptions;
  53155. if (triggerOptions && typeof triggerOptions !== "number") {
  53156. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53157. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53158. }
  53159. else {
  53160. var parameter = {};
  53161. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53162. if (triggerOptions.parameter.mesh) {
  53163. parameter._meshId = triggerOptions.parameter.mesh.id;
  53164. }
  53165. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53166. }
  53167. }
  53168. // Serialize child action, recursively
  53169. this.actions[i].serialize(triggerObject);
  53170. // Add serialized trigger
  53171. root.children.push(triggerObject);
  53172. }
  53173. return root;
  53174. };
  53175. /**
  53176. * Creates a new ActionManager from a JSON data
  53177. * @param parsedActions defines the JSON data to read from
  53178. * @param object defines the hosting mesh
  53179. * @param scene defines the hosting scene
  53180. */
  53181. ActionManager.Parse = function (parsedActions, object, scene) {
  53182. var actionManager = new ActionManager(scene);
  53183. if (object === null)
  53184. scene.actionManager = actionManager;
  53185. else
  53186. object.actionManager = actionManager;
  53187. // instanciate a new object
  53188. var instanciate = function (name, params) {
  53189. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53190. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53191. newInstance.constructor.apply(newInstance, params);
  53192. return newInstance;
  53193. };
  53194. var parseParameter = function (name, value, target, propertyPath) {
  53195. if (propertyPath === null) {
  53196. // String, boolean or float
  53197. var floatValue = parseFloat(value);
  53198. if (value === "true" || value === "false")
  53199. return value === "true";
  53200. else
  53201. return isNaN(floatValue) ? value : floatValue;
  53202. }
  53203. var effectiveTarget = propertyPath.split(".");
  53204. var values = value.split(",");
  53205. // Get effective Target
  53206. for (var i = 0; i < effectiveTarget.length; i++) {
  53207. target = target[effectiveTarget[i]];
  53208. }
  53209. // Return appropriate value with its type
  53210. if (typeof (target) === "boolean")
  53211. return values[0] === "true";
  53212. if (typeof (target) === "string")
  53213. return values[0];
  53214. // Parameters with multiple values such as Vector3 etc.
  53215. var split = new Array();
  53216. for (var i = 0; i < values.length; i++)
  53217. split.push(parseFloat(values[i]));
  53218. if (target instanceof BABYLON.Vector3)
  53219. return BABYLON.Vector3.FromArray(split);
  53220. if (target instanceof BABYLON.Vector4)
  53221. return BABYLON.Vector4.FromArray(split);
  53222. if (target instanceof BABYLON.Color3)
  53223. return BABYLON.Color3.FromArray(split);
  53224. if (target instanceof BABYLON.Color4)
  53225. return BABYLON.Color4.FromArray(split);
  53226. return parseFloat(values[0]);
  53227. };
  53228. // traverse graph per trigger
  53229. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53230. if (combineArray === void 0) { combineArray = null; }
  53231. if (parsedAction.detached)
  53232. return;
  53233. var parameters = new Array();
  53234. var target = null;
  53235. var propertyPath = null;
  53236. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53237. // Parameters
  53238. if (parsedAction.type === 2)
  53239. parameters.push(actionManager);
  53240. else
  53241. parameters.push(trigger);
  53242. if (combine) {
  53243. var actions = new Array();
  53244. for (var j = 0; j < parsedAction.combine.length; j++) {
  53245. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53246. }
  53247. parameters.push(actions);
  53248. }
  53249. else {
  53250. for (var i = 0; i < parsedAction.properties.length; i++) {
  53251. var value = parsedAction.properties[i].value;
  53252. var name = parsedAction.properties[i].name;
  53253. var targetType = parsedAction.properties[i].targetType;
  53254. if (name === "target")
  53255. if (targetType !== null && targetType === "SceneProperties")
  53256. value = target = scene;
  53257. else
  53258. value = target = scene.getNodeByName(value);
  53259. else if (name === "parent")
  53260. value = scene.getNodeByName(value);
  53261. else if (name === "sound") {
  53262. // Can not externalize to component, so only checks for the presence off the API.
  53263. if (scene.getSoundByName) {
  53264. value = scene.getSoundByName(value);
  53265. }
  53266. }
  53267. else if (name !== "propertyPath") {
  53268. if (parsedAction.type === 2 && name === "operator")
  53269. value = BABYLON.ValueCondition[value];
  53270. else
  53271. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53272. }
  53273. else {
  53274. propertyPath = value;
  53275. }
  53276. parameters.push(value);
  53277. }
  53278. }
  53279. if (combineArray === null) {
  53280. parameters.push(condition);
  53281. }
  53282. else {
  53283. parameters.push(null);
  53284. }
  53285. // If interpolate value action
  53286. if (parsedAction.name === "InterpolateValueAction") {
  53287. var param = parameters[parameters.length - 2];
  53288. parameters[parameters.length - 1] = param;
  53289. parameters[parameters.length - 2] = condition;
  53290. }
  53291. // Action or condition(s) and not CombineAction
  53292. var newAction = instanciate(parsedAction.name, parameters);
  53293. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53294. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53295. if (action)
  53296. action.then(nothing);
  53297. else
  53298. actionManager.registerAction(nothing);
  53299. action = nothing;
  53300. }
  53301. if (combineArray === null) {
  53302. if (newAction instanceof BABYLON.Condition) {
  53303. condition = newAction;
  53304. newAction = action;
  53305. }
  53306. else {
  53307. condition = null;
  53308. if (action)
  53309. action.then(newAction);
  53310. else
  53311. actionManager.registerAction(newAction);
  53312. }
  53313. }
  53314. else {
  53315. combineArray.push(newAction);
  53316. }
  53317. for (var i = 0; i < parsedAction.children.length; i++)
  53318. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53319. };
  53320. // triggers
  53321. for (var i = 0; i < parsedActions.children.length; i++) {
  53322. var triggerParams;
  53323. var trigger = parsedActions.children[i];
  53324. if (trigger.properties.length > 0) {
  53325. var param = trigger.properties[0].value;
  53326. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53327. if (value._meshId) {
  53328. value.mesh = scene.getMeshByID(value._meshId);
  53329. }
  53330. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53331. }
  53332. else
  53333. triggerParams = ActionManager[trigger.name];
  53334. for (var j = 0; j < trigger.children.length; j++) {
  53335. if (!trigger.detached)
  53336. traverse(trigger.children[j], triggerParams, null, null);
  53337. }
  53338. }
  53339. };
  53340. /**
  53341. * Get a trigger name by index
  53342. * @param trigger defines the trigger index
  53343. * @returns a trigger name
  53344. */
  53345. ActionManager.GetTriggerName = function (trigger) {
  53346. switch (trigger) {
  53347. case 0: return "NothingTrigger";
  53348. case 1: return "OnPickTrigger";
  53349. case 2: return "OnLeftPickTrigger";
  53350. case 3: return "OnRightPickTrigger";
  53351. case 4: return "OnCenterPickTrigger";
  53352. case 5: return "OnPickDownTrigger";
  53353. case 6: return "OnPickUpTrigger";
  53354. case 7: return "OnLongPressTrigger";
  53355. case 8: return "OnPointerOverTrigger";
  53356. case 9: return "OnPointerOutTrigger";
  53357. case 10: return "OnEveryFrameTrigger";
  53358. case 11: return "OnIntersectionEnterTrigger";
  53359. case 12: return "OnIntersectionExitTrigger";
  53360. case 13: return "OnKeyDownTrigger";
  53361. case 14: return "OnKeyUpTrigger";
  53362. case 15: return "OnPickOutTrigger";
  53363. default: return "";
  53364. }
  53365. };
  53366. // Statics
  53367. ActionManager._NothingTrigger = 0;
  53368. ActionManager._OnPickTrigger = 1;
  53369. ActionManager._OnLeftPickTrigger = 2;
  53370. ActionManager._OnRightPickTrigger = 3;
  53371. ActionManager._OnCenterPickTrigger = 4;
  53372. ActionManager._OnPickDownTrigger = 5;
  53373. ActionManager._OnDoublePickTrigger = 6;
  53374. ActionManager._OnPickUpTrigger = 7;
  53375. ActionManager._OnLongPressTrigger = 8;
  53376. ActionManager._OnPointerOverTrigger = 9;
  53377. ActionManager._OnPointerOutTrigger = 10;
  53378. ActionManager._OnEveryFrameTrigger = 11;
  53379. ActionManager._OnIntersectionEnterTrigger = 12;
  53380. ActionManager._OnIntersectionExitTrigger = 13;
  53381. ActionManager._OnKeyDownTrigger = 14;
  53382. ActionManager._OnKeyUpTrigger = 15;
  53383. ActionManager._OnPickOutTrigger = 16;
  53384. /** Gets the list of active triggers */
  53385. ActionManager.Triggers = {};
  53386. return ActionManager;
  53387. }());
  53388. BABYLON.ActionManager = ActionManager;
  53389. })(BABYLON || (BABYLON = {}));
  53390. //# sourceMappingURL=babylon.actionManager.js.map
  53391. var BABYLON;
  53392. (function (BABYLON) {
  53393. var InterpolateValueAction = /** @class */ (function (_super) {
  53394. __extends(InterpolateValueAction, _super);
  53395. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53396. if (duration === void 0) { duration = 1000; }
  53397. var _this = _super.call(this, triggerOptions, condition) || this;
  53398. _this.propertyPath = propertyPath;
  53399. _this.value = value;
  53400. _this.duration = duration;
  53401. _this.stopOtherAnimations = stopOtherAnimations;
  53402. _this.onInterpolationDone = onInterpolationDone;
  53403. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53404. _this._target = _this._effectiveTarget = target;
  53405. return _this;
  53406. }
  53407. /** @hidden */
  53408. InterpolateValueAction.prototype._prepare = function () {
  53409. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53410. this._property = this._getProperty(this.propertyPath);
  53411. };
  53412. InterpolateValueAction.prototype.execute = function () {
  53413. var _this = this;
  53414. var scene = this._actionManager.getScene();
  53415. var keys = [
  53416. {
  53417. frame: 0,
  53418. value: this._effectiveTarget[this._property]
  53419. }, {
  53420. frame: 100,
  53421. value: this.value
  53422. }
  53423. ];
  53424. var dataType;
  53425. if (typeof this.value === "number") {
  53426. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53427. }
  53428. else if (this.value instanceof BABYLON.Color3) {
  53429. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53430. }
  53431. else if (this.value instanceof BABYLON.Vector3) {
  53432. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53433. }
  53434. else if (this.value instanceof BABYLON.Matrix) {
  53435. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53436. }
  53437. else if (this.value instanceof BABYLON.Quaternion) {
  53438. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53439. }
  53440. else {
  53441. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53442. return;
  53443. }
  53444. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53445. animation.setKeys(keys);
  53446. if (this.stopOtherAnimations) {
  53447. scene.stopAnimation(this._effectiveTarget);
  53448. }
  53449. var wrapper = function () {
  53450. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53451. if (_this.onInterpolationDone) {
  53452. _this.onInterpolationDone();
  53453. }
  53454. };
  53455. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53456. };
  53457. InterpolateValueAction.prototype.serialize = function (parent) {
  53458. return _super.prototype._serialize.call(this, {
  53459. name: "InterpolateValueAction",
  53460. properties: [
  53461. BABYLON.Action._GetTargetProperty(this._target),
  53462. { name: "propertyPath", value: this.propertyPath },
  53463. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53464. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53465. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53466. ]
  53467. }, parent);
  53468. };
  53469. return InterpolateValueAction;
  53470. }(BABYLON.Action));
  53471. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53472. })(BABYLON || (BABYLON = {}));
  53473. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53474. var BABYLON;
  53475. (function (BABYLON) {
  53476. var SwitchBooleanAction = /** @class */ (function (_super) {
  53477. __extends(SwitchBooleanAction, _super);
  53478. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53479. var _this = _super.call(this, triggerOptions, condition) || this;
  53480. _this.propertyPath = propertyPath;
  53481. _this._target = _this._effectiveTarget = target;
  53482. return _this;
  53483. }
  53484. /** @hidden */
  53485. SwitchBooleanAction.prototype._prepare = function () {
  53486. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53487. this._property = this._getProperty(this.propertyPath);
  53488. };
  53489. SwitchBooleanAction.prototype.execute = function () {
  53490. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53491. };
  53492. SwitchBooleanAction.prototype.serialize = function (parent) {
  53493. return _super.prototype._serialize.call(this, {
  53494. name: "SwitchBooleanAction",
  53495. properties: [
  53496. BABYLON.Action._GetTargetProperty(this._target),
  53497. { name: "propertyPath", value: this.propertyPath }
  53498. ]
  53499. }, parent);
  53500. };
  53501. return SwitchBooleanAction;
  53502. }(BABYLON.Action));
  53503. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53504. var SetStateAction = /** @class */ (function (_super) {
  53505. __extends(SetStateAction, _super);
  53506. function SetStateAction(triggerOptions, target, value, condition) {
  53507. var _this = _super.call(this, triggerOptions, condition) || this;
  53508. _this.value = value;
  53509. _this._target = target;
  53510. return _this;
  53511. }
  53512. SetStateAction.prototype.execute = function () {
  53513. this._target.state = this.value;
  53514. };
  53515. SetStateAction.prototype.serialize = function (parent) {
  53516. return _super.prototype._serialize.call(this, {
  53517. name: "SetStateAction",
  53518. properties: [
  53519. BABYLON.Action._GetTargetProperty(this._target),
  53520. { name: "value", value: this.value }
  53521. ]
  53522. }, parent);
  53523. };
  53524. return SetStateAction;
  53525. }(BABYLON.Action));
  53526. BABYLON.SetStateAction = SetStateAction;
  53527. var SetValueAction = /** @class */ (function (_super) {
  53528. __extends(SetValueAction, _super);
  53529. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53530. var _this = _super.call(this, triggerOptions, condition) || this;
  53531. _this.propertyPath = propertyPath;
  53532. _this.value = value;
  53533. _this._target = _this._effectiveTarget = target;
  53534. return _this;
  53535. }
  53536. /** @hidden */
  53537. SetValueAction.prototype._prepare = function () {
  53538. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53539. this._property = this._getProperty(this.propertyPath);
  53540. };
  53541. SetValueAction.prototype.execute = function () {
  53542. this._effectiveTarget[this._property] = this.value;
  53543. if (this._target.markAsDirty) {
  53544. this._target.markAsDirty(this._property);
  53545. }
  53546. };
  53547. SetValueAction.prototype.serialize = function (parent) {
  53548. return _super.prototype._serialize.call(this, {
  53549. name: "SetValueAction",
  53550. properties: [
  53551. BABYLON.Action._GetTargetProperty(this._target),
  53552. { name: "propertyPath", value: this.propertyPath },
  53553. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53554. ]
  53555. }, parent);
  53556. };
  53557. return SetValueAction;
  53558. }(BABYLON.Action));
  53559. BABYLON.SetValueAction = SetValueAction;
  53560. var IncrementValueAction = /** @class */ (function (_super) {
  53561. __extends(IncrementValueAction, _super);
  53562. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53563. var _this = _super.call(this, triggerOptions, condition) || this;
  53564. _this.propertyPath = propertyPath;
  53565. _this.value = value;
  53566. _this._target = _this._effectiveTarget = target;
  53567. return _this;
  53568. }
  53569. /** @hidden */
  53570. IncrementValueAction.prototype._prepare = function () {
  53571. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53572. this._property = this._getProperty(this.propertyPath);
  53573. if (typeof this._effectiveTarget[this._property] !== "number") {
  53574. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53575. }
  53576. };
  53577. IncrementValueAction.prototype.execute = function () {
  53578. this._effectiveTarget[this._property] += this.value;
  53579. if (this._target.markAsDirty) {
  53580. this._target.markAsDirty(this._property);
  53581. }
  53582. };
  53583. IncrementValueAction.prototype.serialize = function (parent) {
  53584. return _super.prototype._serialize.call(this, {
  53585. name: "IncrementValueAction",
  53586. properties: [
  53587. BABYLON.Action._GetTargetProperty(this._target),
  53588. { name: "propertyPath", value: this.propertyPath },
  53589. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53590. ]
  53591. }, parent);
  53592. };
  53593. return IncrementValueAction;
  53594. }(BABYLON.Action));
  53595. BABYLON.IncrementValueAction = IncrementValueAction;
  53596. var PlayAnimationAction = /** @class */ (function (_super) {
  53597. __extends(PlayAnimationAction, _super);
  53598. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53599. var _this = _super.call(this, triggerOptions, condition) || this;
  53600. _this.from = from;
  53601. _this.to = to;
  53602. _this.loop = loop;
  53603. _this._target = target;
  53604. return _this;
  53605. }
  53606. /** @hidden */
  53607. PlayAnimationAction.prototype._prepare = function () {
  53608. };
  53609. PlayAnimationAction.prototype.execute = function () {
  53610. var scene = this._actionManager.getScene();
  53611. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53612. };
  53613. PlayAnimationAction.prototype.serialize = function (parent) {
  53614. return _super.prototype._serialize.call(this, {
  53615. name: "PlayAnimationAction",
  53616. properties: [
  53617. BABYLON.Action._GetTargetProperty(this._target),
  53618. { name: "from", value: String(this.from) },
  53619. { name: "to", value: String(this.to) },
  53620. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53621. ]
  53622. }, parent);
  53623. };
  53624. return PlayAnimationAction;
  53625. }(BABYLON.Action));
  53626. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53627. var StopAnimationAction = /** @class */ (function (_super) {
  53628. __extends(StopAnimationAction, _super);
  53629. function StopAnimationAction(triggerOptions, target, condition) {
  53630. var _this = _super.call(this, triggerOptions, condition) || this;
  53631. _this._target = target;
  53632. return _this;
  53633. }
  53634. /** @hidden */
  53635. StopAnimationAction.prototype._prepare = function () {
  53636. };
  53637. StopAnimationAction.prototype.execute = function () {
  53638. var scene = this._actionManager.getScene();
  53639. scene.stopAnimation(this._target);
  53640. };
  53641. StopAnimationAction.prototype.serialize = function (parent) {
  53642. return _super.prototype._serialize.call(this, {
  53643. name: "StopAnimationAction",
  53644. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53645. }, parent);
  53646. };
  53647. return StopAnimationAction;
  53648. }(BABYLON.Action));
  53649. BABYLON.StopAnimationAction = StopAnimationAction;
  53650. var DoNothingAction = /** @class */ (function (_super) {
  53651. __extends(DoNothingAction, _super);
  53652. function DoNothingAction(triggerOptions, condition) {
  53653. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53654. return _super.call(this, triggerOptions, condition) || this;
  53655. }
  53656. DoNothingAction.prototype.execute = function () {
  53657. };
  53658. DoNothingAction.prototype.serialize = function (parent) {
  53659. return _super.prototype._serialize.call(this, {
  53660. name: "DoNothingAction",
  53661. properties: []
  53662. }, parent);
  53663. };
  53664. return DoNothingAction;
  53665. }(BABYLON.Action));
  53666. BABYLON.DoNothingAction = DoNothingAction;
  53667. var CombineAction = /** @class */ (function (_super) {
  53668. __extends(CombineAction, _super);
  53669. function CombineAction(triggerOptions, children, condition) {
  53670. var _this = _super.call(this, triggerOptions, condition) || this;
  53671. _this.children = children;
  53672. return _this;
  53673. }
  53674. /** @hidden */
  53675. CombineAction.prototype._prepare = function () {
  53676. for (var index = 0; index < this.children.length; index++) {
  53677. this.children[index]._actionManager = this._actionManager;
  53678. this.children[index]._prepare();
  53679. }
  53680. };
  53681. CombineAction.prototype.execute = function (evt) {
  53682. for (var index = 0; index < this.children.length; index++) {
  53683. this.children[index].execute(evt);
  53684. }
  53685. };
  53686. CombineAction.prototype.serialize = function (parent) {
  53687. var serializationObject = _super.prototype._serialize.call(this, {
  53688. name: "CombineAction",
  53689. properties: [],
  53690. combine: []
  53691. }, parent);
  53692. for (var i = 0; i < this.children.length; i++) {
  53693. serializationObject.combine.push(this.children[i].serialize(null));
  53694. }
  53695. return serializationObject;
  53696. };
  53697. return CombineAction;
  53698. }(BABYLON.Action));
  53699. BABYLON.CombineAction = CombineAction;
  53700. var ExecuteCodeAction = /** @class */ (function (_super) {
  53701. __extends(ExecuteCodeAction, _super);
  53702. function ExecuteCodeAction(triggerOptions, func, condition) {
  53703. var _this = _super.call(this, triggerOptions, condition) || this;
  53704. _this.func = func;
  53705. return _this;
  53706. }
  53707. ExecuteCodeAction.prototype.execute = function (evt) {
  53708. this.func(evt);
  53709. };
  53710. return ExecuteCodeAction;
  53711. }(BABYLON.Action));
  53712. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53713. var SetParentAction = /** @class */ (function (_super) {
  53714. __extends(SetParentAction, _super);
  53715. function SetParentAction(triggerOptions, target, parent, condition) {
  53716. var _this = _super.call(this, triggerOptions, condition) || this;
  53717. _this._target = target;
  53718. _this._parent = parent;
  53719. return _this;
  53720. }
  53721. /** @hidden */
  53722. SetParentAction.prototype._prepare = function () {
  53723. };
  53724. SetParentAction.prototype.execute = function () {
  53725. if (this._target.parent === this._parent) {
  53726. return;
  53727. }
  53728. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53729. invertParentWorldMatrix.invert();
  53730. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53731. this._target.parent = this._parent;
  53732. };
  53733. SetParentAction.prototype.serialize = function (parent) {
  53734. return _super.prototype._serialize.call(this, {
  53735. name: "SetParentAction",
  53736. properties: [
  53737. BABYLON.Action._GetTargetProperty(this._target),
  53738. BABYLON.Action._GetTargetProperty(this._parent),
  53739. ]
  53740. }, parent);
  53741. };
  53742. return SetParentAction;
  53743. }(BABYLON.Action));
  53744. BABYLON.SetParentAction = SetParentAction;
  53745. })(BABYLON || (BABYLON = {}));
  53746. //# sourceMappingURL=babylon.directActions.js.map
  53747. var BABYLON;
  53748. (function (BABYLON) {
  53749. var SpriteManager = /** @class */ (function () {
  53750. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53751. if (epsilon === void 0) { epsilon = 0.01; }
  53752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53753. this.name = name;
  53754. this.sprites = new Array();
  53755. this.renderingGroupId = 0;
  53756. this.layerMask = 0x0FFFFFFF;
  53757. this.fogEnabled = true;
  53758. this.isPickable = false;
  53759. /**
  53760. * An event triggered when the manager is disposed.
  53761. */
  53762. this.onDisposeObservable = new BABYLON.Observable();
  53763. this._vertexBuffers = {};
  53764. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  53765. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  53766. }
  53767. this._capacity = capacity;
  53768. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53769. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53770. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53771. if (cellSize.width && cellSize.height) {
  53772. this.cellWidth = cellSize.width;
  53773. this.cellHeight = cellSize.height;
  53774. }
  53775. else if (cellSize !== undefined) {
  53776. this.cellWidth = cellSize;
  53777. this.cellHeight = cellSize;
  53778. }
  53779. else {
  53780. return;
  53781. }
  53782. this._epsilon = epsilon;
  53783. this._scene = scene;
  53784. this._scene.spriteManagers.push(this);
  53785. var indices = [];
  53786. var index = 0;
  53787. for (var count = 0; count < capacity; count++) {
  53788. indices.push(index);
  53789. indices.push(index + 1);
  53790. indices.push(index + 2);
  53791. indices.push(index);
  53792. indices.push(index + 2);
  53793. indices.push(index + 3);
  53794. index += 4;
  53795. }
  53796. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53797. // VBO
  53798. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53799. this._vertexData = new Float32Array(capacity * 16 * 4);
  53800. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53801. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53802. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53803. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53804. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53805. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53806. this._vertexBuffers["options"] = options;
  53807. this._vertexBuffers["cellInfo"] = cellInfo;
  53808. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53809. // Effects
  53810. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53811. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53812. }
  53813. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53814. set: function (callback) {
  53815. if (this._onDisposeObserver) {
  53816. this.onDisposeObservable.remove(this._onDisposeObserver);
  53817. }
  53818. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53819. },
  53820. enumerable: true,
  53821. configurable: true
  53822. });
  53823. Object.defineProperty(SpriteManager.prototype, "texture", {
  53824. get: function () {
  53825. return this._spriteTexture;
  53826. },
  53827. set: function (value) {
  53828. this._spriteTexture = value;
  53829. },
  53830. enumerable: true,
  53831. configurable: true
  53832. });
  53833. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53834. var arrayOffset = index * 16;
  53835. if (offsetX === 0)
  53836. offsetX = this._epsilon;
  53837. else if (offsetX === 1)
  53838. offsetX = 1 - this._epsilon;
  53839. if (offsetY === 0)
  53840. offsetY = this._epsilon;
  53841. else if (offsetY === 1)
  53842. offsetY = 1 - this._epsilon;
  53843. this._vertexData[arrayOffset] = sprite.position.x;
  53844. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53845. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53846. this._vertexData[arrayOffset + 3] = sprite.angle;
  53847. this._vertexData[arrayOffset + 4] = sprite.width;
  53848. this._vertexData[arrayOffset + 5] = sprite.height;
  53849. this._vertexData[arrayOffset + 6] = offsetX;
  53850. this._vertexData[arrayOffset + 7] = offsetY;
  53851. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53852. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53853. var offset = (sprite.cellIndex / rowSize) >> 0;
  53854. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53855. this._vertexData[arrayOffset + 11] = offset;
  53856. // Color
  53857. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53858. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53859. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53860. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53861. };
  53862. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53863. var count = Math.min(this._capacity, this.sprites.length);
  53864. var min = BABYLON.Vector3.Zero();
  53865. var max = BABYLON.Vector3.Zero();
  53866. var distance = Number.MAX_VALUE;
  53867. var currentSprite = null;
  53868. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53869. var cameraView = camera.getViewMatrix();
  53870. for (var index = 0; index < count; index++) {
  53871. var sprite = this.sprites[index];
  53872. if (!sprite) {
  53873. continue;
  53874. }
  53875. if (predicate) {
  53876. if (!predicate(sprite)) {
  53877. continue;
  53878. }
  53879. }
  53880. else if (!sprite.isPickable) {
  53881. continue;
  53882. }
  53883. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53884. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53885. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53886. if (ray.intersectsBoxMinMax(min, max)) {
  53887. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53888. if (distance > currentDistance) {
  53889. distance = currentDistance;
  53890. currentSprite = sprite;
  53891. if (fastCheck) {
  53892. break;
  53893. }
  53894. }
  53895. }
  53896. }
  53897. if (currentSprite) {
  53898. var result = new BABYLON.PickingInfo();
  53899. result.hit = true;
  53900. result.pickedSprite = currentSprite;
  53901. result.distance = distance;
  53902. return result;
  53903. }
  53904. return null;
  53905. };
  53906. SpriteManager.prototype.render = function () {
  53907. // Check
  53908. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53909. return;
  53910. var engine = this._scene.getEngine();
  53911. var baseSize = this._spriteTexture.getBaseSize();
  53912. // Sprites
  53913. var deltaTime = engine.getDeltaTime();
  53914. var max = Math.min(this._capacity, this.sprites.length);
  53915. var rowSize = baseSize.width / this.cellWidth;
  53916. var offset = 0;
  53917. for (var index = 0; index < max; index++) {
  53918. var sprite = this.sprites[index];
  53919. if (!sprite || !sprite.isVisible) {
  53920. continue;
  53921. }
  53922. sprite._animate(deltaTime);
  53923. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53924. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53925. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53926. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53927. }
  53928. this._buffer.update(this._vertexData);
  53929. // Render
  53930. var effect = this._effectBase;
  53931. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53932. effect = this._effectFog;
  53933. }
  53934. engine.enableEffect(effect);
  53935. var viewMatrix = this._scene.getViewMatrix();
  53936. effect.setTexture("diffuseSampler", this._spriteTexture);
  53937. effect.setMatrix("view", viewMatrix);
  53938. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53939. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53940. // Fog
  53941. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53942. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53943. effect.setColor3("vFogColor", this._scene.fogColor);
  53944. }
  53945. // VBOs
  53946. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53947. // Draw order
  53948. engine.setDepthFunctionToLessOrEqual();
  53949. effect.setBool("alphaTest", true);
  53950. engine.setColorWrite(false);
  53951. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53952. engine.setColorWrite(true);
  53953. effect.setBool("alphaTest", false);
  53954. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53955. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53956. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53957. };
  53958. SpriteManager.prototype.dispose = function () {
  53959. if (this._buffer) {
  53960. this._buffer.dispose();
  53961. this._buffer = null;
  53962. }
  53963. if (this._indexBuffer) {
  53964. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53965. this._indexBuffer = null;
  53966. }
  53967. if (this._spriteTexture) {
  53968. this._spriteTexture.dispose();
  53969. this._spriteTexture = null;
  53970. }
  53971. // Remove from scene
  53972. var index = this._scene.spriteManagers.indexOf(this);
  53973. this._scene.spriteManagers.splice(index, 1);
  53974. // Callback
  53975. this.onDisposeObservable.notifyObservers(this);
  53976. this.onDisposeObservable.clear();
  53977. };
  53978. return SpriteManager;
  53979. }());
  53980. BABYLON.SpriteManager = SpriteManager;
  53981. })(BABYLON || (BABYLON = {}));
  53982. //# sourceMappingURL=babylon.spriteManager.js.map
  53983. var BABYLON;
  53984. (function (BABYLON) {
  53985. var Sprite = /** @class */ (function () {
  53986. function Sprite(name, manager) {
  53987. this.name = name;
  53988. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53989. this.width = 1.0;
  53990. this.height = 1.0;
  53991. this.angle = 0;
  53992. this.cellIndex = 0;
  53993. this.invertU = 0;
  53994. this.invertV = 0;
  53995. this.animations = new Array();
  53996. this.isPickable = false;
  53997. this._animationStarted = false;
  53998. this._loopAnimation = false;
  53999. this._fromIndex = 0;
  54000. this._toIndex = 0;
  54001. this._delay = 0;
  54002. this._direction = 1;
  54003. this._time = 0;
  54004. /**
  54005. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54006. */
  54007. this.isVisible = true;
  54008. this._manager = manager;
  54009. this._manager.sprites.push(this);
  54010. this.position = BABYLON.Vector3.Zero();
  54011. }
  54012. Object.defineProperty(Sprite.prototype, "size", {
  54013. get: function () {
  54014. return this.width;
  54015. },
  54016. set: function (value) {
  54017. this.width = value;
  54018. this.height = value;
  54019. },
  54020. enumerable: true,
  54021. configurable: true
  54022. });
  54023. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54024. this._fromIndex = from;
  54025. this._toIndex = to;
  54026. this._loopAnimation = loop;
  54027. this._delay = delay;
  54028. this._animationStarted = true;
  54029. this._direction = from < to ? 1 : -1;
  54030. this.cellIndex = from;
  54031. this._time = 0;
  54032. this._onAnimationEnd = onAnimationEnd;
  54033. };
  54034. Sprite.prototype.stopAnimation = function () {
  54035. this._animationStarted = false;
  54036. };
  54037. /** @hidden */
  54038. Sprite.prototype._animate = function (deltaTime) {
  54039. if (!this._animationStarted)
  54040. return;
  54041. this._time += deltaTime;
  54042. if (this._time > this._delay) {
  54043. this._time = this._time % this._delay;
  54044. this.cellIndex += this._direction;
  54045. if (this.cellIndex > this._toIndex) {
  54046. if (this._loopAnimation) {
  54047. this.cellIndex = this._fromIndex;
  54048. }
  54049. else {
  54050. this.cellIndex = this._toIndex;
  54051. this._animationStarted = false;
  54052. if (this._onAnimationEnd) {
  54053. this._onAnimationEnd();
  54054. }
  54055. if (this.disposeWhenFinishedAnimating) {
  54056. this.dispose();
  54057. }
  54058. }
  54059. }
  54060. }
  54061. };
  54062. Sprite.prototype.dispose = function () {
  54063. for (var i = 0; i < this._manager.sprites.length; i++) {
  54064. if (this._manager.sprites[i] == this) {
  54065. this._manager.sprites.splice(i, 1);
  54066. }
  54067. }
  54068. };
  54069. return Sprite;
  54070. }());
  54071. BABYLON.Sprite = Sprite;
  54072. })(BABYLON || (BABYLON = {}));
  54073. //# sourceMappingURL=babylon.sprite.js.map
  54074. var BABYLON;
  54075. (function (BABYLON) {
  54076. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  54077. if (!BABYLON.PickingInfo) {
  54078. return null;
  54079. }
  54080. var pickingInfo = null;
  54081. if (!camera) {
  54082. if (!this.activeCamera) {
  54083. return null;
  54084. }
  54085. camera = this.activeCamera;
  54086. }
  54087. if (this.spriteManagers.length > 0) {
  54088. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  54089. var spriteManager = this.spriteManagers[spriteIndex];
  54090. if (!spriteManager.isPickable) {
  54091. continue;
  54092. }
  54093. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  54094. if (!result || !result.hit)
  54095. continue;
  54096. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  54097. continue;
  54098. pickingInfo = result;
  54099. if (fastCheck) {
  54100. break;
  54101. }
  54102. }
  54103. }
  54104. return pickingInfo || new BABYLON.PickingInfo();
  54105. };
  54106. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  54107. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  54108. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54109. };
  54110. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  54111. if (!this._tempSpritePickingRay) {
  54112. return null;
  54113. }
  54114. if (!camera) {
  54115. if (!this.activeCamera) {
  54116. return null;
  54117. }
  54118. camera = this.activeCamera;
  54119. }
  54120. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  54121. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54122. };
  54123. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  54124. if (this._pointerOverSprite === sprite) {
  54125. return;
  54126. }
  54127. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54128. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54129. }
  54130. this._pointerOverSprite = sprite;
  54131. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54132. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54133. }
  54134. };
  54135. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  54136. return this._pointerOverSprite;
  54137. };
  54138. /**
  54139. * Defines the sprite scene component responsible to manage sprites
  54140. * in a given scene.
  54141. */
  54142. var SpriteSceneComponent = /** @class */ (function () {
  54143. /**
  54144. * Creates a new instance of the component for the given scene
  54145. * @param scene Defines the scene to register the component in
  54146. */
  54147. function SpriteSceneComponent(scene) {
  54148. /**
  54149. * The component name helpfull to identify the component in the list of scene components.
  54150. */
  54151. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  54152. this.scene = scene;
  54153. this.scene.spriteManagers = new Array();
  54154. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  54155. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  54156. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  54157. this._spritePredicate = function (sprite) {
  54158. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  54159. };
  54160. }
  54161. /**
  54162. * Registers the component in a given scene
  54163. */
  54164. SpriteSceneComponent.prototype.register = function () {
  54165. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  54166. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  54167. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  54168. };
  54169. /**
  54170. * Rebuilds the elements related to this component in case of
  54171. * context lost for instance.
  54172. */
  54173. SpriteSceneComponent.prototype.rebuild = function () {
  54174. /** Nothing to do for sprites */
  54175. };
  54176. /**
  54177. * Disposes the component and the associated ressources.
  54178. */
  54179. SpriteSceneComponent.prototype.dispose = function () {
  54180. this.scene.onBeforeSpritesRenderingObservable.clear();
  54181. this.scene.onAfterSpritesRenderingObservable.clear();
  54182. var spriteManagers = this.scene.spriteManagers;
  54183. while (spriteManagers.length) {
  54184. spriteManagers[0].dispose();
  54185. }
  54186. };
  54187. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  54188. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  54189. if (result) {
  54190. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  54191. }
  54192. return result;
  54193. };
  54194. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  54195. var scene = this.scene;
  54196. if (isMeshPicked) {
  54197. scene.setPointerOverSprite(null);
  54198. }
  54199. else {
  54200. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  54201. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54202. scene.setPointerOverSprite(pickResult.pickedSprite);
  54203. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  54204. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  54205. }
  54206. else {
  54207. canvas.style.cursor = scene.hoverCursor;
  54208. }
  54209. }
  54210. else {
  54211. scene.setPointerOverSprite(null);
  54212. }
  54213. }
  54214. return pickResult;
  54215. };
  54216. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54217. var scene = this.scene;
  54218. scene._pickedDownSprite = null;
  54219. if (scene.spriteManagers.length > 0) {
  54220. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54221. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54222. if (pickResult.pickedSprite.actionManager) {
  54223. scene._pickedDownSprite = pickResult.pickedSprite;
  54224. switch (evt.button) {
  54225. case 0:
  54226. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54227. break;
  54228. case 1:
  54229. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54230. break;
  54231. case 2:
  54232. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54233. break;
  54234. }
  54235. if (pickResult.pickedSprite.actionManager) {
  54236. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54237. }
  54238. }
  54239. }
  54240. }
  54241. return pickResult;
  54242. };
  54243. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54244. var scene = this.scene;
  54245. if (scene.spriteManagers.length > 0) {
  54246. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54247. if (spritePickResult) {
  54248. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  54249. if (spritePickResult.pickedSprite.actionManager) {
  54250. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54251. if (spritePickResult.pickedSprite.actionManager) {
  54252. if (!this.scene._isPointerSwiping()) {
  54253. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54254. }
  54255. }
  54256. }
  54257. }
  54258. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  54259. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  54260. }
  54261. }
  54262. }
  54263. return pickResult;
  54264. };
  54265. return SpriteSceneComponent;
  54266. }());
  54267. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  54268. })(BABYLON || (BABYLON = {}));
  54269. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  54270. var BABYLON;
  54271. (function (BABYLON) {
  54272. var IntersectionInfo = /** @class */ (function () {
  54273. function IntersectionInfo(bu, bv, distance) {
  54274. this.bu = bu;
  54275. this.bv = bv;
  54276. this.distance = distance;
  54277. this.faceId = 0;
  54278. this.subMeshId = 0;
  54279. }
  54280. return IntersectionInfo;
  54281. }());
  54282. BABYLON.IntersectionInfo = IntersectionInfo;
  54283. /**
  54284. * Information about the result of picking within a scene
  54285. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54286. */
  54287. var PickingInfo = /** @class */ (function () {
  54288. function PickingInfo() {
  54289. /**
  54290. * If the pick collided with an object
  54291. */
  54292. this.hit = false;
  54293. /**
  54294. * Distance away where the pick collided
  54295. */
  54296. this.distance = 0;
  54297. /**
  54298. * The location of pick collision
  54299. */
  54300. this.pickedPoint = null;
  54301. /**
  54302. * The mesh corresponding the the pick collision
  54303. */
  54304. this.pickedMesh = null;
  54305. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54306. this.bu = 0;
  54307. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54308. this.bv = 0;
  54309. /** The id of the face on the mesh that was picked */
  54310. this.faceId = -1;
  54311. /** Id of the the submesh that was picked */
  54312. this.subMeshId = 0;
  54313. /** If a sprite was picked, this will be the sprite the pick collided with */
  54314. this.pickedSprite = null;
  54315. /**
  54316. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54317. */
  54318. this.originMesh = null;
  54319. /**
  54320. * The ray that was used to perform the picking.
  54321. */
  54322. this.ray = null;
  54323. }
  54324. /**
  54325. * Gets the normal correspodning to the face the pick collided with
  54326. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54327. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54328. * @returns The normal correspodning to the face the pick collided with
  54329. */
  54330. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54331. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54332. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54333. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54334. return null;
  54335. }
  54336. var indices = this.pickedMesh.getIndices();
  54337. if (!indices) {
  54338. return null;
  54339. }
  54340. var result;
  54341. if (useVerticesNormals) {
  54342. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54343. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54344. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54345. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54346. normal0 = normal0.scale(this.bu);
  54347. normal1 = normal1.scale(this.bv);
  54348. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54349. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54350. }
  54351. else {
  54352. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54353. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54354. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54355. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54356. var p1p2 = vertex1.subtract(vertex2);
  54357. var p3p2 = vertex3.subtract(vertex2);
  54358. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54359. }
  54360. if (useWorldCoordinates) {
  54361. var wm = this.pickedMesh.getWorldMatrix();
  54362. if (this.pickedMesh.nonUniformScaling) {
  54363. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54364. wm = BABYLON.Tmp.Matrix[0];
  54365. wm.setTranslationFromFloats(0, 0, 0);
  54366. wm.invert();
  54367. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54368. wm = BABYLON.Tmp.Matrix[1];
  54369. }
  54370. result = BABYLON.Vector3.TransformNormal(result, wm);
  54371. }
  54372. result.normalize();
  54373. return result;
  54374. };
  54375. /**
  54376. * Gets the texture coordinates of where the pick occured
  54377. * @returns the vector containing the coordnates of the texture
  54378. */
  54379. PickingInfo.prototype.getTextureCoordinates = function () {
  54380. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54381. return null;
  54382. }
  54383. var indices = this.pickedMesh.getIndices();
  54384. if (!indices) {
  54385. return null;
  54386. }
  54387. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54388. if (!uvs) {
  54389. return null;
  54390. }
  54391. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54392. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54393. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54394. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54395. uv1 = uv1.scale(this.bu);
  54396. uv2 = uv2.scale(this.bv);
  54397. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54398. };
  54399. return PickingInfo;
  54400. }());
  54401. BABYLON.PickingInfo = PickingInfo;
  54402. })(BABYLON || (BABYLON = {}));
  54403. //# sourceMappingURL=babylon.pickingInfo.js.map
  54404. var BABYLON;
  54405. (function (BABYLON) {
  54406. var Ray = /** @class */ (function () {
  54407. function Ray(origin, direction, length) {
  54408. if (length === void 0) { length = Number.MAX_VALUE; }
  54409. this.origin = origin;
  54410. this.direction = direction;
  54411. this.length = length;
  54412. }
  54413. // Methods
  54414. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54415. var d = 0.0;
  54416. var maxValue = Number.MAX_VALUE;
  54417. var inv;
  54418. var min;
  54419. var max;
  54420. var temp;
  54421. if (Math.abs(this.direction.x) < 0.0000001) {
  54422. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54423. return false;
  54424. }
  54425. }
  54426. else {
  54427. inv = 1.0 / this.direction.x;
  54428. min = (minimum.x - this.origin.x) * inv;
  54429. max = (maximum.x - this.origin.x) * inv;
  54430. if (max === -Infinity) {
  54431. max = Infinity;
  54432. }
  54433. if (min > max) {
  54434. temp = min;
  54435. min = max;
  54436. max = temp;
  54437. }
  54438. d = Math.max(min, d);
  54439. maxValue = Math.min(max, maxValue);
  54440. if (d > maxValue) {
  54441. return false;
  54442. }
  54443. }
  54444. if (Math.abs(this.direction.y) < 0.0000001) {
  54445. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54446. return false;
  54447. }
  54448. }
  54449. else {
  54450. inv = 1.0 / this.direction.y;
  54451. min = (minimum.y - this.origin.y) * inv;
  54452. max = (maximum.y - this.origin.y) * inv;
  54453. if (max === -Infinity) {
  54454. max = Infinity;
  54455. }
  54456. if (min > max) {
  54457. temp = min;
  54458. min = max;
  54459. max = temp;
  54460. }
  54461. d = Math.max(min, d);
  54462. maxValue = Math.min(max, maxValue);
  54463. if (d > maxValue) {
  54464. return false;
  54465. }
  54466. }
  54467. if (Math.abs(this.direction.z) < 0.0000001) {
  54468. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54469. return false;
  54470. }
  54471. }
  54472. else {
  54473. inv = 1.0 / this.direction.z;
  54474. min = (minimum.z - this.origin.z) * inv;
  54475. max = (maximum.z - this.origin.z) * inv;
  54476. if (max === -Infinity) {
  54477. max = Infinity;
  54478. }
  54479. if (min > max) {
  54480. temp = min;
  54481. min = max;
  54482. max = temp;
  54483. }
  54484. d = Math.max(min, d);
  54485. maxValue = Math.min(max, maxValue);
  54486. if (d > maxValue) {
  54487. return false;
  54488. }
  54489. }
  54490. return true;
  54491. };
  54492. Ray.prototype.intersectsBox = function (box) {
  54493. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54494. };
  54495. Ray.prototype.intersectsSphere = function (sphere) {
  54496. var x = sphere.center.x - this.origin.x;
  54497. var y = sphere.center.y - this.origin.y;
  54498. var z = sphere.center.z - this.origin.z;
  54499. var pyth = (x * x) + (y * y) + (z * z);
  54500. var rr = sphere.radius * sphere.radius;
  54501. if (pyth <= rr) {
  54502. return true;
  54503. }
  54504. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54505. if (dot < 0.0) {
  54506. return false;
  54507. }
  54508. var temp = pyth - (dot * dot);
  54509. return temp <= rr;
  54510. };
  54511. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54512. if (!this._edge1) {
  54513. this._edge1 = BABYLON.Vector3.Zero();
  54514. this._edge2 = BABYLON.Vector3.Zero();
  54515. this._pvec = BABYLON.Vector3.Zero();
  54516. this._tvec = BABYLON.Vector3.Zero();
  54517. this._qvec = BABYLON.Vector3.Zero();
  54518. }
  54519. vertex1.subtractToRef(vertex0, this._edge1);
  54520. vertex2.subtractToRef(vertex0, this._edge2);
  54521. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54522. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54523. if (det === 0) {
  54524. return null;
  54525. }
  54526. var invdet = 1 / det;
  54527. this.origin.subtractToRef(vertex0, this._tvec);
  54528. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54529. if (bu < 0 || bu > 1.0) {
  54530. return null;
  54531. }
  54532. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54533. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54534. if (bv < 0 || bu + bv > 1.0) {
  54535. return null;
  54536. }
  54537. //check if the distance is longer than the predefined length.
  54538. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54539. if (distance > this.length) {
  54540. return null;
  54541. }
  54542. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54543. };
  54544. Ray.prototype.intersectsPlane = function (plane) {
  54545. var distance;
  54546. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54547. if (Math.abs(result1) < 9.99999997475243E-07) {
  54548. return null;
  54549. }
  54550. else {
  54551. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54552. distance = (-plane.d - result2) / result1;
  54553. if (distance < 0.0) {
  54554. if (distance < -9.99999997475243E-07) {
  54555. return null;
  54556. }
  54557. else {
  54558. return 0;
  54559. }
  54560. }
  54561. return distance;
  54562. }
  54563. };
  54564. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54565. var tm = BABYLON.Tmp.Matrix[0];
  54566. mesh.getWorldMatrix().invertToRef(tm);
  54567. if (this._tmpRay) {
  54568. Ray.TransformToRef(this, tm, this._tmpRay);
  54569. }
  54570. else {
  54571. this._tmpRay = Ray.Transform(this, tm);
  54572. }
  54573. return mesh.intersects(this._tmpRay, fastCheck);
  54574. };
  54575. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54576. if (results) {
  54577. results.length = 0;
  54578. }
  54579. else {
  54580. results = [];
  54581. }
  54582. for (var i = 0; i < meshes.length; i++) {
  54583. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54584. if (pickInfo.hit) {
  54585. results.push(pickInfo);
  54586. }
  54587. }
  54588. results.sort(this._comparePickingInfo);
  54589. return results;
  54590. };
  54591. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54592. if (pickingInfoA.distance < pickingInfoB.distance) {
  54593. return -1;
  54594. }
  54595. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54596. return 1;
  54597. }
  54598. else {
  54599. return 0;
  54600. }
  54601. };
  54602. /**
  54603. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54604. * @param sega the first point of the segment to test the intersection against
  54605. * @param segb the second point of the segment to test the intersection against
  54606. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54607. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54608. */
  54609. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54610. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54611. var u = segb.subtract(sega);
  54612. var v = rsegb.subtract(this.origin);
  54613. var w = sega.subtract(this.origin);
  54614. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54615. var b = BABYLON.Vector3.Dot(u, v);
  54616. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54617. var d = BABYLON.Vector3.Dot(u, w);
  54618. var e = BABYLON.Vector3.Dot(v, w);
  54619. var D = a * c - b * b; // always >= 0
  54620. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54621. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54622. // compute the line parameters of the two closest points
  54623. if (D < Ray.smallnum) { // the lines are almost parallel
  54624. sN = 0.0; // force using point P0 on segment S1
  54625. sD = 1.0; // to prevent possible division by 0.0 later
  54626. tN = e;
  54627. tD = c;
  54628. }
  54629. else { // get the closest points on the infinite lines
  54630. sN = (b * e - c * d);
  54631. tN = (a * e - b * d);
  54632. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54633. sN = 0.0;
  54634. tN = e;
  54635. tD = c;
  54636. }
  54637. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54638. sN = sD;
  54639. tN = e + b;
  54640. tD = c;
  54641. }
  54642. }
  54643. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54644. tN = 0.0;
  54645. // recompute sc for this edge
  54646. if (-d < 0.0) {
  54647. sN = 0.0;
  54648. }
  54649. else if (-d > a)
  54650. sN = sD;
  54651. else {
  54652. sN = -d;
  54653. sD = a;
  54654. }
  54655. }
  54656. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54657. tN = tD;
  54658. // recompute sc for this edge
  54659. if ((-d + b) < 0.0) {
  54660. sN = 0;
  54661. }
  54662. else if ((-d + b) > a) {
  54663. sN = sD;
  54664. }
  54665. else {
  54666. sN = (-d + b);
  54667. sD = a;
  54668. }
  54669. }
  54670. // finally do the division to get sc and tc
  54671. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54672. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54673. // get the difference of the two closest points
  54674. var qtc = v.multiplyByFloats(tc, tc, tc);
  54675. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54676. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54677. if (isIntersected) {
  54678. return qtc.length();
  54679. }
  54680. return -1;
  54681. };
  54682. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54683. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54684. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54685. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54686. this.direction.normalize();
  54687. return this;
  54688. };
  54689. // Statics
  54690. Ray.Zero = function () {
  54691. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54692. };
  54693. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54694. var result = Ray.Zero();
  54695. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54696. };
  54697. /**
  54698. * 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
  54699. * transformed to the given world matrix.
  54700. * @param origin The origin point
  54701. * @param end The end point
  54702. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54703. */
  54704. Ray.CreateNewFromTo = function (origin, end, world) {
  54705. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54706. var direction = end.subtract(origin);
  54707. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54708. direction.normalize();
  54709. return Ray.Transform(new Ray(origin, direction, length), world);
  54710. };
  54711. Ray.Transform = function (ray, matrix) {
  54712. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54713. Ray.TransformToRef(ray, matrix, result);
  54714. return result;
  54715. };
  54716. Ray.TransformToRef = function (ray, matrix, result) {
  54717. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54718. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54719. result.length = ray.length;
  54720. var dir = result.direction;
  54721. var len = dir.length();
  54722. if (!(len === 0 || len === 1)) {
  54723. var num = 1.0 / len;
  54724. dir.x *= num;
  54725. dir.y *= num;
  54726. dir.z *= num;
  54727. result.length *= len;
  54728. }
  54729. };
  54730. Ray.smallnum = 0.00000001;
  54731. Ray.rayl = 10e8;
  54732. return Ray;
  54733. }());
  54734. BABYLON.Ray = Ray;
  54735. })(BABYLON || (BABYLON = {}));
  54736. //# sourceMappingURL=babylon.ray.js.map
  54737. var BABYLON;
  54738. (function (BABYLON) {
  54739. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54740. if (boxMin.x > sphereCenter.x + sphereRadius)
  54741. return false;
  54742. if (sphereCenter.x - sphereRadius > boxMax.x)
  54743. return false;
  54744. if (boxMin.y > sphereCenter.y + sphereRadius)
  54745. return false;
  54746. if (sphereCenter.y - sphereRadius > boxMax.y)
  54747. return false;
  54748. if (boxMin.z > sphereCenter.z + sphereRadius)
  54749. return false;
  54750. if (sphereCenter.z - sphereRadius > boxMax.z)
  54751. return false;
  54752. return true;
  54753. };
  54754. var getLowestRoot = (function () {
  54755. var result = { root: 0, found: false };
  54756. return function (a, b, c, maxR) {
  54757. result.root = 0;
  54758. result.found = false;
  54759. var determinant = b * b - 4.0 * a * c;
  54760. if (determinant < 0)
  54761. return result;
  54762. var sqrtD = Math.sqrt(determinant);
  54763. var r1 = (-b - sqrtD) / (2.0 * a);
  54764. var r2 = (-b + sqrtD) / (2.0 * a);
  54765. if (r1 > r2) {
  54766. var temp = r2;
  54767. r2 = r1;
  54768. r1 = temp;
  54769. }
  54770. if (r1 > 0 && r1 < maxR) {
  54771. result.root = r1;
  54772. result.found = true;
  54773. return result;
  54774. }
  54775. if (r2 > 0 && r2 < maxR) {
  54776. result.root = r2;
  54777. result.found = true;
  54778. return result;
  54779. }
  54780. return result;
  54781. };
  54782. })();
  54783. var Collider = /** @class */ (function () {
  54784. function Collider() {
  54785. this._collisionPoint = BABYLON.Vector3.Zero();
  54786. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54787. this._tempVector = BABYLON.Vector3.Zero();
  54788. this._tempVector2 = BABYLON.Vector3.Zero();
  54789. this._tempVector3 = BABYLON.Vector3.Zero();
  54790. this._tempVector4 = BABYLON.Vector3.Zero();
  54791. this._edge = BABYLON.Vector3.Zero();
  54792. this._baseToVertex = BABYLON.Vector3.Zero();
  54793. this._destinationPoint = BABYLON.Vector3.Zero();
  54794. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54795. this._displacementVector = BABYLON.Vector3.Zero();
  54796. /** @hidden */
  54797. this._radius = BABYLON.Vector3.One();
  54798. /** @hidden */
  54799. this._retry = 0;
  54800. /** @hidden */
  54801. this._basePointWorld = BABYLON.Vector3.Zero();
  54802. this._velocityWorld = BABYLON.Vector3.Zero();
  54803. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54804. this._collisionMask = -1;
  54805. }
  54806. Object.defineProperty(Collider.prototype, "collisionMask", {
  54807. get: function () {
  54808. return this._collisionMask;
  54809. },
  54810. set: function (mask) {
  54811. this._collisionMask = !isNaN(mask) ? mask : -1;
  54812. },
  54813. enumerable: true,
  54814. configurable: true
  54815. });
  54816. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54817. /**
  54818. * Gets the plane normal used to compute the sliding response (in local space)
  54819. */
  54820. get: function () {
  54821. return this._slidePlaneNormal;
  54822. },
  54823. enumerable: true,
  54824. configurable: true
  54825. });
  54826. // Methods
  54827. /** @hidden */
  54828. Collider.prototype._initialize = function (source, dir, e) {
  54829. this._velocity = dir;
  54830. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54831. this._basePoint = source;
  54832. source.multiplyToRef(this._radius, this._basePointWorld);
  54833. dir.multiplyToRef(this._radius, this._velocityWorld);
  54834. this._velocityWorldLength = this._velocityWorld.length();
  54835. this._epsilon = e;
  54836. this.collisionFound = false;
  54837. };
  54838. /** @hidden */
  54839. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54840. pa.subtractToRef(point, this._tempVector);
  54841. pb.subtractToRef(point, this._tempVector2);
  54842. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54843. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54844. if (d < 0)
  54845. return false;
  54846. pc.subtractToRef(point, this._tempVector3);
  54847. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54848. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54849. if (d < 0)
  54850. return false;
  54851. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54852. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54853. return d >= 0;
  54854. };
  54855. /** @hidden */
  54856. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54857. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54858. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54859. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54860. return false;
  54861. }
  54862. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54863. return false;
  54864. return true;
  54865. };
  54866. /** @hidden */
  54867. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54868. var t0;
  54869. var embeddedInPlane = false;
  54870. //defensive programming, actually not needed.
  54871. if (!trianglePlaneArray) {
  54872. trianglePlaneArray = [];
  54873. }
  54874. if (!trianglePlaneArray[faceIndex]) {
  54875. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54876. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54877. }
  54878. var trianglePlane = trianglePlaneArray[faceIndex];
  54879. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54880. return;
  54881. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54882. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54883. if (normalDotVelocity == 0) {
  54884. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54885. return;
  54886. embeddedInPlane = true;
  54887. t0 = 0;
  54888. }
  54889. else {
  54890. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54891. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54892. if (t0 > t1) {
  54893. var temp = t1;
  54894. t1 = t0;
  54895. t0 = temp;
  54896. }
  54897. if (t0 > 1.0 || t1 < 0.0)
  54898. return;
  54899. if (t0 < 0)
  54900. t0 = 0;
  54901. if (t0 > 1.0)
  54902. t0 = 1.0;
  54903. }
  54904. this._collisionPoint.copyFromFloats(0, 0, 0);
  54905. var found = false;
  54906. var t = 1.0;
  54907. if (!embeddedInPlane) {
  54908. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54909. this._velocity.scaleToRef(t0, this._tempVector);
  54910. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54911. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54912. found = true;
  54913. t = t0;
  54914. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54915. }
  54916. }
  54917. if (!found) {
  54918. var velocitySquaredLength = this._velocity.lengthSquared();
  54919. var a = velocitySquaredLength;
  54920. this._basePoint.subtractToRef(p1, this._tempVector);
  54921. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54922. var c = this._tempVector.lengthSquared() - 1.0;
  54923. var lowestRoot = getLowestRoot(a, b, c, t);
  54924. if (lowestRoot.found) {
  54925. t = lowestRoot.root;
  54926. found = true;
  54927. this._collisionPoint.copyFrom(p1);
  54928. }
  54929. this._basePoint.subtractToRef(p2, this._tempVector);
  54930. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54931. c = this._tempVector.lengthSquared() - 1.0;
  54932. lowestRoot = getLowestRoot(a, b, c, t);
  54933. if (lowestRoot.found) {
  54934. t = lowestRoot.root;
  54935. found = true;
  54936. this._collisionPoint.copyFrom(p2);
  54937. }
  54938. this._basePoint.subtractToRef(p3, this._tempVector);
  54939. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54940. c = this._tempVector.lengthSquared() - 1.0;
  54941. lowestRoot = getLowestRoot(a, b, c, t);
  54942. if (lowestRoot.found) {
  54943. t = lowestRoot.root;
  54944. found = true;
  54945. this._collisionPoint.copyFrom(p3);
  54946. }
  54947. p2.subtractToRef(p1, this._edge);
  54948. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54949. var edgeSquaredLength = this._edge.lengthSquared();
  54950. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54951. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54952. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54953. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54954. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54955. lowestRoot = getLowestRoot(a, b, c, t);
  54956. if (lowestRoot.found) {
  54957. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54958. if (f >= 0.0 && f <= 1.0) {
  54959. t = lowestRoot.root;
  54960. found = true;
  54961. this._edge.scaleInPlace(f);
  54962. p1.addToRef(this._edge, this._collisionPoint);
  54963. }
  54964. }
  54965. p3.subtractToRef(p2, this._edge);
  54966. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54967. edgeSquaredLength = this._edge.lengthSquared();
  54968. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54969. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54970. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54971. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54972. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54973. lowestRoot = getLowestRoot(a, b, c, t);
  54974. if (lowestRoot.found) {
  54975. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54976. if (f >= 0.0 && f <= 1.0) {
  54977. t = lowestRoot.root;
  54978. found = true;
  54979. this._edge.scaleInPlace(f);
  54980. p2.addToRef(this._edge, this._collisionPoint);
  54981. }
  54982. }
  54983. p1.subtractToRef(p3, this._edge);
  54984. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54985. edgeSquaredLength = this._edge.lengthSquared();
  54986. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54987. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54988. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54989. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54990. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54991. lowestRoot = getLowestRoot(a, b, c, t);
  54992. if (lowestRoot.found) {
  54993. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54994. if (f >= 0.0 && f <= 1.0) {
  54995. t = lowestRoot.root;
  54996. found = true;
  54997. this._edge.scaleInPlace(f);
  54998. p3.addToRef(this._edge, this._collisionPoint);
  54999. }
  55000. }
  55001. }
  55002. if (found) {
  55003. var distToCollision = t * this._velocity.length();
  55004. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55005. if (!this.intersectionPoint) {
  55006. this.intersectionPoint = this._collisionPoint.clone();
  55007. }
  55008. else {
  55009. this.intersectionPoint.copyFrom(this._collisionPoint);
  55010. }
  55011. this._nearestDistance = distToCollision;
  55012. this.collisionFound = true;
  55013. }
  55014. }
  55015. };
  55016. /** @hidden */
  55017. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55018. for (var i = indexStart; i < indexEnd; i += 3) {
  55019. var p1 = pts[indices[i] - decal];
  55020. var p2 = pts[indices[i + 1] - decal];
  55021. var p3 = pts[indices[i + 2] - decal];
  55022. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55023. }
  55024. };
  55025. /** @hidden */
  55026. Collider.prototype._getResponse = function (pos, vel) {
  55027. pos.addToRef(vel, this._destinationPoint);
  55028. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55029. this._basePoint.addToRef(vel, pos);
  55030. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55031. this._slidePlaneNormal.normalize();
  55032. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55033. pos.addInPlace(this._displacementVector);
  55034. this.intersectionPoint.addInPlace(this._displacementVector);
  55035. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55036. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55037. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55038. };
  55039. return Collider;
  55040. }());
  55041. BABYLON.Collider = Collider;
  55042. })(BABYLON || (BABYLON = {}));
  55043. //# sourceMappingURL=babylon.collider.js.map
  55044. var BABYLON;
  55045. (function (BABYLON) {
  55046. //WebWorker code will be inserted to this variable.
  55047. BABYLON.CollisionWorker = "";
  55048. /** Defines supported task for worker process */
  55049. var WorkerTaskType;
  55050. (function (WorkerTaskType) {
  55051. /** Initialization */
  55052. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55053. /** Update of geometry */
  55054. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55055. /** Evaluate collision */
  55056. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55057. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55058. /** Defines kind of replies returned by worker */
  55059. var WorkerReplyType;
  55060. (function (WorkerReplyType) {
  55061. /** Success */
  55062. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55063. /** Unkown error */
  55064. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55065. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55066. var CollisionCoordinatorWorker = /** @class */ (function () {
  55067. function CollisionCoordinatorWorker() {
  55068. var _this = this;
  55069. this._scaledPosition = BABYLON.Vector3.Zero();
  55070. this._scaledVelocity = BABYLON.Vector3.Zero();
  55071. this.onMeshUpdated = function (transformNode) {
  55072. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55073. };
  55074. this.onGeometryUpdated = function (geometry) {
  55075. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55076. };
  55077. this._afterRender = function () {
  55078. if (!_this._init)
  55079. return;
  55080. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55081. return;
  55082. }
  55083. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55084. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55085. if (_this._runningUpdated > 4) {
  55086. return;
  55087. }
  55088. ++_this._runningUpdated;
  55089. var payload = {
  55090. updatedMeshes: _this._addUpdateMeshesList,
  55091. updatedGeometries: _this._addUpdateGeometriesList,
  55092. removedGeometries: _this._toRemoveGeometryArray,
  55093. removedMeshes: _this._toRemoveMeshesArray
  55094. };
  55095. var message = {
  55096. payload: payload,
  55097. taskType: WorkerTaskType.UPDATE
  55098. };
  55099. var serializable = [];
  55100. for (var id in payload.updatedGeometries) {
  55101. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55102. //prepare transferables
  55103. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55104. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55105. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55106. }
  55107. }
  55108. _this._worker.postMessage(message, serializable);
  55109. _this._addUpdateMeshesList = {};
  55110. _this._addUpdateGeometriesList = {};
  55111. _this._toRemoveGeometryArray = [];
  55112. _this._toRemoveMeshesArray = [];
  55113. };
  55114. this._onMessageFromWorker = function (e) {
  55115. var returnData = e.data;
  55116. if (returnData.error != WorkerReplyType.SUCCESS) {
  55117. //TODO what errors can be returned from the worker?
  55118. BABYLON.Tools.Warn("error returned from worker!");
  55119. return;
  55120. }
  55121. switch (returnData.taskType) {
  55122. case WorkerTaskType.INIT:
  55123. _this._init = true;
  55124. //Update the worked with ALL of the scene's current state
  55125. _this._scene.meshes.forEach(function (mesh) {
  55126. _this.onMeshAdded(mesh);
  55127. });
  55128. _this._scene.getGeometries().forEach(function (geometry) {
  55129. _this.onGeometryAdded(geometry);
  55130. });
  55131. break;
  55132. case WorkerTaskType.UPDATE:
  55133. _this._runningUpdated--;
  55134. break;
  55135. case WorkerTaskType.COLLIDE:
  55136. var returnPayload = returnData.payload;
  55137. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55138. return;
  55139. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55140. if (callback) {
  55141. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55142. if (mesh) {
  55143. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55144. }
  55145. }
  55146. //cleanup
  55147. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55148. break;
  55149. }
  55150. };
  55151. this._collisionsCallbackArray = [];
  55152. this._init = false;
  55153. this._runningUpdated = 0;
  55154. this._addUpdateMeshesList = {};
  55155. this._addUpdateGeometriesList = {};
  55156. this._toRemoveGeometryArray = [];
  55157. this._toRemoveMeshesArray = [];
  55158. }
  55159. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55160. if (!this._init)
  55161. return;
  55162. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55163. return;
  55164. position.divideToRef(collider._radius, this._scaledPosition);
  55165. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55166. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55167. var payload = {
  55168. collider: {
  55169. position: this._scaledPosition.asArray(),
  55170. velocity: this._scaledVelocity.asArray(),
  55171. radius: collider._radius.asArray()
  55172. },
  55173. collisionId: collisionIndex,
  55174. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55175. maximumRetry: maximumRetry
  55176. };
  55177. var message = {
  55178. payload: payload,
  55179. taskType: WorkerTaskType.COLLIDE
  55180. };
  55181. this._worker.postMessage(message);
  55182. };
  55183. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55184. this._scene = scene;
  55185. this._scene.registerAfterRender(this._afterRender);
  55186. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55187. this._worker = new Worker(workerUrl);
  55188. this._worker.onmessage = this._onMessageFromWorker;
  55189. var message = {
  55190. payload: {},
  55191. taskType: WorkerTaskType.INIT
  55192. };
  55193. this._worker.postMessage(message);
  55194. };
  55195. CollisionCoordinatorWorker.prototype.destroy = function () {
  55196. this._scene.unregisterAfterRender(this._afterRender);
  55197. this._worker.terminate();
  55198. };
  55199. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55200. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55201. this.onMeshUpdated(mesh);
  55202. };
  55203. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55204. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55205. };
  55206. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55207. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55208. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55209. this.onGeometryUpdated(geometry);
  55210. };
  55211. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55212. this._toRemoveGeometryArray.push(geometry.id);
  55213. };
  55214. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55215. var submeshes = [];
  55216. if (mesh.subMeshes) {
  55217. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55218. var boundingInfo = sm.getBoundingInfo();
  55219. return {
  55220. position: idx,
  55221. verticesStart: sm.verticesStart,
  55222. verticesCount: sm.verticesCount,
  55223. indexStart: sm.indexStart,
  55224. indexCount: sm.indexCount,
  55225. hasMaterial: !!sm.getMaterial(),
  55226. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55227. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55228. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55229. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55230. };
  55231. });
  55232. }
  55233. var geometryId = null;
  55234. if (mesh instanceof BABYLON.Mesh) {
  55235. var geometry = mesh.geometry;
  55236. geometryId = geometry ? geometry.id : null;
  55237. }
  55238. else if (mesh instanceof BABYLON.InstancedMesh) {
  55239. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55240. geometryId = geometry ? geometry.id : null;
  55241. }
  55242. var boundingInfo = mesh.getBoundingInfo();
  55243. return {
  55244. uniqueId: mesh.uniqueId,
  55245. id: mesh.id,
  55246. name: mesh.name,
  55247. geometryId: geometryId,
  55248. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55249. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55250. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55251. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55252. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55253. subMeshes: submeshes,
  55254. checkCollisions: mesh.checkCollisions
  55255. };
  55256. };
  55257. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55258. return {
  55259. id: geometry.id,
  55260. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55261. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55262. indices: new Uint32Array(geometry.getIndices() || []),
  55263. };
  55264. };
  55265. return CollisionCoordinatorWorker;
  55266. }());
  55267. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55268. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55269. function CollisionCoordinatorLegacy() {
  55270. this._scaledPosition = BABYLON.Vector3.Zero();
  55271. this._scaledVelocity = BABYLON.Vector3.Zero();
  55272. this._finalPosition = BABYLON.Vector3.Zero();
  55273. }
  55274. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55275. position.divideToRef(collider._radius, this._scaledPosition);
  55276. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55277. collider.collidedMesh = null;
  55278. collider._retry = 0;
  55279. collider._initialVelocity = this._scaledVelocity;
  55280. collider._initialPosition = this._scaledPosition;
  55281. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55282. this._finalPosition.multiplyInPlace(collider._radius);
  55283. //run the callback
  55284. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55285. };
  55286. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55287. this._scene = scene;
  55288. };
  55289. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55290. //Legacy need no destruction method.
  55291. };
  55292. //No update in legacy mode
  55293. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55294. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55295. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55296. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55297. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55298. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55299. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55300. if (excludedMesh === void 0) { excludedMesh = null; }
  55301. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55302. if (collider._retry >= maximumRetry) {
  55303. finalPosition.copyFrom(position);
  55304. return;
  55305. }
  55306. // Check if this is a mesh else camera or -1
  55307. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55308. collider._initialize(position, velocity, closeDistance);
  55309. // Check all meshes
  55310. for (var index = 0; index < this._scene.meshes.length; index++) {
  55311. var mesh = this._scene.meshes[index];
  55312. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55313. mesh._checkCollision(collider);
  55314. }
  55315. }
  55316. if (!collider.collisionFound) {
  55317. position.addToRef(velocity, finalPosition);
  55318. return;
  55319. }
  55320. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55321. collider._getResponse(position, velocity);
  55322. }
  55323. if (velocity.length() <= closeDistance) {
  55324. finalPosition.copyFrom(position);
  55325. return;
  55326. }
  55327. collider._retry++;
  55328. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55329. };
  55330. return CollisionCoordinatorLegacy;
  55331. }());
  55332. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55333. })(BABYLON || (BABYLON = {}));
  55334. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55335. var BABYLON;
  55336. (function (BABYLON) {
  55337. /**
  55338. * A particle represents one of the element emitted by a particle system.
  55339. * This is mainly define by its coordinates, direction, velocity and age.
  55340. */
  55341. var Particle = /** @class */ (function () {
  55342. /**
  55343. * Creates a new instance Particle
  55344. * @param particleSystem the particle system the particle belongs to
  55345. */
  55346. function Particle(
  55347. /**
  55348. * The particle system the particle belongs to.
  55349. */
  55350. particleSystem) {
  55351. this.particleSystem = particleSystem;
  55352. /**
  55353. * The world position of the particle in the scene.
  55354. */
  55355. this.position = BABYLON.Vector3.Zero();
  55356. /**
  55357. * The world direction of the particle in the scene.
  55358. */
  55359. this.direction = BABYLON.Vector3.Zero();
  55360. /**
  55361. * The color of the particle.
  55362. */
  55363. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55364. /**
  55365. * The color change of the particle per step.
  55366. */
  55367. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55368. /**
  55369. * Defines how long will the life of the particle be.
  55370. */
  55371. this.lifeTime = 1.0;
  55372. /**
  55373. * The current age of the particle.
  55374. */
  55375. this.age = 0;
  55376. /**
  55377. * The current size of the particle.
  55378. */
  55379. this.size = 0;
  55380. /**
  55381. * The current scale of the particle.
  55382. */
  55383. this.scale = new BABYLON.Vector2(1, 1);
  55384. /**
  55385. * The current angle of the particle.
  55386. */
  55387. this.angle = 0;
  55388. /**
  55389. * Defines how fast is the angle changing.
  55390. */
  55391. this.angularSpeed = 0;
  55392. /**
  55393. * Defines the cell index used by the particle to be rendered from a sprite.
  55394. */
  55395. this.cellIndex = 0;
  55396. /** @hidden */
  55397. this._attachedSubEmitters = null;
  55398. /** @hidden */
  55399. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55400. /** @hidden */
  55401. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55402. /** @hidden */
  55403. this._currentSize1 = 0;
  55404. /** @hidden */
  55405. this._currentSize2 = 0;
  55406. /** @hidden */
  55407. this._currentAngularSpeed1 = 0;
  55408. /** @hidden */
  55409. this._currentAngularSpeed2 = 0;
  55410. /** @hidden */
  55411. this._currentVelocity1 = 0;
  55412. /** @hidden */
  55413. this._currentVelocity2 = 0;
  55414. /** @hidden */
  55415. this._currentLimitVelocity1 = 0;
  55416. /** @hidden */
  55417. this._currentLimitVelocity2 = 0;
  55418. /** @hidden */
  55419. this._currentDrag1 = 0;
  55420. /** @hidden */
  55421. this._currentDrag2 = 0;
  55422. this.id = Particle._Count++;
  55423. if (!this.particleSystem.isAnimationSheetEnabled) {
  55424. return;
  55425. }
  55426. this.updateCellInfoFromSystem();
  55427. }
  55428. Particle.prototype.updateCellInfoFromSystem = function () {
  55429. this.cellIndex = this.particleSystem.startSpriteCellID;
  55430. };
  55431. /**
  55432. * Defines how the sprite cell index is updated for the particle
  55433. */
  55434. Particle.prototype.updateCellIndex = function () {
  55435. var offsetAge = this.age;
  55436. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  55437. if (this.particleSystem.spriteRandomStartCell) {
  55438. if (this._randomCellOffset === undefined) {
  55439. this._randomCellOffset = Math.random() * this.lifeTime;
  55440. }
  55441. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  55442. changeSpeed = 1;
  55443. offsetAge = this._randomCellOffset;
  55444. }
  55445. else {
  55446. offsetAge += this._randomCellOffset;
  55447. }
  55448. }
  55449. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55450. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  55451. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55452. };
  55453. /** @hidden */
  55454. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  55455. if (subEmitter.particleSystem.emitter.position) {
  55456. var emitterMesh = subEmitter.particleSystem.emitter;
  55457. emitterMesh.position.copyFrom(this.position);
  55458. if (subEmitter.inheritDirection) {
  55459. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  55460. // Look at using Y as forward
  55461. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  55462. }
  55463. emitterMesh.computeWorldMatrix(true);
  55464. }
  55465. else {
  55466. var emitterPosition = subEmitter.particleSystem.emitter;
  55467. emitterPosition.copyFrom(this.position);
  55468. }
  55469. // Set inheritedVelocityOffset to be used when new particles are created
  55470. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  55471. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  55472. };
  55473. /** @hidden */
  55474. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  55475. var _this = this;
  55476. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  55477. this._attachedSubEmitters.forEach(function (subEmitter) {
  55478. _this, _this._inheritParticleInfoToSubEmitter(subEmitter);
  55479. });
  55480. }
  55481. };
  55482. /** @hidden */
  55483. Particle.prototype._reset = function () {
  55484. this.age = 0;
  55485. this._currentColorGradient = null;
  55486. this._currentSizeGradient = null;
  55487. this._currentAngularSpeedGradient = null;
  55488. this._currentVelocityGradient = null;
  55489. this._currentLimitVelocityGradient = null;
  55490. this._currentDragGradient = null;
  55491. this.cellIndex = this.particleSystem.startSpriteCellID;
  55492. this._randomCellOffset = undefined;
  55493. };
  55494. /**
  55495. * Copy the properties of particle to another one.
  55496. * @param other the particle to copy the information to.
  55497. */
  55498. Particle.prototype.copyTo = function (other) {
  55499. other.position.copyFrom(this.position);
  55500. if (this._initialDirection) {
  55501. if (other._initialDirection) {
  55502. other._initialDirection.copyFrom(this._initialDirection);
  55503. }
  55504. else {
  55505. other._initialDirection = this._initialDirection.clone();
  55506. }
  55507. }
  55508. else {
  55509. other._initialDirection = null;
  55510. }
  55511. other.direction.copyFrom(this.direction);
  55512. other.color.copyFrom(this.color);
  55513. other.colorStep.copyFrom(this.colorStep);
  55514. other.lifeTime = this.lifeTime;
  55515. other.age = this.age;
  55516. other._randomCellOffset = undefined;
  55517. other.size = this.size;
  55518. other.scale.copyFrom(this.scale);
  55519. other.angle = this.angle;
  55520. other.angularSpeed = this.angularSpeed;
  55521. other.particleSystem = this.particleSystem;
  55522. other.cellIndex = this.cellIndex;
  55523. other.id = this.id;
  55524. other._attachedSubEmitters = this._attachedSubEmitters;
  55525. if (this._currentColorGradient) {
  55526. other._currentColorGradient = this._currentColorGradient;
  55527. other._currentColor1.copyFrom(this._currentColor1);
  55528. other._currentColor2.copyFrom(this._currentColor2);
  55529. }
  55530. if (this._currentSizeGradient) {
  55531. other._currentSizeGradient = this._currentSizeGradient;
  55532. other._currentSize1 = this._currentSize1;
  55533. other._currentSize2 = this._currentSize2;
  55534. }
  55535. if (this._currentAngularSpeedGradient) {
  55536. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55537. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55538. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55539. }
  55540. if (this._currentVelocityGradient) {
  55541. other._currentVelocityGradient = this._currentVelocityGradient;
  55542. other._currentVelocity1 = this._currentVelocity1;
  55543. other._currentVelocity2 = this._currentVelocity2;
  55544. }
  55545. if (this._currentLimitVelocityGradient) {
  55546. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55547. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55548. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55549. }
  55550. if (this._currentDragGradient) {
  55551. other._currentDragGradient = this._currentDragGradient;
  55552. other._currentDrag1 = this._currentDrag1;
  55553. other._currentDrag2 = this._currentDrag2;
  55554. }
  55555. if (this.particleSystem.isAnimationSheetEnabled) {
  55556. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55557. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55558. }
  55559. if (this.particleSystem.useRampGradients) {
  55560. other.remapData.copyFrom(this.remapData);
  55561. }
  55562. if (this._randomNoiseCoordinates1) {
  55563. if (other._randomNoiseCoordinates1) {
  55564. other._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  55565. other._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  55566. }
  55567. else {
  55568. other._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  55569. other._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  55570. }
  55571. }
  55572. };
  55573. Particle._Count = 0;
  55574. return Particle;
  55575. }());
  55576. BABYLON.Particle = Particle;
  55577. })(BABYLON || (BABYLON = {}));
  55578. //# sourceMappingURL=babylon.particle.js.map
  55579. var BABYLON;
  55580. (function (BABYLON) {
  55581. /**
  55582. * This represents the base class for particle system in Babylon.
  55583. * 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.
  55584. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55585. * @example https://doc.babylonjs.com/babylon101/particles
  55586. */
  55587. var BaseParticleSystem = /** @class */ (function () {
  55588. /**
  55589. * Instantiates a particle system.
  55590. * 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.
  55591. * @param name The name of the particle system
  55592. */
  55593. function BaseParticleSystem(name) {
  55594. /**
  55595. * List of animations used by the particle system.
  55596. */
  55597. this.animations = [];
  55598. /**
  55599. * The rendering group used by the Particle system to chose when to render.
  55600. */
  55601. this.renderingGroupId = 0;
  55602. /**
  55603. * The emitter represents the Mesh or position we are attaching the particle system to.
  55604. */
  55605. this.emitter = null;
  55606. /**
  55607. * The maximum number of particles to emit per frame
  55608. */
  55609. this.emitRate = 10;
  55610. /**
  55611. * If you want to launch only a few particles at once, that can be done, as well.
  55612. */
  55613. this.manualEmitCount = -1;
  55614. /**
  55615. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55616. */
  55617. this.updateSpeed = 0.01;
  55618. /**
  55619. * The amount of time the particle system is running (depends of the overall update speed).
  55620. */
  55621. this.targetStopDuration = 0;
  55622. /**
  55623. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55624. */
  55625. this.disposeOnStop = false;
  55626. /**
  55627. * Minimum power of emitting particles.
  55628. */
  55629. this.minEmitPower = 1;
  55630. /**
  55631. * Maximum power of emitting particles.
  55632. */
  55633. this.maxEmitPower = 1;
  55634. /**
  55635. * Minimum life time of emitting particles.
  55636. */
  55637. this.minLifeTime = 1;
  55638. /**
  55639. * Maximum life time of emitting particles.
  55640. */
  55641. this.maxLifeTime = 1;
  55642. /**
  55643. * Minimum Size of emitting particles.
  55644. */
  55645. this.minSize = 1;
  55646. /**
  55647. * Maximum Size of emitting particles.
  55648. */
  55649. this.maxSize = 1;
  55650. /**
  55651. * Minimum scale of emitting particles on X axis.
  55652. */
  55653. this.minScaleX = 1;
  55654. /**
  55655. * Maximum scale of emitting particles on X axis.
  55656. */
  55657. this.maxScaleX = 1;
  55658. /**
  55659. * Minimum scale of emitting particles on Y axis.
  55660. */
  55661. this.minScaleY = 1;
  55662. /**
  55663. * Maximum scale of emitting particles on Y axis.
  55664. */
  55665. this.maxScaleY = 1;
  55666. /**
  55667. * Gets or sets the minimal initial rotation in radians.
  55668. */
  55669. this.minInitialRotation = 0;
  55670. /**
  55671. * Gets or sets the maximal initial rotation in radians.
  55672. */
  55673. this.maxInitialRotation = 0;
  55674. /**
  55675. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55676. */
  55677. this.minAngularSpeed = 0;
  55678. /**
  55679. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55680. */
  55681. this.maxAngularSpeed = 0;
  55682. /**
  55683. * The layer mask we are rendering the particles through.
  55684. */
  55685. this.layerMask = 0x0FFFFFFF;
  55686. /**
  55687. * This can help using your own shader to render the particle system.
  55688. * The according effect will be created
  55689. */
  55690. this.customShader = null;
  55691. /**
  55692. * By default particle system starts as soon as they are created. This prevents the
  55693. * automatic start to happen and let you decide when to start emitting particles.
  55694. */
  55695. this.preventAutoStart = false;
  55696. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55697. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55698. /**
  55699. * Callback triggered when the particle animation is ending.
  55700. */
  55701. this.onAnimationEnd = null;
  55702. /**
  55703. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55704. */
  55705. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55706. /**
  55707. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55708. * to override the particles.
  55709. */
  55710. this.forceDepthWrite = false;
  55711. /** 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 */
  55712. this.preWarmCycles = 0;
  55713. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55714. this.preWarmStepOffset = 1;
  55715. /**
  55716. * 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)
  55717. */
  55718. this.spriteCellChangeSpeed = 1;
  55719. /**
  55720. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55721. */
  55722. this.startSpriteCellID = 0;
  55723. /**
  55724. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55725. */
  55726. this.endSpriteCellID = 0;
  55727. /**
  55728. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55729. */
  55730. this.spriteCellWidth = 0;
  55731. /**
  55732. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55733. */
  55734. this.spriteCellHeight = 0;
  55735. /**
  55736. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  55737. */
  55738. this.spriteRandomStartCell = false;
  55739. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55740. this.translationPivot = new BABYLON.Vector2(0, 0);
  55741. /**
  55742. * You can use gravity if you want to give an orientation to your particles.
  55743. */
  55744. this.gravity = BABYLON.Vector3.Zero();
  55745. this._colorGradients = null;
  55746. this._sizeGradients = null;
  55747. this._lifeTimeGradients = null;
  55748. this._angularSpeedGradients = null;
  55749. this._velocityGradients = null;
  55750. this._limitVelocityGradients = null;
  55751. this._dragGradients = null;
  55752. this._emitRateGradients = null;
  55753. this._startSizeGradients = null;
  55754. this._rampGradients = null;
  55755. this._colorRemapGradients = null;
  55756. this._alphaRemapGradients = null;
  55757. /**
  55758. * Defines the delay in milliseconds before starting the system (0 by default)
  55759. */
  55760. this.startDelay = 0;
  55761. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55762. this.limitVelocityDamping = 0.4;
  55763. /**
  55764. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55765. */
  55766. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55767. /**
  55768. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55769. */
  55770. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55771. /**
  55772. * Color the particle will have at the end of its lifetime
  55773. */
  55774. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55775. /**
  55776. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55777. */
  55778. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55779. /**
  55780. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55781. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55782. */
  55783. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55784. this._isBillboardBased = true;
  55785. /**
  55786. * Local cache of defines for image processing.
  55787. */
  55788. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55789. this.id = name;
  55790. this.name = name;
  55791. }
  55792. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55793. /**
  55794. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55795. */
  55796. get: function () {
  55797. return this._isAnimationSheetEnabled;
  55798. },
  55799. set: function (value) {
  55800. if (this._isAnimationSheetEnabled == value) {
  55801. return;
  55802. }
  55803. this._isAnimationSheetEnabled = value;
  55804. this._reset();
  55805. },
  55806. enumerable: true,
  55807. configurable: true
  55808. });
  55809. /**
  55810. * Get hosting scene
  55811. * @returns the scene
  55812. */
  55813. BaseParticleSystem.prototype.getScene = function () {
  55814. return this._scene;
  55815. };
  55816. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  55817. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  55818. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  55819. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  55820. };
  55821. /**
  55822. * Gets the current list of drag gradients.
  55823. * You must use addDragGradient and removeDragGradient to udpate this list
  55824. * @returns the list of drag gradients
  55825. */
  55826. BaseParticleSystem.prototype.getDragGradients = function () {
  55827. return this._dragGradients;
  55828. };
  55829. /**
  55830. * Gets the current list of limit velocity gradients.
  55831. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55832. * @returns the list of limit velocity gradients
  55833. */
  55834. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55835. return this._limitVelocityGradients;
  55836. };
  55837. /**
  55838. * Gets the current list of color gradients.
  55839. * You must use addColorGradient and removeColorGradient to udpate this list
  55840. * @returns the list of color gradients
  55841. */
  55842. BaseParticleSystem.prototype.getColorGradients = function () {
  55843. return this._colorGradients;
  55844. };
  55845. /**
  55846. * Gets the current list of size gradients.
  55847. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55848. * @returns the list of size gradients
  55849. */
  55850. BaseParticleSystem.prototype.getSizeGradients = function () {
  55851. return this._sizeGradients;
  55852. };
  55853. /**
  55854. * Gets the current list of color remap gradients.
  55855. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  55856. * @returns the list of color remap gradients
  55857. */
  55858. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  55859. return this._colorRemapGradients;
  55860. };
  55861. /**
  55862. * Gets the current list of alpha remap gradients.
  55863. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  55864. * @returns the list of alpha remap gradients
  55865. */
  55866. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  55867. return this._alphaRemapGradients;
  55868. };
  55869. /**
  55870. * Gets the current list of life time gradients.
  55871. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55872. * @returns the list of life time gradients
  55873. */
  55874. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55875. return this._lifeTimeGradients;
  55876. };
  55877. /**
  55878. * Gets the current list of angular speed gradients.
  55879. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55880. * @returns the list of angular speed gradients
  55881. */
  55882. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55883. return this._angularSpeedGradients;
  55884. };
  55885. /**
  55886. * Gets the current list of velocity gradients.
  55887. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55888. * @returns the list of velocity gradients
  55889. */
  55890. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55891. return this._velocityGradients;
  55892. };
  55893. /**
  55894. * Gets the current list of start size gradients.
  55895. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  55896. * @returns the list of start size gradients
  55897. */
  55898. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  55899. return this._startSizeGradients;
  55900. };
  55901. /**
  55902. * Gets the current list of emit rate gradients.
  55903. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  55904. * @returns the list of emit rate gradients
  55905. */
  55906. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  55907. return this._emitRateGradients;
  55908. };
  55909. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55910. /**
  55911. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55912. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55913. */
  55914. get: function () {
  55915. if (this.particleEmitterType.direction1) {
  55916. return this.particleEmitterType.direction1;
  55917. }
  55918. return BABYLON.Vector3.Zero();
  55919. },
  55920. set: function (value) {
  55921. if (this.particleEmitterType.direction1) {
  55922. this.particleEmitterType.direction1 = value;
  55923. }
  55924. },
  55925. enumerable: true,
  55926. configurable: true
  55927. });
  55928. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55929. /**
  55930. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55931. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55932. */
  55933. get: function () {
  55934. if (this.particleEmitterType.direction2) {
  55935. return this.particleEmitterType.direction2;
  55936. }
  55937. return BABYLON.Vector3.Zero();
  55938. },
  55939. set: function (value) {
  55940. if (this.particleEmitterType.direction2) {
  55941. this.particleEmitterType.direction2 = value;
  55942. }
  55943. },
  55944. enumerable: true,
  55945. configurable: true
  55946. });
  55947. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55948. /**
  55949. * 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.
  55950. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55951. */
  55952. get: function () {
  55953. if (this.particleEmitterType.minEmitBox) {
  55954. return this.particleEmitterType.minEmitBox;
  55955. }
  55956. return BABYLON.Vector3.Zero();
  55957. },
  55958. set: function (value) {
  55959. if (this.particleEmitterType.minEmitBox) {
  55960. this.particleEmitterType.minEmitBox = value;
  55961. }
  55962. },
  55963. enumerable: true,
  55964. configurable: true
  55965. });
  55966. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55967. /**
  55968. * 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.
  55969. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55970. */
  55971. get: function () {
  55972. if (this.particleEmitterType.maxEmitBox) {
  55973. return this.particleEmitterType.maxEmitBox;
  55974. }
  55975. return BABYLON.Vector3.Zero();
  55976. },
  55977. set: function (value) {
  55978. if (this.particleEmitterType.maxEmitBox) {
  55979. this.particleEmitterType.maxEmitBox = value;
  55980. }
  55981. },
  55982. enumerable: true,
  55983. configurable: true
  55984. });
  55985. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55986. /**
  55987. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55988. */
  55989. get: function () {
  55990. return this._isBillboardBased;
  55991. },
  55992. set: function (value) {
  55993. if (this._isBillboardBased === value) {
  55994. return;
  55995. }
  55996. this._isBillboardBased = value;
  55997. this._reset();
  55998. },
  55999. enumerable: true,
  56000. configurable: true
  56001. });
  56002. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  56003. /**
  56004. * Gets the image processing configuration used either in this material.
  56005. */
  56006. get: function () {
  56007. return this._imageProcessingConfiguration;
  56008. },
  56009. /**
  56010. * Sets the Default image processing configuration used either in the this material.
  56011. *
  56012. * If sets to null, the scene one is in use.
  56013. */
  56014. set: function (value) {
  56015. this._attachImageProcessingConfiguration(value);
  56016. },
  56017. enumerable: true,
  56018. configurable: true
  56019. });
  56020. /**
  56021. * Attaches a new image processing configuration to the Standard Material.
  56022. * @param configuration
  56023. */
  56024. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  56025. if (configuration === this._imageProcessingConfiguration) {
  56026. return;
  56027. }
  56028. // Pick the scene configuration if needed.
  56029. if (!configuration) {
  56030. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  56031. }
  56032. else {
  56033. this._imageProcessingConfiguration = configuration;
  56034. }
  56035. };
  56036. /** @hidden */
  56037. BaseParticleSystem.prototype._reset = function () {
  56038. };
  56039. /** @hidden */
  56040. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  56041. if (!gradients) {
  56042. return this;
  56043. }
  56044. var index = 0;
  56045. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  56046. var valueGradient = gradients_1[_i];
  56047. if (valueGradient.gradient === gradient) {
  56048. gradients.splice(index, 1);
  56049. break;
  56050. }
  56051. index++;
  56052. }
  56053. if (texture) {
  56054. texture.dispose();
  56055. }
  56056. return this;
  56057. };
  56058. /**
  56059. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  56060. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56061. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56062. * @returns the emitter
  56063. */
  56064. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  56065. var particleEmitter = new BABYLON.PointParticleEmitter();
  56066. particleEmitter.direction1 = direction1;
  56067. particleEmitter.direction2 = direction2;
  56068. this.particleEmitterType = particleEmitter;
  56069. return particleEmitter;
  56070. };
  56071. /**
  56072. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  56073. * @param radius The radius of the hemisphere to emit from
  56074. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56075. * @returns the emitter
  56076. */
  56077. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  56078. if (radius === void 0) { radius = 1; }
  56079. if (radiusRange === void 0) { radiusRange = 1; }
  56080. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  56081. this.particleEmitterType = particleEmitter;
  56082. return particleEmitter;
  56083. };
  56084. /**
  56085. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  56086. * @param radius The radius of the sphere to emit from
  56087. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56088. * @returns the emitter
  56089. */
  56090. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56091. if (radius === void 0) { radius = 1; }
  56092. if (radiusRange === void 0) { radiusRange = 1; }
  56093. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56094. this.particleEmitterType = particleEmitter;
  56095. return particleEmitter;
  56096. };
  56097. /**
  56098. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  56099. * @param radius The radius of the sphere to emit from
  56100. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56101. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56102. * @returns the emitter
  56103. */
  56104. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56105. if (radius === void 0) { radius = 1; }
  56106. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56107. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56108. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56109. this.particleEmitterType = particleEmitter;
  56110. return particleEmitter;
  56111. };
  56112. /**
  56113. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  56114. * @param radius The radius of the emission cylinder
  56115. * @param height The height of the emission cylinder
  56116. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  56117. * @param directionRandomizer How much to randomize the particle direction [0-1]
  56118. * @returns the emitter
  56119. */
  56120. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  56121. if (radius === void 0) { radius = 1; }
  56122. if (height === void 0) { height = 1; }
  56123. if (radiusRange === void 0) { radiusRange = 1; }
  56124. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56125. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  56126. this.particleEmitterType = particleEmitter;
  56127. return particleEmitter;
  56128. };
  56129. /**
  56130. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  56131. * @param radius The radius of the cylinder to emit from
  56132. * @param height The height of the emission cylinder
  56133. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  56134. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  56135. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  56136. * @returns the emitter
  56137. */
  56138. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  56139. if (radius === void 0) { radius = 1; }
  56140. if (height === void 0) { height = 1; }
  56141. if (radiusRange === void 0) { radiusRange = 1; }
  56142. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56143. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56144. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  56145. this.particleEmitterType = particleEmitter;
  56146. return particleEmitter;
  56147. };
  56148. /**
  56149. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  56150. * @param radius The radius of the cone to emit from
  56151. * @param angle The base angle of the cone
  56152. * @returns the emitter
  56153. */
  56154. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56155. if (radius === void 0) { radius = 1; }
  56156. if (angle === void 0) { angle = Math.PI / 4; }
  56157. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56158. this.particleEmitterType = particleEmitter;
  56159. return particleEmitter;
  56160. };
  56161. /**
  56162. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56163. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56164. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56165. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56166. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56167. * @returns the emitter
  56168. */
  56169. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56170. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56171. this.particleEmitterType = particleEmitter;
  56172. this.direction1 = direction1;
  56173. this.direction2 = direction2;
  56174. this.minEmitBox = minEmitBox;
  56175. this.maxEmitBox = maxEmitBox;
  56176. return particleEmitter;
  56177. };
  56178. /**
  56179. * Source color is added to the destination color without alpha affecting the result
  56180. */
  56181. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  56182. /**
  56183. * Blend current color and particle color using particle’s alpha
  56184. */
  56185. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  56186. /**
  56187. * Add current color and particle color multiplied by particle’s alpha
  56188. */
  56189. BaseParticleSystem.BLENDMODE_ADD = 2;
  56190. /**
  56191. * Multiply current color with particle color
  56192. */
  56193. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  56194. /**
  56195. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  56196. */
  56197. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  56198. return BaseParticleSystem;
  56199. }());
  56200. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56201. })(BABYLON || (BABYLON = {}));
  56202. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56203. var BABYLON;
  56204. (function (BABYLON) {
  56205. /**
  56206. * This represents a particle system in Babylon.
  56207. * 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.
  56208. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56209. * @example https://doc.babylonjs.com/babylon101/particles
  56210. */
  56211. var ParticleSystem = /** @class */ (function (_super) {
  56212. __extends(ParticleSystem, _super);
  56213. /**
  56214. * Instantiates a particle system.
  56215. * 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.
  56216. * @param name The name of the particle system
  56217. * @param capacity The max number of particles alive at the same time
  56218. * @param scene The scene the particle system belongs to
  56219. * @param customEffect a custom effect used to change the way particles are rendered by default
  56220. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56221. * @param epsilon Offset used to render the particles
  56222. */
  56223. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56224. if (customEffect === void 0) { customEffect = null; }
  56225. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56226. if (epsilon === void 0) { epsilon = 0.01; }
  56227. var _this = _super.call(this, name) || this;
  56228. /**
  56229. * @hidden
  56230. */
  56231. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  56232. /**
  56233. * An event triggered when the system is disposed
  56234. */
  56235. _this.onDisposeObservable = new BABYLON.Observable();
  56236. _this._particles = new Array();
  56237. _this._stockParticles = new Array();
  56238. _this._newPartsExcess = 0;
  56239. _this._vertexBuffers = {};
  56240. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56241. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56242. _this._scaledDirection = BABYLON.Vector3.Zero();
  56243. _this._scaledGravity = BABYLON.Vector3.Zero();
  56244. _this._currentRenderId = -1;
  56245. _this._useInstancing = false;
  56246. _this._started = false;
  56247. _this._stopped = false;
  56248. _this._actualFrame = 0;
  56249. /** @hidden */
  56250. _this._currentEmitRate1 = 0;
  56251. /** @hidden */
  56252. _this._currentEmitRate2 = 0;
  56253. /** @hidden */
  56254. _this._currentStartSize1 = 0;
  56255. /** @hidden */
  56256. _this._currentStartSize2 = 0;
  56257. _this._rawTextureWidth = 256;
  56258. _this._useRampGradients = false;
  56259. /**
  56260. * @hidden
  56261. * If the particle systems emitter should be disposed when the particle system is disposed
  56262. */
  56263. _this._disposeEmitterOnDispose = false;
  56264. // start of sub system methods
  56265. /**
  56266. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56267. * Its lifetime will start back at 0.
  56268. */
  56269. _this.recycleParticle = function (particle) {
  56270. // move particle from activeParticle list to stock particles
  56271. var lastParticle = _this._particles.pop();
  56272. if (lastParticle !== particle) {
  56273. lastParticle.copyTo(particle);
  56274. }
  56275. _this._stockParticles.push(lastParticle);
  56276. };
  56277. _this._createParticle = function () {
  56278. var particle;
  56279. if (_this._stockParticles.length !== 0) {
  56280. particle = _this._stockParticles.pop();
  56281. particle._reset();
  56282. }
  56283. else {
  56284. particle = new BABYLON.Particle(_this);
  56285. }
  56286. // Attach emitters
  56287. if (_this._subEmitters && _this._subEmitters.length > 0) {
  56288. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  56289. particle._attachedSubEmitters = [];
  56290. subEmitters.forEach(function (subEmitter) {
  56291. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  56292. var newEmitter = subEmitter.clone();
  56293. particle._attachedSubEmitters.push(newEmitter);
  56294. newEmitter.particleSystem.start();
  56295. }
  56296. });
  56297. }
  56298. return particle;
  56299. };
  56300. _this._emitFromParticle = function (particle) {
  56301. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  56302. return;
  56303. }
  56304. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  56305. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  56306. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  56307. var subSystem = subEmitter.clone();
  56308. particle._inheritParticleInfoToSubEmitter(subSystem);
  56309. subSystem.particleSystem._rootParticleSystem = _this;
  56310. _this.activeSubSystems.push(subSystem.particleSystem);
  56311. subSystem.particleSystem.start();
  56312. }
  56313. });
  56314. };
  56315. _this._capacity = capacity;
  56316. _this._epsilon = epsilon;
  56317. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56318. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56319. // Setup the default processing configuration to the scene.
  56320. _this._attachImageProcessingConfiguration(null);
  56321. _this._customEffect = customEffect;
  56322. _this._scene.particleSystems.push(_this);
  56323. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56324. _this._createIndexBuffer();
  56325. _this._createVertexBuffers();
  56326. // Default emitter type
  56327. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56328. // Update
  56329. _this.updateFunction = function (particles) {
  56330. var noiseTextureSize = null;
  56331. var noiseTextureData = null;
  56332. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56333. noiseTextureSize = _this.noiseTexture.getSize();
  56334. noiseTextureData = (_this.noiseTexture.getContent());
  56335. }
  56336. var _loop_1 = function () {
  56337. particle = particles[index];
  56338. particle.age += _this._scaledUpdateSpeed;
  56339. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56340. _this._emitFromParticle(particle);
  56341. if (particle._attachedSubEmitters) {
  56342. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56343. subEmitter.particleSystem.disposeOnStop = true;
  56344. subEmitter.particleSystem.stop();
  56345. });
  56346. particle._attachedSubEmitters = null;
  56347. }
  56348. _this.recycleParticle(particle);
  56349. index--;
  56350. return "continue";
  56351. }
  56352. else {
  56353. var ratio = particle.age / particle.lifeTime;
  56354. // Color
  56355. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56356. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56357. if (currentGradient !== particle._currentColorGradient) {
  56358. particle._currentColor1.copyFrom(particle._currentColor2);
  56359. nextGradient.getColorToRef(particle._currentColor2);
  56360. particle._currentColorGradient = currentGradient;
  56361. }
  56362. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56363. });
  56364. }
  56365. else {
  56366. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56367. particle.color.addInPlace(_this._scaledColorStep);
  56368. if (particle.color.a < 0) {
  56369. particle.color.a = 0;
  56370. }
  56371. }
  56372. // Angular speed
  56373. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56374. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56375. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56376. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56377. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56378. particle._currentAngularSpeedGradient = currentGradient;
  56379. }
  56380. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56381. });
  56382. }
  56383. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56384. // Direction
  56385. var directionScale_1 = _this._scaledUpdateSpeed;
  56386. /// Velocity
  56387. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56388. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56389. if (currentGradient !== particle._currentVelocityGradient) {
  56390. particle._currentVelocity1 = particle._currentVelocity2;
  56391. particle._currentVelocity2 = nextGradient.getFactor();
  56392. particle._currentVelocityGradient = currentGradient;
  56393. }
  56394. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56395. });
  56396. }
  56397. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56398. /// Limit velocity
  56399. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56400. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56401. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56402. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56403. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56404. particle._currentLimitVelocityGradient = currentGradient;
  56405. }
  56406. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56407. var currentVelocity = particle.direction.length();
  56408. if (currentVelocity > limitVelocity) {
  56409. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56410. }
  56411. });
  56412. }
  56413. /// Drag
  56414. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56415. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56416. if (currentGradient !== particle._currentDragGradient) {
  56417. particle._currentDrag1 = particle._currentDrag2;
  56418. particle._currentDrag2 = nextGradient.getFactor();
  56419. particle._currentDragGradient = currentGradient;
  56420. }
  56421. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56422. _this._scaledDirection.scaleInPlace(1.0 - drag);
  56423. });
  56424. }
  56425. particle.position.addInPlace(_this._scaledDirection);
  56426. // Noise
  56427. if (noiseTextureData && noiseTextureSize) {
  56428. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56429. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56430. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56431. var force = BABYLON.Tmp.Vector3[0];
  56432. var scaledForce = BABYLON.Tmp.Vector3[1];
  56433. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56434. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56435. particle.direction.addInPlace(scaledForce);
  56436. }
  56437. // Gravity
  56438. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56439. particle.direction.addInPlace(_this._scaledGravity);
  56440. // Size
  56441. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56442. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56443. if (currentGradient !== particle._currentSizeGradient) {
  56444. particle._currentSize1 = particle._currentSize2;
  56445. particle._currentSize2 = nextGradient.getFactor();
  56446. particle._currentSizeGradient = currentGradient;
  56447. }
  56448. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56449. });
  56450. }
  56451. // Remap data
  56452. if (_this._useRampGradients) {
  56453. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  56454. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  56455. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56456. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56457. particle.remapData.x = min;
  56458. particle.remapData.y = max - min;
  56459. });
  56460. }
  56461. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  56462. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  56463. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56464. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56465. particle.remapData.z = min;
  56466. particle.remapData.w = max - min;
  56467. });
  56468. }
  56469. }
  56470. if (_this._isAnimationSheetEnabled) {
  56471. particle.updateCellIndex();
  56472. }
  56473. // Update the position of the attached sub-emitters to match their attached particle
  56474. particle._inheritParticleInfoToSubEmitters();
  56475. }
  56476. };
  56477. var particle;
  56478. for (var index = 0; index < particles.length; index++) {
  56479. _loop_1();
  56480. }
  56481. };
  56482. return _this;
  56483. }
  56484. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56485. /**
  56486. * Sets a callback that will be triggered when the system is disposed
  56487. */
  56488. set: function (callback) {
  56489. if (this._onDisposeObserver) {
  56490. this.onDisposeObservable.remove(this._onDisposeObserver);
  56491. }
  56492. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56493. },
  56494. enumerable: true,
  56495. configurable: true
  56496. });
  56497. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  56498. /** Gets or sets a boolean indicating that ramp gradients must be used
  56499. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  56500. */
  56501. get: function () {
  56502. return this._useRampGradients;
  56503. },
  56504. set: function (value) {
  56505. if (this._useRampGradients === value) {
  56506. return;
  56507. }
  56508. this._useRampGradients = value;
  56509. this._resetEffect();
  56510. },
  56511. enumerable: true,
  56512. configurable: true
  56513. });
  56514. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56515. //end of Sub-emitter
  56516. /**
  56517. * Gets the current list of active particles
  56518. */
  56519. get: function () {
  56520. return this._particles;
  56521. },
  56522. enumerable: true,
  56523. configurable: true
  56524. });
  56525. /**
  56526. * Returns the string "ParticleSystem"
  56527. * @returns a string containing the class name
  56528. */
  56529. ParticleSystem.prototype.getClassName = function () {
  56530. return "ParticleSystem";
  56531. };
  56532. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56533. var newGradient = new BABYLON.FactorGradient();
  56534. newGradient.gradient = gradient;
  56535. newGradient.factor1 = factor;
  56536. newGradient.factor2 = factor2;
  56537. factorGradients.push(newGradient);
  56538. factorGradients.sort(function (a, b) {
  56539. if (a.gradient < b.gradient) {
  56540. return -1;
  56541. }
  56542. else if (a.gradient > b.gradient) {
  56543. return 1;
  56544. }
  56545. return 0;
  56546. });
  56547. };
  56548. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56549. if (!factorGradients) {
  56550. return;
  56551. }
  56552. var index = 0;
  56553. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56554. var factorGradient = factorGradients_1[_i];
  56555. if (factorGradient.gradient === gradient) {
  56556. factorGradients.splice(index, 1);
  56557. break;
  56558. }
  56559. index++;
  56560. }
  56561. };
  56562. /**
  56563. * Adds a new life time gradient
  56564. * @param gradient defines the gradient to use (between 0 and 1)
  56565. * @param factor defines the life time factor to affect to the specified gradient
  56566. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56567. * @returns the current particle system
  56568. */
  56569. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56570. if (!this._lifeTimeGradients) {
  56571. this._lifeTimeGradients = [];
  56572. }
  56573. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56574. return this;
  56575. };
  56576. /**
  56577. * Remove a specific life time gradient
  56578. * @param gradient defines the gradient to remove
  56579. * @returns the current particle system
  56580. */
  56581. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56582. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56583. return this;
  56584. };
  56585. /**
  56586. * Adds a new size gradient
  56587. * @param gradient defines the gradient to use (between 0 and 1)
  56588. * @param factor defines the size factor to affect to the specified gradient
  56589. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56590. * @returns the current particle system
  56591. */
  56592. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56593. if (!this._sizeGradients) {
  56594. this._sizeGradients = [];
  56595. }
  56596. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56597. return this;
  56598. };
  56599. /**
  56600. * Remove a specific size gradient
  56601. * @param gradient defines the gradient to remove
  56602. * @returns the current particle system
  56603. */
  56604. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56605. this._removeFactorGradient(this._sizeGradients, gradient);
  56606. return this;
  56607. };
  56608. /**
  56609. * Adds a new color remap gradient
  56610. * @param gradient defines the gradient to use (between 0 and 1)
  56611. * @param min defines the color remap minimal range
  56612. * @param max defines the color remap maximal range
  56613. * @returns the current particle system
  56614. */
  56615. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  56616. if (!this._colorRemapGradients) {
  56617. this._colorRemapGradients = [];
  56618. }
  56619. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  56620. return this;
  56621. };
  56622. /**
  56623. * Remove a specific color remap gradient
  56624. * @param gradient defines the gradient to remove
  56625. * @returns the current particle system
  56626. */
  56627. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  56628. this._removeFactorGradient(this._colorRemapGradients, gradient);
  56629. return this;
  56630. };
  56631. /**
  56632. * Adds a new alpha remap gradient
  56633. * @param gradient defines the gradient to use (between 0 and 1)
  56634. * @param min defines the alpha remap minimal range
  56635. * @param max defines the alpha remap maximal range
  56636. * @returns the current particle system
  56637. */
  56638. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  56639. if (!this._alphaRemapGradients) {
  56640. this._alphaRemapGradients = [];
  56641. }
  56642. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  56643. return this;
  56644. };
  56645. /**
  56646. * Remove a specific alpha remap gradient
  56647. * @param gradient defines the gradient to remove
  56648. * @returns the current particle system
  56649. */
  56650. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  56651. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  56652. return this;
  56653. };
  56654. /**
  56655. * Adds a new angular speed gradient
  56656. * @param gradient defines the gradient to use (between 0 and 1)
  56657. * @param factor defines the angular speed to affect to the specified gradient
  56658. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56659. * @returns the current particle system
  56660. */
  56661. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56662. if (!this._angularSpeedGradients) {
  56663. this._angularSpeedGradients = [];
  56664. }
  56665. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56666. return this;
  56667. };
  56668. /**
  56669. * Remove a specific angular speed gradient
  56670. * @param gradient defines the gradient to remove
  56671. * @returns the current particle system
  56672. */
  56673. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56674. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56675. return this;
  56676. };
  56677. /**
  56678. * Adds a new velocity gradient
  56679. * @param gradient defines the gradient to use (between 0 and 1)
  56680. * @param factor defines the velocity to affect to the specified gradient
  56681. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56682. * @returns the current particle system
  56683. */
  56684. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56685. if (!this._velocityGradients) {
  56686. this._velocityGradients = [];
  56687. }
  56688. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56689. return this;
  56690. };
  56691. /**
  56692. * Remove a specific velocity gradient
  56693. * @param gradient defines the gradient to remove
  56694. * @returns the current particle system
  56695. */
  56696. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56697. this._removeFactorGradient(this._velocityGradients, gradient);
  56698. return this;
  56699. };
  56700. /**
  56701. * Adds a new limit velocity gradient
  56702. * @param gradient defines the gradient to use (between 0 and 1)
  56703. * @param factor defines the limit velocity value to affect to the specified gradient
  56704. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56705. * @returns the current particle system
  56706. */
  56707. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56708. if (!this._limitVelocityGradients) {
  56709. this._limitVelocityGradients = [];
  56710. }
  56711. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56712. return this;
  56713. };
  56714. /**
  56715. * Remove a specific limit velocity gradient
  56716. * @param gradient defines the gradient to remove
  56717. * @returns the current particle system
  56718. */
  56719. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56720. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56721. return this;
  56722. };
  56723. /**
  56724. * Adds a new drag gradient
  56725. * @param gradient defines the gradient to use (between 0 and 1)
  56726. * @param factor defines the drag value to affect to the specified gradient
  56727. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56728. * @returns the current particle system
  56729. */
  56730. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56731. if (!this._dragGradients) {
  56732. this._dragGradients = [];
  56733. }
  56734. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56735. return this;
  56736. };
  56737. /**
  56738. * Remove a specific drag gradient
  56739. * @param gradient defines the gradient to remove
  56740. * @returns the current particle system
  56741. */
  56742. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56743. this._removeFactorGradient(this._dragGradients, gradient);
  56744. return this;
  56745. };
  56746. /**
  56747. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  56748. * @param gradient defines the gradient to use (between 0 and 1)
  56749. * @param factor defines the emit rate value to affect to the specified gradient
  56750. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56751. * @returns the current particle system
  56752. */
  56753. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  56754. if (!this._emitRateGradients) {
  56755. this._emitRateGradients = [];
  56756. }
  56757. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  56758. if (!this._currentEmitRateGradient) {
  56759. this._currentEmitRateGradient = this._emitRateGradients[0];
  56760. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  56761. this._currentEmitRate2 = this._currentEmitRate1;
  56762. }
  56763. if (this._emitRateGradients.length === 2) {
  56764. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  56765. }
  56766. return this;
  56767. };
  56768. /**
  56769. * Remove a specific emit rate gradient
  56770. * @param gradient defines the gradient to remove
  56771. * @returns the current particle system
  56772. */
  56773. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  56774. this._removeFactorGradient(this._emitRateGradients, gradient);
  56775. return this;
  56776. };
  56777. /**
  56778. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  56779. * @param gradient defines the gradient to use (between 0 and 1)
  56780. * @param factor defines the start size value to affect to the specified gradient
  56781. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56782. * @returns the current particle system
  56783. */
  56784. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  56785. if (!this._startSizeGradients) {
  56786. this._startSizeGradients = [];
  56787. }
  56788. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  56789. if (!this._currentStartSizeGradient) {
  56790. this._currentStartSizeGradient = this._startSizeGradients[0];
  56791. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  56792. this._currentStartSize2 = this._currentStartSize1;
  56793. }
  56794. if (this._startSizeGradients.length === 2) {
  56795. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  56796. }
  56797. return this;
  56798. };
  56799. /**
  56800. * Remove a specific start size gradient
  56801. * @param gradient defines the gradient to remove
  56802. * @returns the current particle system
  56803. */
  56804. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  56805. this._removeFactorGradient(this._emitRateGradients, gradient);
  56806. return this;
  56807. };
  56808. ParticleSystem.prototype._createRampGradientTexture = function () {
  56809. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  56810. return;
  56811. }
  56812. var data = new Uint8Array(this._rawTextureWidth * 4);
  56813. var tmpColor = BABYLON.Tmp.Color3[0];
  56814. for (var x = 0; x < this._rawTextureWidth; x++) {
  56815. var ratio = x / this._rawTextureWidth;
  56816. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  56817. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  56818. data[x * 4] = tmpColor.r * 255;
  56819. data[x * 4 + 1] = tmpColor.g * 255;
  56820. data[x * 4 + 2] = tmpColor.b * 255;
  56821. data[x * 4 + 3] = 255;
  56822. });
  56823. }
  56824. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56825. };
  56826. /**
  56827. * Gets the current list of ramp gradients.
  56828. * You must use addRampGradient and removeRampGradient to udpate this list
  56829. * @returns the list of ramp gradients
  56830. */
  56831. ParticleSystem.prototype.getRampGradients = function () {
  56832. return this._rampGradients;
  56833. };
  56834. /**
  56835. * Adds a new ramp gradient used to remap particle colors
  56836. * @param gradient defines the gradient to use (between 0 and 1)
  56837. * @param color defines the color to affect to the specified gradient
  56838. * @returns the current particle system
  56839. */
  56840. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  56841. if (!this._rampGradients) {
  56842. this._rampGradients = [];
  56843. }
  56844. var rampGradient = new BABYLON.Color3Gradient();
  56845. rampGradient.gradient = gradient;
  56846. rampGradient.color = color;
  56847. this._rampGradients.push(rampGradient);
  56848. this._rampGradients.sort(function (a, b) {
  56849. if (a.gradient < b.gradient) {
  56850. return -1;
  56851. }
  56852. else if (a.gradient > b.gradient) {
  56853. return 1;
  56854. }
  56855. return 0;
  56856. });
  56857. if (this._rampGradientsTexture) {
  56858. this._rampGradientsTexture.dispose();
  56859. this._rampGradientsTexture = null;
  56860. }
  56861. this._createRampGradientTexture();
  56862. return this;
  56863. };
  56864. /**
  56865. * Remove a specific ramp gradient
  56866. * @param gradient defines the gradient to remove
  56867. * @returns the current particle system
  56868. */
  56869. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  56870. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  56871. this._rampGradientsTexture = null;
  56872. if (this._rampGradients && this._rampGradients.length > 0) {
  56873. this._createRampGradientTexture();
  56874. }
  56875. return this;
  56876. };
  56877. /**
  56878. * Adds a new color gradient
  56879. * @param gradient defines the gradient to use (between 0 and 1)
  56880. * @param color defines the color to affect to the specified gradient
  56881. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56882. */
  56883. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56884. if (!this._colorGradients) {
  56885. this._colorGradients = [];
  56886. }
  56887. var colorGradient = new BABYLON.ColorGradient();
  56888. colorGradient.gradient = gradient;
  56889. colorGradient.color1 = color;
  56890. colorGradient.color2 = color2;
  56891. this._colorGradients.push(colorGradient);
  56892. this._colorGradients.sort(function (a, b) {
  56893. if (a.gradient < b.gradient) {
  56894. return -1;
  56895. }
  56896. else if (a.gradient > b.gradient) {
  56897. return 1;
  56898. }
  56899. return 0;
  56900. });
  56901. return this;
  56902. };
  56903. /**
  56904. * Remove a specific color gradient
  56905. * @param gradient defines the gradient to remove
  56906. */
  56907. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56908. if (!this._colorGradients) {
  56909. return this;
  56910. }
  56911. var index = 0;
  56912. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56913. var colorGradient = _a[_i];
  56914. if (colorGradient.gradient === gradient) {
  56915. this._colorGradients.splice(index, 1);
  56916. break;
  56917. }
  56918. index++;
  56919. }
  56920. return this;
  56921. };
  56922. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56923. u = Math.abs(u) * 0.5 + 0.5;
  56924. v = Math.abs(v) * 0.5 + 0.5;
  56925. var wrappedU = ((u * width) % width) | 0;
  56926. var wrappedV = ((v * height) % height) | 0;
  56927. var position = (wrappedU + wrappedV * width) * 4;
  56928. return pixels[position] / 255;
  56929. };
  56930. ParticleSystem.prototype._reset = function () {
  56931. this._resetEffect();
  56932. };
  56933. ParticleSystem.prototype._resetEffect = function () {
  56934. if (this._vertexBuffer) {
  56935. this._vertexBuffer.dispose();
  56936. this._vertexBuffer = null;
  56937. }
  56938. if (this._spriteBuffer) {
  56939. this._spriteBuffer.dispose();
  56940. this._spriteBuffer = null;
  56941. }
  56942. this._createVertexBuffers();
  56943. };
  56944. ParticleSystem.prototype._createVertexBuffers = function () {
  56945. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56946. if (this._isAnimationSheetEnabled) {
  56947. this._vertexBufferSize += 1;
  56948. }
  56949. if (!this._isBillboardBased) {
  56950. this._vertexBufferSize += 3;
  56951. }
  56952. if (this._useRampGradients) {
  56953. this._vertexBufferSize += 4;
  56954. }
  56955. var engine = this._scene.getEngine();
  56956. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56957. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56958. var dataOffset = 0;
  56959. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56960. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56961. dataOffset += 3;
  56962. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56963. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56964. dataOffset += 4;
  56965. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56966. this._vertexBuffers["angle"] = options;
  56967. dataOffset += 1;
  56968. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56969. this._vertexBuffers["size"] = size;
  56970. dataOffset += 2;
  56971. if (this._isAnimationSheetEnabled) {
  56972. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56973. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56974. dataOffset += 1;
  56975. }
  56976. if (!this._isBillboardBased) {
  56977. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56978. this._vertexBuffers["direction"] = directionBuffer;
  56979. dataOffset += 3;
  56980. }
  56981. if (this._useRampGradients) {
  56982. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56983. this._vertexBuffers["remapData"] = rampDataBuffer;
  56984. dataOffset += 4;
  56985. }
  56986. var offsets;
  56987. if (this._useInstancing) {
  56988. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56989. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56990. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56991. }
  56992. else {
  56993. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56994. dataOffset += 2;
  56995. }
  56996. this._vertexBuffers["offset"] = offsets;
  56997. };
  56998. ParticleSystem.prototype._createIndexBuffer = function () {
  56999. if (this._useInstancing) {
  57000. return;
  57001. }
  57002. var indices = [];
  57003. var index = 0;
  57004. for (var count = 0; count < this._capacity; count++) {
  57005. indices.push(index);
  57006. indices.push(index + 1);
  57007. indices.push(index + 2);
  57008. indices.push(index);
  57009. indices.push(index + 2);
  57010. indices.push(index + 3);
  57011. index += 4;
  57012. }
  57013. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  57014. };
  57015. /**
  57016. * Gets the maximum number of particles active at the same time.
  57017. * @returns The max number of active particles.
  57018. */
  57019. ParticleSystem.prototype.getCapacity = function () {
  57020. return this._capacity;
  57021. };
  57022. /**
  57023. * Gets whether there are still active particles in the system.
  57024. * @returns True if it is alive, otherwise false.
  57025. */
  57026. ParticleSystem.prototype.isAlive = function () {
  57027. return this._alive;
  57028. };
  57029. /**
  57030. * Gets if the system has been started. (Note: this will still be true after stop is called)
  57031. * @returns True if it has been started, otherwise false.
  57032. */
  57033. ParticleSystem.prototype.isStarted = function () {
  57034. return this._started;
  57035. };
  57036. /**
  57037. * Starts the particle system and begins to emit
  57038. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  57039. */
  57040. ParticleSystem.prototype.start = function (delay) {
  57041. var _this = this;
  57042. if (delay === void 0) { delay = this.startDelay; }
  57043. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  57044. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  57045. }
  57046. if (delay) {
  57047. setTimeout(function () {
  57048. _this.start(0);
  57049. }, delay);
  57050. return;
  57051. }
  57052. // Convert the subEmitters field to the constant type field _subEmitters
  57053. this._subEmitters = new Array();
  57054. if (this.subEmitters) {
  57055. this.subEmitters.forEach(function (subEmitter) {
  57056. if (subEmitter instanceof ParticleSystem) {
  57057. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  57058. }
  57059. else if (subEmitter instanceof BABYLON.SubEmitter) {
  57060. _this._subEmitters.push([subEmitter]);
  57061. }
  57062. else if (subEmitter instanceof Array) {
  57063. _this._subEmitters.push(subEmitter);
  57064. }
  57065. _this._subEmitters[_this._subEmitters.length - 1].forEach(function (se) {
  57066. if (!(se.particleSystem.emitter instanceof BABYLON.AbstractMesh) && se.inheritDirection) {
  57067. BABYLON.Tools.Warn("subEmitter.inheritDirection is not supported with non-mesh emitter type");
  57068. }
  57069. });
  57070. });
  57071. }
  57072. this._started = true;
  57073. this._stopped = false;
  57074. this._actualFrame = 0;
  57075. if (this._subEmitters && this._subEmitters.length != 0) {
  57076. this.activeSubSystems = new Array();
  57077. }
  57078. if (this.preWarmCycles) {
  57079. var noiseTextureAsProcedural_1 = this.noiseTexture;
  57080. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  57081. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  57082. setTimeout(function () {
  57083. for (var index = 0; index < _this.preWarmCycles; index++) {
  57084. _this.animate(true);
  57085. noiseTextureAsProcedural_1.render();
  57086. }
  57087. });
  57088. });
  57089. }
  57090. else {
  57091. for (var index = 0; index < this.preWarmCycles; index++) {
  57092. this.animate(true);
  57093. }
  57094. }
  57095. }
  57096. };
  57097. /**
  57098. * Stops the particle system.
  57099. * @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.
  57100. */
  57101. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  57102. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  57103. this._stopped = true;
  57104. if (stopSubEmitters) {
  57105. this._stopSubEmitters();
  57106. }
  57107. };
  57108. // animation sheet
  57109. /**
  57110. * Remove all active particles
  57111. */
  57112. ParticleSystem.prototype.reset = function () {
  57113. this._stockParticles = [];
  57114. this._particles = [];
  57115. };
  57116. /**
  57117. * @hidden (for internal use only)
  57118. */
  57119. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  57120. var offset = index * this._vertexBufferSize;
  57121. this._vertexData[offset++] = particle.position.x;
  57122. this._vertexData[offset++] = particle.position.y;
  57123. this._vertexData[offset++] = particle.position.z;
  57124. this._vertexData[offset++] = particle.color.r;
  57125. this._vertexData[offset++] = particle.color.g;
  57126. this._vertexData[offset++] = particle.color.b;
  57127. this._vertexData[offset++] = particle.color.a;
  57128. this._vertexData[offset++] = particle.angle;
  57129. this._vertexData[offset++] = particle.scale.x * particle.size;
  57130. this._vertexData[offset++] = particle.scale.y * particle.size;
  57131. if (this._isAnimationSheetEnabled) {
  57132. this._vertexData[offset++] = particle.cellIndex;
  57133. }
  57134. if (!this._isBillboardBased) {
  57135. if (particle._initialDirection) {
  57136. this._vertexData[offset++] = particle._initialDirection.x;
  57137. this._vertexData[offset++] = particle._initialDirection.y;
  57138. this._vertexData[offset++] = particle._initialDirection.z;
  57139. }
  57140. else {
  57141. this._vertexData[offset++] = particle.direction.x;
  57142. this._vertexData[offset++] = particle.direction.y;
  57143. this._vertexData[offset++] = particle.direction.z;
  57144. }
  57145. }
  57146. if (this._useRampGradients) {
  57147. this._vertexData[offset++] = particle.remapData.x;
  57148. this._vertexData[offset++] = particle.remapData.y;
  57149. this._vertexData[offset++] = particle.remapData.z;
  57150. this._vertexData[offset++] = particle.remapData.w;
  57151. }
  57152. if (!this._useInstancing) {
  57153. if (this._isAnimationSheetEnabled) {
  57154. if (offsetX === 0)
  57155. offsetX = this._epsilon;
  57156. else if (offsetX === 1)
  57157. offsetX = 1 - this._epsilon;
  57158. if (offsetY === 0)
  57159. offsetY = this._epsilon;
  57160. else if (offsetY === 1)
  57161. offsetY = 1 - this._epsilon;
  57162. }
  57163. this._vertexData[offset++] = offsetX;
  57164. this._vertexData[offset++] = offsetY;
  57165. }
  57166. };
  57167. ParticleSystem.prototype._stopSubEmitters = function () {
  57168. if (!this.activeSubSystems) {
  57169. return;
  57170. }
  57171. this.activeSubSystems.forEach(function (subSystem) {
  57172. subSystem.stop(true);
  57173. });
  57174. this.activeSubSystems = new Array();
  57175. };
  57176. ParticleSystem.prototype._removeFromRoot = function () {
  57177. if (!this._rootParticleSystem) {
  57178. return;
  57179. }
  57180. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  57181. if (index !== -1) {
  57182. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  57183. }
  57184. };
  57185. // End of sub system methods
  57186. ParticleSystem.prototype._update = function (newParticles) {
  57187. var _this = this;
  57188. // Update current
  57189. this._alive = this._particles.length > 0;
  57190. if (this.emitter.position) {
  57191. var emitterMesh = this.emitter;
  57192. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  57193. }
  57194. else {
  57195. var emitterPosition = this.emitter;
  57196. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57197. }
  57198. this.updateFunction(this._particles);
  57199. // Add new ones
  57200. var particle;
  57201. var _loop_2 = function () {
  57202. if (this_1._particles.length === this_1._capacity) {
  57203. return "break";
  57204. }
  57205. particle = this_1._createParticle();
  57206. this_1._particles.push(particle);
  57207. // Emitter
  57208. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  57209. if (this_1.startPositionFunction) {
  57210. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  57211. }
  57212. else {
  57213. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  57214. }
  57215. if (this_1.startDirectionFunction) {
  57216. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  57217. }
  57218. else {
  57219. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  57220. }
  57221. if (emitPower === 0) {
  57222. if (!particle._initialDirection) {
  57223. particle._initialDirection = particle.direction.clone();
  57224. }
  57225. else {
  57226. particle._initialDirection.copyFrom(particle.direction);
  57227. }
  57228. }
  57229. else {
  57230. particle._initialDirection = null;
  57231. }
  57232. particle.direction.scaleInPlace(emitPower);
  57233. // Life time
  57234. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  57235. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  57236. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  57237. var factorGradient1 = currentGradient;
  57238. var factorGradient2 = nextGradient;
  57239. var lifeTime1 = factorGradient1.getFactor();
  57240. var lifeTime2 = factorGradient2.getFactor();
  57241. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  57242. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  57243. });
  57244. }
  57245. else {
  57246. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  57247. }
  57248. // Size
  57249. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  57250. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  57251. }
  57252. else {
  57253. particle._currentSizeGradient = this_1._sizeGradients[0];
  57254. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  57255. particle.size = particle._currentSize1;
  57256. if (this_1._sizeGradients.length > 1) {
  57257. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  57258. }
  57259. else {
  57260. particle._currentSize2 = particle._currentSize1;
  57261. }
  57262. }
  57263. // Size and scale
  57264. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  57265. // Adjust scale by start size
  57266. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  57267. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  57268. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  57269. if (currentGradient !== _this._currentStartSizeGradient) {
  57270. _this._currentStartSize1 = _this._currentStartSize2;
  57271. _this._currentStartSize2 = nextGradient.getFactor();
  57272. _this._currentStartSizeGradient = currentGradient;
  57273. }
  57274. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  57275. particle.scale.scaleInPlace(value);
  57276. });
  57277. }
  57278. // Angle
  57279. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  57280. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  57281. }
  57282. else {
  57283. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  57284. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  57285. particle._currentAngularSpeed1 = particle.angularSpeed;
  57286. if (this_1._angularSpeedGradients.length > 1) {
  57287. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  57288. }
  57289. else {
  57290. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  57291. }
  57292. }
  57293. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  57294. // Velocity
  57295. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  57296. particle._currentVelocityGradient = this_1._velocityGradients[0];
  57297. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  57298. if (this_1._velocityGradients.length > 1) {
  57299. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  57300. }
  57301. else {
  57302. particle._currentVelocity2 = particle._currentVelocity1;
  57303. }
  57304. }
  57305. // Limit velocity
  57306. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  57307. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  57308. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  57309. if (this_1._limitVelocityGradients.length > 1) {
  57310. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  57311. }
  57312. else {
  57313. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  57314. }
  57315. }
  57316. // Drag
  57317. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  57318. particle._currentDragGradient = this_1._dragGradients[0];
  57319. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  57320. if (this_1._dragGradients.length > 1) {
  57321. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  57322. }
  57323. else {
  57324. particle._currentDrag2 = particle._currentDrag1;
  57325. }
  57326. }
  57327. // Color
  57328. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  57329. step = BABYLON.Scalar.RandomRange(0, 1.0);
  57330. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  57331. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  57332. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  57333. }
  57334. else {
  57335. particle._currentColorGradient = this_1._colorGradients[0];
  57336. particle._currentColorGradient.getColorToRef(particle.color);
  57337. particle._currentColor1.copyFrom(particle.color);
  57338. if (this_1._colorGradients.length > 1) {
  57339. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  57340. }
  57341. else {
  57342. particle._currentColor2.copyFrom(particle.color);
  57343. }
  57344. }
  57345. // Sheet
  57346. if (this_1._isAnimationSheetEnabled) {
  57347. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  57348. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  57349. }
  57350. // Inherited Velocity
  57351. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  57352. // Ramp
  57353. if (this_1._useRampGradients) {
  57354. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  57355. }
  57356. // Noise texture coordinates
  57357. if (this_1.noiseTexture) {
  57358. if (particle._randomNoiseCoordinates1) {
  57359. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  57360. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  57361. }
  57362. else {
  57363. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  57364. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  57365. }
  57366. }
  57367. // Update the position of the attached sub-emitters to match their attached particle
  57368. particle._inheritParticleInfoToSubEmitters();
  57369. };
  57370. var this_1 = this, step;
  57371. for (var index = 0; index < newParticles; index++) {
  57372. var state_1 = _loop_2();
  57373. if (state_1 === "break")
  57374. break;
  57375. }
  57376. };
  57377. /** @hidden */
  57378. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  57379. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57380. if (isBillboardBased === void 0) { isBillboardBased = false; }
  57381. if (useRampGradients === void 0) { useRampGradients = false; }
  57382. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  57383. if (isAnimationSheetEnabled) {
  57384. attributeNamesOrOptions.push("cellIndex");
  57385. }
  57386. if (!isBillboardBased) {
  57387. attributeNamesOrOptions.push("direction");
  57388. }
  57389. if (useRampGradients) {
  57390. attributeNamesOrOptions.push("remapData");
  57391. }
  57392. return attributeNamesOrOptions;
  57393. };
  57394. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  57395. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57396. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  57397. if (isAnimationSheetEnabled) {
  57398. effectCreationOption.push("particlesInfos");
  57399. }
  57400. return effectCreationOption;
  57401. };
  57402. ParticleSystem.prototype._getEffect = function (blendMode) {
  57403. if (this._customEffect) {
  57404. return this._customEffect;
  57405. }
  57406. ;
  57407. var defines = [];
  57408. if (this._scene.clipPlane) {
  57409. defines.push("#define CLIPPLANE");
  57410. }
  57411. if (this._scene.clipPlane2) {
  57412. defines.push("#define CLIPPLANE2");
  57413. }
  57414. if (this._scene.clipPlane3) {
  57415. defines.push("#define CLIPPLANE3");
  57416. }
  57417. if (this._scene.clipPlane4) {
  57418. defines.push("#define CLIPPLANE4");
  57419. }
  57420. if (this._isAnimationSheetEnabled) {
  57421. defines.push("#define ANIMATESHEET");
  57422. }
  57423. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  57424. defines.push("#define BLENDMULTIPLYMODE");
  57425. }
  57426. if (this._useRampGradients) {
  57427. defines.push("#define RAMPGRADIENT");
  57428. }
  57429. if (this._isBillboardBased) {
  57430. defines.push("#define BILLBOARD");
  57431. switch (this.billboardMode) {
  57432. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57433. defines.push("#define BILLBOARDY");
  57434. break;
  57435. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57436. default:
  57437. break;
  57438. }
  57439. }
  57440. if (this._imageProcessingConfiguration) {
  57441. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  57442. defines.push(this._imageProcessingConfigurationDefines.toString());
  57443. }
  57444. // Effect
  57445. var join = defines.join("\n");
  57446. if (this._cachedDefines !== join) {
  57447. this._cachedDefines = join;
  57448. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased, this._useRampGradients);
  57449. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  57450. var samplers = ["diffuseSampler", "rampSampler"];
  57451. if (BABYLON.ImageProcessingConfiguration) {
  57452. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  57453. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  57454. }
  57455. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  57456. }
  57457. return this._effect;
  57458. };
  57459. /**
  57460. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57461. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57462. */
  57463. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57464. var _this = this;
  57465. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57466. if (!this._started)
  57467. return;
  57468. if (!preWarmOnly) {
  57469. // Check
  57470. if (!this.isReady())
  57471. return;
  57472. if (this._currentRenderId === this._scene.getRenderId()) {
  57473. return;
  57474. }
  57475. this._currentRenderId = this._scene.getRenderId();
  57476. }
  57477. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57478. // Determine the number of particles we need to create
  57479. var newParticles;
  57480. if (this.manualEmitCount > -1) {
  57481. newParticles = this.manualEmitCount;
  57482. this._newPartsExcess = 0;
  57483. this.manualEmitCount = 0;
  57484. }
  57485. else {
  57486. var rate_1 = this.emitRate;
  57487. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  57488. var ratio = this._actualFrame / this.targetStopDuration;
  57489. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  57490. if (currentGradient !== _this._currentEmitRateGradient) {
  57491. _this._currentEmitRate1 = _this._currentEmitRate2;
  57492. _this._currentEmitRate2 = nextGradient.getFactor();
  57493. _this._currentEmitRateGradient = currentGradient;
  57494. }
  57495. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  57496. });
  57497. }
  57498. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  57499. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  57500. }
  57501. if (this._newPartsExcess > 1.0) {
  57502. newParticles += this._newPartsExcess >> 0;
  57503. this._newPartsExcess -= this._newPartsExcess >> 0;
  57504. }
  57505. this._alive = false;
  57506. if (!this._stopped) {
  57507. this._actualFrame += this._scaledUpdateSpeed;
  57508. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57509. this.stop();
  57510. }
  57511. else {
  57512. newParticles = 0;
  57513. }
  57514. this._update(newParticles);
  57515. // Stopped?
  57516. if (this._stopped) {
  57517. if (!this._alive) {
  57518. this._started = false;
  57519. if (this.onAnimationEnd) {
  57520. this.onAnimationEnd();
  57521. }
  57522. if (this.disposeOnStop) {
  57523. this._scene._toBeDisposed.push(this);
  57524. }
  57525. }
  57526. }
  57527. if (!preWarmOnly) {
  57528. // Update VBO
  57529. var offset = 0;
  57530. for (var index = 0; index < this._particles.length; index++) {
  57531. var particle = this._particles[index];
  57532. this._appendParticleVertices(offset, particle);
  57533. offset += this._useInstancing ? 1 : 4;
  57534. }
  57535. if (this._vertexBuffer) {
  57536. this._vertexBuffer.update(this._vertexData);
  57537. }
  57538. }
  57539. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57540. this.stop();
  57541. }
  57542. };
  57543. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57544. this._appendParticleVertex(offset++, particle, 0, 0);
  57545. if (!this._useInstancing) {
  57546. this._appendParticleVertex(offset++, particle, 1, 0);
  57547. this._appendParticleVertex(offset++, particle, 1, 1);
  57548. this._appendParticleVertex(offset++, particle, 0, 1);
  57549. }
  57550. };
  57551. /**
  57552. * Rebuilds the particle system.
  57553. */
  57554. ParticleSystem.prototype.rebuild = function () {
  57555. this._createIndexBuffer();
  57556. if (this._vertexBuffer) {
  57557. this._vertexBuffer._rebuild();
  57558. }
  57559. };
  57560. /**
  57561. * Is this system ready to be used/rendered
  57562. * @return true if the system is ready
  57563. */
  57564. ParticleSystem.prototype.isReady = function () {
  57565. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57566. return false;
  57567. }
  57568. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  57569. if (!this._getEffect(this.blendMode).isReady()) {
  57570. return false;
  57571. }
  57572. }
  57573. else {
  57574. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  57575. return false;
  57576. }
  57577. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  57578. return false;
  57579. }
  57580. }
  57581. return true;
  57582. };
  57583. ParticleSystem.prototype._render = function (blendMode) {
  57584. var effect = this._getEffect(blendMode);
  57585. var engine = this._scene.getEngine();
  57586. // Render
  57587. engine.enableEffect(effect);
  57588. var viewMatrix = this._scene.getViewMatrix();
  57589. effect.setTexture("diffuseSampler", this.particleTexture);
  57590. effect.setMatrix("view", viewMatrix);
  57591. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57592. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57593. var baseSize = this.particleTexture.getBaseSize();
  57594. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57595. }
  57596. effect.setVector2("translationPivot", this.translationPivot);
  57597. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57598. if (this._isBillboardBased) {
  57599. var camera = this._scene.activeCamera;
  57600. effect.setVector3("eyePosition", camera.globalPosition);
  57601. }
  57602. if (this._rampGradientsTexture) {
  57603. effect.setTexture("rampSampler", this._rampGradientsTexture);
  57604. }
  57605. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57606. var invView = viewMatrix.clone();
  57607. invView.invert();
  57608. effect.setMatrix("invView", invView);
  57609. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57610. }
  57611. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57612. // image processing
  57613. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57614. this._imageProcessingConfiguration.bind(effect);
  57615. }
  57616. // Draw order
  57617. switch (blendMode) {
  57618. case ParticleSystem.BLENDMODE_ADD:
  57619. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57620. break;
  57621. case ParticleSystem.BLENDMODE_ONEONE:
  57622. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57623. break;
  57624. case ParticleSystem.BLENDMODE_STANDARD:
  57625. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57626. break;
  57627. case ParticleSystem.BLENDMODE_MULTIPLY:
  57628. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  57629. break;
  57630. }
  57631. if (this._useInstancing) {
  57632. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57633. }
  57634. else {
  57635. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57636. }
  57637. return this._particles.length;
  57638. };
  57639. /**
  57640. * Renders the particle system in its current state.
  57641. * @returns the current number of particles
  57642. */
  57643. ParticleSystem.prototype.render = function () {
  57644. // Check
  57645. if (!this.isReady() || !this._particles.length) {
  57646. return 0;
  57647. }
  57648. var engine = this._scene.getEngine();
  57649. engine.setState(false);
  57650. if (this.forceDepthWrite) {
  57651. engine.setDepthWrite(true);
  57652. }
  57653. var outparticles = 0;
  57654. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  57655. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  57656. }
  57657. outparticles = this._render(this.blendMode);
  57658. engine.unbindInstanceAttributes();
  57659. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57660. return outparticles;
  57661. };
  57662. /**
  57663. * Disposes the particle system and free the associated resources
  57664. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57665. */
  57666. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57667. if (disposeTexture === void 0) { disposeTexture = true; }
  57668. if (this._vertexBuffer) {
  57669. this._vertexBuffer.dispose();
  57670. this._vertexBuffer = null;
  57671. }
  57672. if (this._spriteBuffer) {
  57673. this._spriteBuffer.dispose();
  57674. this._spriteBuffer = null;
  57675. }
  57676. if (this._indexBuffer) {
  57677. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57678. this._indexBuffer = null;
  57679. }
  57680. if (disposeTexture && this.particleTexture) {
  57681. this.particleTexture.dispose();
  57682. this.particleTexture = null;
  57683. }
  57684. if (disposeTexture && this.noiseTexture) {
  57685. this.noiseTexture.dispose();
  57686. this.noiseTexture = null;
  57687. }
  57688. if (this._rampGradientsTexture) {
  57689. this._rampGradientsTexture.dispose();
  57690. this._rampGradientsTexture = null;
  57691. }
  57692. this._removeFromRoot();
  57693. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  57694. this.emitter.dispose(true);
  57695. }
  57696. // Remove from scene
  57697. var index = this._scene.particleSystems.indexOf(this);
  57698. if (index > -1) {
  57699. this._scene.particleSystems.splice(index, 1);
  57700. }
  57701. // Callback
  57702. this.onDisposeObservable.notifyObservers(this);
  57703. this.onDisposeObservable.clear();
  57704. };
  57705. // Clone
  57706. /**
  57707. * Clones the particle system.
  57708. * @param name The name of the cloned object
  57709. * @param newEmitter The new emitter to use
  57710. * @returns the cloned particle system
  57711. */
  57712. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57713. var custom = null;
  57714. var program = null;
  57715. if (this.customShader != null) {
  57716. program = this.customShader;
  57717. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57718. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57719. }
  57720. else if (this._customEffect) {
  57721. custom = this._customEffect;
  57722. }
  57723. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57724. result.customShader = program;
  57725. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  57726. if (newEmitter === undefined) {
  57727. newEmitter = this.emitter;
  57728. }
  57729. result.noiseTexture = this.noiseTexture;
  57730. result.emitter = newEmitter;
  57731. if (this.particleTexture) {
  57732. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57733. }
  57734. // Clone gradients
  57735. if (this._colorGradients) {
  57736. this._colorGradients.forEach(function (v) {
  57737. result.addColorGradient(v.gradient, v.color1, v.color2);
  57738. });
  57739. }
  57740. if (this._dragGradients) {
  57741. this._dragGradients.forEach(function (v) {
  57742. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  57743. });
  57744. }
  57745. if (this._angularSpeedGradients) {
  57746. this._angularSpeedGradients.forEach(function (v) {
  57747. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  57748. });
  57749. }
  57750. if (this._emitRateGradients) {
  57751. this._emitRateGradients.forEach(function (v) {
  57752. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  57753. });
  57754. }
  57755. if (this._lifeTimeGradients) {
  57756. this._lifeTimeGradients.forEach(function (v) {
  57757. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  57758. });
  57759. }
  57760. if (this._limitVelocityGradients) {
  57761. this._limitVelocityGradients.forEach(function (v) {
  57762. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  57763. });
  57764. }
  57765. if (this._sizeGradients) {
  57766. this._sizeGradients.forEach(function (v) {
  57767. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  57768. });
  57769. }
  57770. if (this._startSizeGradients) {
  57771. this._startSizeGradients.forEach(function (v) {
  57772. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  57773. });
  57774. }
  57775. if (this._velocityGradients) {
  57776. this._velocityGradients.forEach(function (v) {
  57777. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  57778. });
  57779. }
  57780. if (this._rampGradients) {
  57781. this._rampGradients.forEach(function (v) {
  57782. result.addRampGradient(v.gradient, v.color);
  57783. });
  57784. }
  57785. if (this._colorRemapGradients) {
  57786. this._colorRemapGradients.forEach(function (v) {
  57787. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  57788. });
  57789. }
  57790. if (this._alphaRemapGradients) {
  57791. this._alphaRemapGradients.forEach(function (v) {
  57792. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  57793. });
  57794. }
  57795. if (!this.preventAutoStart) {
  57796. result.start();
  57797. }
  57798. return result;
  57799. };
  57800. /**
  57801. * Serializes the particle system to a JSON object.
  57802. * @returns the JSON object
  57803. */
  57804. ParticleSystem.prototype.serialize = function () {
  57805. var serializationObject = {};
  57806. ParticleSystem._Serialize(serializationObject, this);
  57807. serializationObject.textureMask = this.textureMask.asArray();
  57808. serializationObject.customShader = this.customShader;
  57809. serializationObject.preventAutoStart = this.preventAutoStart;
  57810. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57811. return serializationObject;
  57812. };
  57813. /** @hidden */
  57814. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57815. serializationObject.name = particleSystem.name;
  57816. serializationObject.id = particleSystem.id;
  57817. serializationObject.capacity = particleSystem.getCapacity();
  57818. // Emitter
  57819. if (particleSystem.emitter.position) {
  57820. var emitterMesh = particleSystem.emitter;
  57821. serializationObject.emitterId = emitterMesh.id;
  57822. }
  57823. else {
  57824. var emitterPosition = particleSystem.emitter;
  57825. serializationObject.emitter = emitterPosition.asArray();
  57826. }
  57827. // Emitter
  57828. if (particleSystem.particleEmitterType) {
  57829. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57830. }
  57831. if (particleSystem.particleTexture) {
  57832. serializationObject.textureName = particleSystem.particleTexture.name;
  57833. }
  57834. // Animations
  57835. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57836. // Particle system
  57837. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57838. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57839. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57840. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57841. serializationObject.minSize = particleSystem.minSize;
  57842. serializationObject.maxSize = particleSystem.maxSize;
  57843. serializationObject.minScaleX = particleSystem.minScaleX;
  57844. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57845. serializationObject.minScaleY = particleSystem.minScaleY;
  57846. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57847. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57848. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57849. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57850. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57851. serializationObject.emitRate = particleSystem.emitRate;
  57852. serializationObject.gravity = particleSystem.gravity.asArray();
  57853. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57854. serializationObject.color1 = particleSystem.color1.asArray();
  57855. serializationObject.color2 = particleSystem.color2.asArray();
  57856. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57857. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57858. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57859. serializationObject.blendMode = particleSystem.blendMode;
  57860. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57861. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57862. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57863. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57864. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57865. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57866. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57867. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57868. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57869. var colorGradients = particleSystem.getColorGradients();
  57870. if (colorGradients) {
  57871. serializationObject.colorGradients = [];
  57872. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57873. var colorGradient = colorGradients_1[_i];
  57874. var serializedGradient = {
  57875. gradient: colorGradient.gradient,
  57876. color1: colorGradient.color1.asArray()
  57877. };
  57878. if (colorGradient.color2) {
  57879. serializedGradient.color2 = colorGradient.color2.asArray();
  57880. }
  57881. serializationObject.colorGradients.push(serializedGradient);
  57882. }
  57883. }
  57884. var rampGradients = particleSystem.getRampGradients();
  57885. if (rampGradients) {
  57886. serializationObject.rampGradients = [];
  57887. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  57888. var rampGradient = rampGradients_1[_a];
  57889. var serializedGradient = {
  57890. gradient: rampGradient.gradient,
  57891. color: rampGradient.color.asArray()
  57892. };
  57893. serializationObject.rampGradients.push(serializedGradient);
  57894. }
  57895. }
  57896. var colorRemapGradients = particleSystem.getColorRemapGradients();
  57897. if (colorRemapGradients) {
  57898. serializationObject.colorRemapGradients = [];
  57899. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  57900. var colorRemapGradient = colorRemapGradients_1[_b];
  57901. var serializedGradient = {
  57902. gradient: colorRemapGradient.gradient,
  57903. factor1: colorRemapGradient.factor1
  57904. };
  57905. if (colorRemapGradient.factor2 !== undefined) {
  57906. serializedGradient.factor2 = colorRemapGradient.factor2;
  57907. }
  57908. serializationObject.colorRemapGradients.push(serializedGradient);
  57909. }
  57910. }
  57911. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  57912. if (alphaRemapGradients) {
  57913. serializationObject.alphaRemapGradients = [];
  57914. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  57915. var alphaRemapGradient = alphaRemapGradients_1[_c];
  57916. var serializedGradient = {
  57917. gradient: alphaRemapGradient.gradient,
  57918. factor1: alphaRemapGradient.factor1
  57919. };
  57920. if (alphaRemapGradient.factor2 !== undefined) {
  57921. serializedGradient.factor2 = alphaRemapGradient.factor2;
  57922. }
  57923. serializationObject.alphaRemapGradients.push(serializedGradient);
  57924. }
  57925. }
  57926. var sizeGradients = particleSystem.getSizeGradients();
  57927. if (sizeGradients) {
  57928. serializationObject.sizeGradients = [];
  57929. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  57930. var sizeGradient = sizeGradients_1[_d];
  57931. var serializedGradient = {
  57932. gradient: sizeGradient.gradient,
  57933. factor1: sizeGradient.factor1
  57934. };
  57935. if (sizeGradient.factor2 !== undefined) {
  57936. serializedGradient.factor2 = sizeGradient.factor2;
  57937. }
  57938. serializationObject.sizeGradients.push(serializedGradient);
  57939. }
  57940. }
  57941. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57942. if (angularSpeedGradients) {
  57943. serializationObject.angularSpeedGradients = [];
  57944. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  57945. var angularSpeedGradient = angularSpeedGradients_1[_e];
  57946. var serializedGradient = {
  57947. gradient: angularSpeedGradient.gradient,
  57948. factor1: angularSpeedGradient.factor1
  57949. };
  57950. if (angularSpeedGradient.factor2 !== undefined) {
  57951. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57952. }
  57953. serializationObject.angularSpeedGradients.push(serializedGradient);
  57954. }
  57955. }
  57956. var velocityGradients = particleSystem.getVelocityGradients();
  57957. if (velocityGradients) {
  57958. serializationObject.velocityGradients = [];
  57959. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  57960. var velocityGradient = velocityGradients_1[_f];
  57961. var serializedGradient = {
  57962. gradient: velocityGradient.gradient,
  57963. factor1: velocityGradient.factor1
  57964. };
  57965. if (velocityGradient.factor2 !== undefined) {
  57966. serializedGradient.factor2 = velocityGradient.factor2;
  57967. }
  57968. serializationObject.velocityGradients.push(serializedGradient);
  57969. }
  57970. }
  57971. var dragGradients = particleSystem.getDragGradients();
  57972. if (dragGradients) {
  57973. serializationObject.dragyGradients = [];
  57974. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  57975. var dragGradient = dragGradients_1[_g];
  57976. var serializedGradient = {
  57977. gradient: dragGradient.gradient,
  57978. factor1: dragGradient.factor1
  57979. };
  57980. if (dragGradient.factor2 !== undefined) {
  57981. serializedGradient.factor2 = dragGradient.factor2;
  57982. }
  57983. serializationObject.dragGradients.push(serializedGradient);
  57984. }
  57985. }
  57986. var emitRateGradients = particleSystem.getEmitRateGradients();
  57987. if (emitRateGradients) {
  57988. serializationObject.emitRateGradients = [];
  57989. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  57990. var emitRateGradient = emitRateGradients_1[_h];
  57991. var serializedGradient = {
  57992. gradient: emitRateGradient.gradient,
  57993. factor1: emitRateGradient.factor1
  57994. };
  57995. if (emitRateGradient.factor2 !== undefined) {
  57996. serializedGradient.factor2 = emitRateGradient.factor2;
  57997. }
  57998. serializationObject.emitRateGradients.push(serializedGradient);
  57999. }
  58000. }
  58001. var startSizeGradients = particleSystem.getStartSizeGradients();
  58002. if (startSizeGradients) {
  58003. serializationObject.startSizeGradients = [];
  58004. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  58005. var startSizeGradient = startSizeGradients_1[_j];
  58006. var serializedGradient = {
  58007. gradient: startSizeGradient.gradient,
  58008. factor1: startSizeGradient.factor1
  58009. };
  58010. if (startSizeGradient.factor2 !== undefined) {
  58011. serializedGradient.factor2 = startSizeGradient.factor2;
  58012. }
  58013. serializationObject.startSizeGradients.push(serializedGradient);
  58014. }
  58015. }
  58016. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  58017. if (limitVelocityGradients) {
  58018. serializationObject.limitVelocityGradients = [];
  58019. for (var _k = 0, limitVelocityGradients_1 = limitVelocityGradients; _k < limitVelocityGradients_1.length; _k++) {
  58020. var limitVelocityGradient = limitVelocityGradients_1[_k];
  58021. var serializedGradient = {
  58022. gradient: limitVelocityGradient.gradient,
  58023. factor1: limitVelocityGradient.factor1
  58024. };
  58025. if (limitVelocityGradient.factor2 !== undefined) {
  58026. serializedGradient.factor2 = limitVelocityGradient.factor2;
  58027. }
  58028. serializationObject.limitVelocityGradients.push(serializedGradient);
  58029. }
  58030. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  58031. }
  58032. if (particleSystem.noiseTexture) {
  58033. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  58034. }
  58035. };
  58036. /** @hidden */
  58037. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  58038. // Texture
  58039. if (parsedParticleSystem.textureName) {
  58040. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58041. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58042. }
  58043. // Emitter
  58044. if (parsedParticleSystem.emitterId === undefined) {
  58045. particleSystem.emitter = BABYLON.Vector3.Zero();
  58046. }
  58047. else if (parsedParticleSystem.emitterId) {
  58048. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58049. }
  58050. else {
  58051. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58052. }
  58053. // Misc.
  58054. if (parsedParticleSystem.renderingGroupId !== undefined) {
  58055. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  58056. }
  58057. if (parsedParticleSystem.isBillboardBased !== undefined) {
  58058. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  58059. }
  58060. // Animations
  58061. if (parsedParticleSystem.animations) {
  58062. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58063. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58064. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58065. }
  58066. }
  58067. if (parsedParticleSystem.autoAnimate) {
  58068. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  58069. }
  58070. // Particle system
  58071. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58072. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58073. particleSystem.minSize = parsedParticleSystem.minSize;
  58074. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58075. if (parsedParticleSystem.minScaleX) {
  58076. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  58077. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  58078. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  58079. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  58080. }
  58081. if (parsedParticleSystem.preWarmCycles !== undefined) {
  58082. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  58083. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  58084. }
  58085. if (parsedParticleSystem.minInitialRotation !== undefined) {
  58086. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  58087. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  58088. }
  58089. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58090. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58091. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58092. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58093. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58094. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58095. if (parsedParticleSystem.noiseStrength) {
  58096. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  58097. }
  58098. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58099. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58100. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58101. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58102. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58103. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58104. if (parsedParticleSystem.colorGradients) {
  58105. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  58106. var colorGradient = _a[_i];
  58107. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  58108. }
  58109. }
  58110. if (parsedParticleSystem.rampGradients) {
  58111. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  58112. var rampGradient = _c[_b];
  58113. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color1));
  58114. }
  58115. }
  58116. if (parsedParticleSystem.colorRemapGradients) {
  58117. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  58118. var colorRemapGradient = _e[_d];
  58119. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  58120. }
  58121. }
  58122. if (parsedParticleSystem.alphaRemapGradients) {
  58123. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  58124. var alphaRemapGradient = _g[_f];
  58125. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  58126. }
  58127. }
  58128. if (parsedParticleSystem.sizeGradients) {
  58129. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  58130. var sizeGradient = _j[_h];
  58131. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  58132. }
  58133. }
  58134. if (parsedParticleSystem.sizeGradients) {
  58135. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  58136. var sizeGradient = _l[_k];
  58137. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  58138. }
  58139. }
  58140. if (parsedParticleSystem.angularSpeedGradients) {
  58141. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  58142. var angularSpeedGradient = _o[_m];
  58143. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  58144. }
  58145. }
  58146. if (parsedParticleSystem.velocityGradients) {
  58147. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  58148. var velocityGradient = _q[_p];
  58149. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  58150. }
  58151. }
  58152. if (parsedParticleSystem.dragGradients) {
  58153. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  58154. var dragGradient = _s[_r];
  58155. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  58156. }
  58157. }
  58158. if (parsedParticleSystem.emitRateGradients) {
  58159. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  58160. var emitRateGradient = _u[_t];
  58161. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  58162. }
  58163. }
  58164. if (parsedParticleSystem.startSizeGradients) {
  58165. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  58166. var startSizeGradient = _w[_v];
  58167. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  58168. }
  58169. }
  58170. if (parsedParticleSystem.limitVelocityGradients) {
  58171. for (var _x = 0, _y = parsedParticleSystem.limitVelocityGradients; _x < _y.length; _x++) {
  58172. var limitVelocityGradient = _y[_x];
  58173. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  58174. }
  58175. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  58176. }
  58177. if (parsedParticleSystem.noiseTexture) {
  58178. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  58179. }
  58180. // Emitter
  58181. var emitterType;
  58182. if (parsedParticleSystem.particleEmitterType) {
  58183. switch (parsedParticleSystem.particleEmitterType.type) {
  58184. case "SphereParticleEmitter":
  58185. emitterType = new BABYLON.SphereParticleEmitter();
  58186. break;
  58187. case "SphereDirectedParticleEmitter":
  58188. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58189. break;
  58190. case "ConeEmitter":
  58191. case "ConeParticleEmitter":
  58192. emitterType = new BABYLON.ConeParticleEmitter();
  58193. break;
  58194. case "BoxEmitter":
  58195. case "BoxParticleEmitter":
  58196. default:
  58197. emitterType = new BABYLON.BoxParticleEmitter();
  58198. break;
  58199. }
  58200. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58201. }
  58202. else {
  58203. emitterType = new BABYLON.BoxParticleEmitter();
  58204. emitterType.parse(parsedParticleSystem);
  58205. }
  58206. particleSystem.particleEmitterType = emitterType;
  58207. // Animation sheet
  58208. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  58209. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  58210. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  58211. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  58212. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  58213. };
  58214. /**
  58215. * Parses a JSON object to create a particle system.
  58216. * @param parsedParticleSystem The JSON object to parse
  58217. * @param scene The scene to create the particle system in
  58218. * @param rootUrl The root url to use to load external dependencies like texture
  58219. * @returns the Parsed particle system
  58220. */
  58221. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58222. var name = parsedParticleSystem.name;
  58223. var custom = null;
  58224. var program = null;
  58225. if (parsedParticleSystem.customShader) {
  58226. program = parsedParticleSystem.customShader;
  58227. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  58228. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  58229. }
  58230. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  58231. particleSystem.customShader = program;
  58232. if (parsedParticleSystem.id) {
  58233. particleSystem.id = parsedParticleSystem.id;
  58234. }
  58235. // Auto start
  58236. if (parsedParticleSystem.preventAutoStart) {
  58237. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  58238. }
  58239. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  58240. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  58241. if (!particleSystem.preventAutoStart) {
  58242. particleSystem.start();
  58243. }
  58244. return particleSystem;
  58245. };
  58246. return ParticleSystem;
  58247. }(BABYLON.BaseParticleSystem));
  58248. BABYLON.ParticleSystem = ParticleSystem;
  58249. })(BABYLON || (BABYLON = {}));
  58250. //# sourceMappingURL=babylon.particleSystem.js.map
  58251. var BABYLON;
  58252. (function (BABYLON) {
  58253. /**
  58254. * Particle emitter emitting particles from the inside of a box.
  58255. * It emits the particles randomly between 2 given directions.
  58256. */
  58257. var BoxParticleEmitter = /** @class */ (function () {
  58258. /**
  58259. * Creates a new instance BoxParticleEmitter
  58260. */
  58261. function BoxParticleEmitter() {
  58262. /**
  58263. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58264. */
  58265. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58266. /**
  58267. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58268. */
  58269. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58270. /**
  58271. * 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.
  58272. */
  58273. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  58274. /**
  58275. * 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.
  58276. */
  58277. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  58278. }
  58279. /**
  58280. * Called by the particle System when the direction is computed for the created particle.
  58281. * @param worldMatrix is the world matrix of the particle system
  58282. * @param directionToUpdate is the direction vector to update with the result
  58283. * @param particle is the particle we are computed the direction for
  58284. */
  58285. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58286. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58287. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58288. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58289. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58290. };
  58291. /**
  58292. * Called by the particle System when the position is computed for the created particle.
  58293. * @param worldMatrix is the world matrix of the particle system
  58294. * @param positionToUpdate is the position vector to update with the result
  58295. * @param particle is the particle we are computed the position for
  58296. */
  58297. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58298. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  58299. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  58300. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  58301. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58302. };
  58303. /**
  58304. * Clones the current emitter and returns a copy of it
  58305. * @returns the new emitter
  58306. */
  58307. BoxParticleEmitter.prototype.clone = function () {
  58308. var newOne = new BoxParticleEmitter();
  58309. BABYLON.Tools.DeepCopy(this, newOne);
  58310. return newOne;
  58311. };
  58312. /**
  58313. * Called by the GPUParticleSystem to setup the update shader
  58314. * @param effect defines the update shader
  58315. */
  58316. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  58317. effect.setVector3("direction1", this.direction1);
  58318. effect.setVector3("direction2", this.direction2);
  58319. effect.setVector3("minEmitBox", this.minEmitBox);
  58320. effect.setVector3("maxEmitBox", this.maxEmitBox);
  58321. };
  58322. /**
  58323. * Returns a string to use to update the GPU particles update shader
  58324. * @returns a string containng the defines string
  58325. */
  58326. BoxParticleEmitter.prototype.getEffectDefines = function () {
  58327. return "#define BOXEMITTER";
  58328. };
  58329. /**
  58330. * Returns the string "BoxParticleEmitter"
  58331. * @returns a string containing the class name
  58332. */
  58333. BoxParticleEmitter.prototype.getClassName = function () {
  58334. return "BoxParticleEmitter";
  58335. };
  58336. /**
  58337. * Serializes the particle system to a JSON object.
  58338. * @returns the JSON object
  58339. */
  58340. BoxParticleEmitter.prototype.serialize = function () {
  58341. var serializationObject = {};
  58342. serializationObject.type = this.getClassName();
  58343. serializationObject.direction1 = this.direction1.asArray();
  58344. serializationObject.direction2 = this.direction2.asArray();
  58345. serializationObject.minEmitBox = this.minEmitBox.asArray();
  58346. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  58347. return serializationObject;
  58348. };
  58349. /**
  58350. * Parse properties from a JSON object
  58351. * @param serializationObject defines the JSON object
  58352. */
  58353. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  58354. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58355. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58356. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  58357. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  58358. };
  58359. return BoxParticleEmitter;
  58360. }());
  58361. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  58362. })(BABYLON || (BABYLON = {}));
  58363. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  58364. var BABYLON;
  58365. (function (BABYLON) {
  58366. /**
  58367. * Particle emitter emitting particles from the inside of a cylinder.
  58368. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  58369. */
  58370. var CylinderParticleEmitter = /** @class */ (function () {
  58371. /**
  58372. * Creates a new instance CylinderParticleEmitter
  58373. * @param radius the radius of the emission cylinder (1 by default)
  58374. * @param height the height of the emission cylinder (1 by default)
  58375. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58376. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58377. */
  58378. function CylinderParticleEmitter(
  58379. /**
  58380. * The radius of the emission cylinder.
  58381. */
  58382. radius,
  58383. /**
  58384. * The height of the emission cylinder.
  58385. */
  58386. height,
  58387. /**
  58388. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58389. */
  58390. radiusRange,
  58391. /**
  58392. * How much to randomize the particle direction [0-1].
  58393. */
  58394. directionRandomizer) {
  58395. if (radius === void 0) { radius = 1; }
  58396. if (height === void 0) { height = 1; }
  58397. if (radiusRange === void 0) { radiusRange = 1; }
  58398. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58399. this.radius = radius;
  58400. this.height = height;
  58401. this.radiusRange = radiusRange;
  58402. this.directionRandomizer = directionRandomizer;
  58403. }
  58404. /**
  58405. * Called by the particle System when the direction is computed for the created particle.
  58406. * @param worldMatrix is the world matrix of the particle system
  58407. * @param directionToUpdate is the direction vector to update with the result
  58408. * @param particle is the particle we are computed the direction for
  58409. */
  58410. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58411. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58412. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  58413. var angle = Math.atan2(direction.x, direction.z);
  58414. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  58415. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  58416. direction.x = Math.sin(angle);
  58417. direction.z = Math.cos(angle);
  58418. direction.normalize();
  58419. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58420. };
  58421. /**
  58422. * Called by the particle System when the position is computed for the created particle.
  58423. * @param worldMatrix is the world matrix of the particle system
  58424. * @param positionToUpdate is the position vector to update with the result
  58425. * @param particle is the particle we are computed the position for
  58426. */
  58427. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58428. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  58429. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58430. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  58431. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  58432. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  58433. var xPos = positionRadius * Math.cos(angle);
  58434. var zPos = positionRadius * Math.sin(angle);
  58435. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  58436. };
  58437. /**
  58438. * Clones the current emitter and returns a copy of it
  58439. * @returns the new emitter
  58440. */
  58441. CylinderParticleEmitter.prototype.clone = function () {
  58442. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  58443. BABYLON.Tools.DeepCopy(this, newOne);
  58444. return newOne;
  58445. };
  58446. /**
  58447. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58448. * @param effect defines the update shader
  58449. */
  58450. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  58451. effect.setFloat("radius", this.radius);
  58452. effect.setFloat("height", this.height);
  58453. effect.setFloat("radiusRange", this.radiusRange);
  58454. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58455. };
  58456. /**
  58457. * Returns a string to use to update the GPU particles update shader
  58458. * @returns a string containng the defines string
  58459. */
  58460. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  58461. return "#define CYLINDEREMITTER";
  58462. };
  58463. /**
  58464. * Returns the string "CylinderParticleEmitter"
  58465. * @returns a string containing the class name
  58466. */
  58467. CylinderParticleEmitter.prototype.getClassName = function () {
  58468. return "CylinderParticleEmitter";
  58469. };
  58470. /**
  58471. * Serializes the particle system to a JSON object.
  58472. * @returns the JSON object
  58473. */
  58474. CylinderParticleEmitter.prototype.serialize = function () {
  58475. var serializationObject = {};
  58476. serializationObject.type = this.getClassName();
  58477. serializationObject.radius = this.radius;
  58478. serializationObject.height = this.height;
  58479. serializationObject.radiusRange = this.radiusRange;
  58480. serializationObject.directionRandomizer = this.directionRandomizer;
  58481. return serializationObject;
  58482. };
  58483. /**
  58484. * Parse properties from a JSON object
  58485. * @param serializationObject defines the JSON object
  58486. */
  58487. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  58488. this.radius = serializationObject.radius;
  58489. this.height = serializationObject.height;
  58490. this.radiusRange = serializationObject.radiusRange;
  58491. this.directionRandomizer = serializationObject.directionRandomizer;
  58492. };
  58493. return CylinderParticleEmitter;
  58494. }());
  58495. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  58496. /**
  58497. * Particle emitter emitting particles from the inside of a cylinder.
  58498. * It emits the particles randomly between two vectors.
  58499. */
  58500. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  58501. __extends(CylinderDirectedParticleEmitter, _super);
  58502. /**
  58503. * Creates a new instance CylinderDirectedParticleEmitter
  58504. * @param radius the radius of the emission cylinder (1 by default)
  58505. * @param height the height of the emission cylinder (1 by default)
  58506. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58507. * @param direction1 the min limit of the emission direction (up vector by default)
  58508. * @param direction2 the max limit of the emission direction (up vector by default)
  58509. */
  58510. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  58511. /**
  58512. * The min limit of the emission direction.
  58513. */
  58514. direction1,
  58515. /**
  58516. * The max limit of the emission direction.
  58517. */
  58518. direction2) {
  58519. if (radius === void 0) { radius = 1; }
  58520. if (height === void 0) { height = 1; }
  58521. if (radiusRange === void 0) { radiusRange = 1; }
  58522. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58523. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58524. var _this = _super.call(this, radius, height, radiusRange) || this;
  58525. _this.direction1 = direction1;
  58526. _this.direction2 = direction2;
  58527. return _this;
  58528. }
  58529. /**
  58530. * Called by the particle System when the direction is computed for the created particle.
  58531. * @param worldMatrix is the world matrix of the particle system
  58532. * @param directionToUpdate is the direction vector to update with the result
  58533. * @param particle is the particle we are computed the direction for
  58534. */
  58535. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58536. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58537. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58538. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58539. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58540. };
  58541. /**
  58542. * Clones the current emitter and returns a copy of it
  58543. * @returns the new emitter
  58544. */
  58545. CylinderDirectedParticleEmitter.prototype.clone = function () {
  58546. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  58547. BABYLON.Tools.DeepCopy(this, newOne);
  58548. return newOne;
  58549. };
  58550. /**
  58551. * Called by the GPUParticleSystem to setup the update shader
  58552. * @param effect defines the update shader
  58553. */
  58554. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58555. effect.setFloat("radius", this.radius);
  58556. effect.setFloat("height", this.height);
  58557. effect.setFloat("radiusRange", this.radiusRange);
  58558. effect.setVector3("direction1", this.direction1);
  58559. effect.setVector3("direction2", this.direction2);
  58560. };
  58561. /**
  58562. * Returns a string to use to update the GPU particles update shader
  58563. * @returns a string containng the defines string
  58564. */
  58565. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58566. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  58567. };
  58568. /**
  58569. * Returns the string "CylinderDirectedParticleEmitter"
  58570. * @returns a string containing the class name
  58571. */
  58572. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  58573. return "CylinderDirectedParticleEmitter";
  58574. };
  58575. /**
  58576. * Serializes the particle system to a JSON object.
  58577. * @returns the JSON object
  58578. */
  58579. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  58580. var serializationObject = _super.prototype.serialize.call(this);
  58581. serializationObject.direction1 = this.direction1.asArray();
  58582. serializationObject.direction2 = this.direction2.asArray();
  58583. return serializationObject;
  58584. };
  58585. /**
  58586. * Parse properties from a JSON object
  58587. * @param serializationObject defines the JSON object
  58588. */
  58589. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58590. _super.prototype.parse.call(this, serializationObject);
  58591. this.direction1.copyFrom(serializationObject.direction1);
  58592. this.direction2.copyFrom(serializationObject.direction2);
  58593. };
  58594. return CylinderDirectedParticleEmitter;
  58595. }(CylinderParticleEmitter));
  58596. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  58597. })(BABYLON || (BABYLON = {}));
  58598. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  58599. var BABYLON;
  58600. (function (BABYLON) {
  58601. /**
  58602. * Particle emitter emitting particles from the inside of a cone.
  58603. * It emits the particles alongside the cone volume from the base to the particle.
  58604. * The emission direction might be randomized.
  58605. */
  58606. var ConeParticleEmitter = /** @class */ (function () {
  58607. /**
  58608. * Creates a new instance ConeParticleEmitter
  58609. * @param radius the radius of the emission cone (1 by default)
  58610. * @param angles the cone base angle (PI by default)
  58611. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  58612. */
  58613. function ConeParticleEmitter(radius, angle,
  58614. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  58615. directionRandomizer) {
  58616. if (radius === void 0) { radius = 1; }
  58617. if (angle === void 0) { angle = Math.PI; }
  58618. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58619. this.directionRandomizer = directionRandomizer;
  58620. /**
  58621. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  58622. */
  58623. this.radiusRange = 1;
  58624. /**
  58625. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  58626. */
  58627. this.heightRange = 1;
  58628. /**
  58629. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  58630. */
  58631. this.emitFromSpawnPointOnly = false;
  58632. this.angle = angle;
  58633. this.radius = radius;
  58634. }
  58635. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  58636. /**
  58637. * Gets or sets the radius of the emission cone
  58638. */
  58639. get: function () {
  58640. return this._radius;
  58641. },
  58642. set: function (value) {
  58643. this._radius = value;
  58644. this._buildHeight();
  58645. },
  58646. enumerable: true,
  58647. configurable: true
  58648. });
  58649. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  58650. /**
  58651. * Gets or sets the angle of the emission cone
  58652. */
  58653. get: function () {
  58654. return this._angle;
  58655. },
  58656. set: function (value) {
  58657. this._angle = value;
  58658. this._buildHeight();
  58659. },
  58660. enumerable: true,
  58661. configurable: true
  58662. });
  58663. ConeParticleEmitter.prototype._buildHeight = function () {
  58664. if (this._angle !== 0) {
  58665. this._height = this._radius / Math.tan(this._angle / 2);
  58666. }
  58667. else {
  58668. this._height = 1;
  58669. }
  58670. };
  58671. /**
  58672. * Called by the particle System when the direction is computed for the created particle.
  58673. * @param worldMatrix is the world matrix of the particle system
  58674. * @param directionToUpdate is the direction vector to update with the result
  58675. * @param particle is the particle we are computed the direction for
  58676. */
  58677. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58678. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  58679. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  58680. }
  58681. else {
  58682. // measure the direction Vector from the emitter to the 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. /**
  58695. * Called by the particle System when the position is computed for the created particle.
  58696. * @param worldMatrix is the world matrix of the particle system
  58697. * @param positionToUpdate is the position vector to update with the result
  58698. * @param particle is the particle we are computed the position for
  58699. */
  58700. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58701. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  58702. var h;
  58703. if (!this.emitFromSpawnPointOnly) {
  58704. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  58705. // Better distribution in a cone at normal angles.
  58706. h = 1 - h * h;
  58707. }
  58708. else {
  58709. h = 0.0001;
  58710. }
  58711. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  58712. radius = radius * h;
  58713. var randX = radius * Math.sin(s);
  58714. var randZ = radius * Math.cos(s);
  58715. var randY = h * this._height;
  58716. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58717. };
  58718. /**
  58719. * Clones the current emitter and returns a copy of it
  58720. * @returns the new emitter
  58721. */
  58722. ConeParticleEmitter.prototype.clone = function () {
  58723. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  58724. BABYLON.Tools.DeepCopy(this, newOne);
  58725. return newOne;
  58726. };
  58727. /**
  58728. * Called by the GPUParticleSystem to setup the update shader
  58729. * @param effect defines the update shader
  58730. */
  58731. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  58732. effect.setFloat2("radius", this._radius, this.radiusRange);
  58733. effect.setFloat("coneAngle", this._angle);
  58734. effect.setFloat2("height", this._height, this.heightRange);
  58735. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58736. };
  58737. /**
  58738. * Returns a string to use to update the GPU particles update shader
  58739. * @returns a string containng the defines string
  58740. */
  58741. ConeParticleEmitter.prototype.getEffectDefines = function () {
  58742. var defines = "#define CONEEMITTER";
  58743. if (this.emitFromSpawnPointOnly) {
  58744. defines += "\n#define CONEEMITTERSPAWNPOINT";
  58745. }
  58746. return defines;
  58747. };
  58748. /**
  58749. * Returns the string "ConeParticleEmitter"
  58750. * @returns a string containing the class name
  58751. */
  58752. ConeParticleEmitter.prototype.getClassName = function () {
  58753. return "ConeParticleEmitter";
  58754. };
  58755. /**
  58756. * Serializes the particle system to a JSON object.
  58757. * @returns the JSON object
  58758. */
  58759. ConeParticleEmitter.prototype.serialize = function () {
  58760. var serializationObject = {};
  58761. serializationObject.type = this.getClassName();
  58762. serializationObject.radius = this._radius;
  58763. serializationObject.angle = this._angle;
  58764. serializationObject.directionRandomizer = this.directionRandomizer;
  58765. return serializationObject;
  58766. };
  58767. /**
  58768. * Parse properties from a JSON object
  58769. * @param serializationObject defines the JSON object
  58770. */
  58771. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  58772. this.radius = serializationObject.radius;
  58773. this.angle = serializationObject.angle;
  58774. this.directionRandomizer = serializationObject.directionRandomizer;
  58775. };
  58776. return ConeParticleEmitter;
  58777. }());
  58778. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  58779. })(BABYLON || (BABYLON = {}));
  58780. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  58781. var BABYLON;
  58782. (function (BABYLON) {
  58783. /**
  58784. * Particle emitter emitting particles from the inside of a sphere.
  58785. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  58786. */
  58787. var SphereParticleEmitter = /** @class */ (function () {
  58788. /**
  58789. * Creates a new instance SphereParticleEmitter
  58790. * @param radius the radius of the emission sphere (1 by default)
  58791. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58792. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58793. */
  58794. function SphereParticleEmitter(
  58795. /**
  58796. * The radius of the emission sphere.
  58797. */
  58798. radius,
  58799. /**
  58800. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58801. */
  58802. radiusRange,
  58803. /**
  58804. * How much to randomize the particle direction [0-1].
  58805. */
  58806. directionRandomizer) {
  58807. if (radius === void 0) { radius = 1; }
  58808. if (radiusRange === void 0) { radiusRange = 1; }
  58809. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58810. this.radius = radius;
  58811. this.radiusRange = radiusRange;
  58812. this.directionRandomizer = directionRandomizer;
  58813. }
  58814. /**
  58815. * Called by the particle System when the direction is computed for the created particle.
  58816. * @param worldMatrix is the world matrix of the particle system
  58817. * @param directionToUpdate is the direction vector to update with the result
  58818. * @param particle is the particle we are computed the direction for
  58819. */
  58820. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58821. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58822. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58823. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58824. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58825. direction.x += randX;
  58826. direction.y += randY;
  58827. direction.z += randZ;
  58828. direction.normalize();
  58829. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58830. };
  58831. /**
  58832. * Called by the particle System when the position is computed for the created particle.
  58833. * @param worldMatrix is the world matrix of the particle system
  58834. * @param positionToUpdate is the position vector to update with the result
  58835. * @param particle is the particle we are computed the position for
  58836. */
  58837. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58838. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58839. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58840. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58841. var theta = Math.acos(2 * v - 1);
  58842. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58843. var randY = randRadius * Math.cos(theta);
  58844. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58845. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58846. };
  58847. /**
  58848. * Clones the current emitter and returns a copy of it
  58849. * @returns the new emitter
  58850. */
  58851. SphereParticleEmitter.prototype.clone = function () {
  58852. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58853. BABYLON.Tools.DeepCopy(this, newOne);
  58854. return newOne;
  58855. };
  58856. /**
  58857. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58858. * @param effect defines the update shader
  58859. */
  58860. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58861. effect.setFloat("radius", this.radius);
  58862. effect.setFloat("radiusRange", this.radiusRange);
  58863. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58864. };
  58865. /**
  58866. * Returns a string to use to update the GPU particles update shader
  58867. * @returns a string containng the defines string
  58868. */
  58869. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58870. return "#define SPHEREEMITTER";
  58871. };
  58872. /**
  58873. * Returns the string "SphereParticleEmitter"
  58874. * @returns a string containing the class name
  58875. */
  58876. SphereParticleEmitter.prototype.getClassName = function () {
  58877. return "SphereParticleEmitter";
  58878. };
  58879. /**
  58880. * Serializes the particle system to a JSON object.
  58881. * @returns the JSON object
  58882. */
  58883. SphereParticleEmitter.prototype.serialize = function () {
  58884. var serializationObject = {};
  58885. serializationObject.type = this.getClassName();
  58886. serializationObject.radius = this.radius;
  58887. serializationObject.radiusRange = this.radiusRange;
  58888. serializationObject.directionRandomizer = this.directionRandomizer;
  58889. return serializationObject;
  58890. };
  58891. /**
  58892. * Parse properties from a JSON object
  58893. * @param serializationObject defines the JSON object
  58894. */
  58895. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58896. this.radius = serializationObject.radius;
  58897. this.radiusRange = serializationObject.radiusRange;
  58898. this.directionRandomizer = serializationObject.directionRandomizer;
  58899. };
  58900. return SphereParticleEmitter;
  58901. }());
  58902. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58903. /**
  58904. * Particle emitter emitting particles from the inside of a sphere.
  58905. * It emits the particles randomly between two vectors.
  58906. */
  58907. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58908. __extends(SphereDirectedParticleEmitter, _super);
  58909. /**
  58910. * Creates a new instance SphereDirectedParticleEmitter
  58911. * @param radius the radius of the emission sphere (1 by default)
  58912. * @param direction1 the min limit of the emission direction (up vector by default)
  58913. * @param direction2 the max limit of the emission direction (up vector by default)
  58914. */
  58915. function SphereDirectedParticleEmitter(radius,
  58916. /**
  58917. * The min limit of the emission direction.
  58918. */
  58919. direction1,
  58920. /**
  58921. * The max limit of the emission direction.
  58922. */
  58923. direction2) {
  58924. if (radius === void 0) { radius = 1; }
  58925. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58926. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58927. var _this = _super.call(this, radius) || this;
  58928. _this.direction1 = direction1;
  58929. _this.direction2 = direction2;
  58930. return _this;
  58931. }
  58932. /**
  58933. * Called by the particle System when the direction is computed for the created particle.
  58934. * @param worldMatrix is the world matrix of the particle system
  58935. * @param directionToUpdate is the direction vector to update with the result
  58936. * @param particle is the particle we are computed the direction for
  58937. */
  58938. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58939. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58940. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58941. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58942. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58943. };
  58944. /**
  58945. * Clones the current emitter and returns a copy of it
  58946. * @returns the new emitter
  58947. */
  58948. SphereDirectedParticleEmitter.prototype.clone = function () {
  58949. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58950. BABYLON.Tools.DeepCopy(this, newOne);
  58951. return newOne;
  58952. };
  58953. /**
  58954. * Called by the GPUParticleSystem to setup the update shader
  58955. * @param effect defines the update shader
  58956. */
  58957. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58958. effect.setFloat("radius", this.radius);
  58959. effect.setFloat("radiusRange", this.radiusRange);
  58960. effect.setVector3("direction1", this.direction1);
  58961. effect.setVector3("direction2", this.direction2);
  58962. };
  58963. /**
  58964. * Returns a string to use to update the GPU particles update shader
  58965. * @returns a string containng the defines string
  58966. */
  58967. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58968. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58969. };
  58970. /**
  58971. * Returns the string "SphereDirectedParticleEmitter"
  58972. * @returns a string containing the class name
  58973. */
  58974. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58975. return "SphereDirectedParticleEmitter";
  58976. };
  58977. /**
  58978. * Serializes the particle system to a JSON object.
  58979. * @returns the JSON object
  58980. */
  58981. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58982. var serializationObject = _super.prototype.serialize.call(this);
  58983. serializationObject.direction1 = this.direction1.asArray();
  58984. serializationObject.direction2 = this.direction2.asArray();
  58985. return serializationObject;
  58986. };
  58987. /**
  58988. * Parse properties from a JSON object
  58989. * @param serializationObject defines the JSON object
  58990. */
  58991. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58992. _super.prototype.parse.call(this, serializationObject);
  58993. this.direction1.copyFrom(serializationObject.direction1);
  58994. this.direction2.copyFrom(serializationObject.direction2);
  58995. };
  58996. return SphereDirectedParticleEmitter;
  58997. }(SphereParticleEmitter));
  58998. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58999. })(BABYLON || (BABYLON = {}));
  59000. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  59001. var BABYLON;
  59002. (function (BABYLON) {
  59003. /**
  59004. * Particle emitter emitting particles from the inside of a hemisphere.
  59005. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  59006. */
  59007. var HemisphericParticleEmitter = /** @class */ (function () {
  59008. /**
  59009. * Creates a new instance HemisphericParticleEmitter
  59010. * @param radius the radius of the emission hemisphere (1 by default)
  59011. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59012. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59013. */
  59014. function HemisphericParticleEmitter(
  59015. /**
  59016. * The radius of the emission hemisphere.
  59017. */
  59018. radius,
  59019. /**
  59020. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59021. */
  59022. radiusRange,
  59023. /**
  59024. * How much to randomize the particle direction [0-1].
  59025. */
  59026. directionRandomizer) {
  59027. if (radius === void 0) { radius = 1; }
  59028. if (radiusRange === void 0) { radiusRange = 1; }
  59029. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59030. this.radius = radius;
  59031. this.radiusRange = radiusRange;
  59032. this.directionRandomizer = directionRandomizer;
  59033. }
  59034. /**
  59035. * Called by the particle System when the direction is computed for the created particle.
  59036. * @param worldMatrix is the world matrix of the particle system
  59037. * @param directionToUpdate is the direction vector to update with the result
  59038. * @param particle is the particle we are computed the direction for
  59039. */
  59040. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59041. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59042. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59043. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59044. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59045. direction.x += randX;
  59046. direction.y += randY;
  59047. direction.z += randZ;
  59048. direction.normalize();
  59049. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59050. };
  59051. /**
  59052. * Called by the particle System when the position is computed for the created particle.
  59053. * @param worldMatrix is the world matrix of the particle system
  59054. * @param positionToUpdate is the position vector to update with the result
  59055. * @param particle is the particle we are computed the position for
  59056. */
  59057. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59058. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  59059. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  59060. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59061. var theta = Math.acos(2 * v - 1);
  59062. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  59063. var randY = randRadius * Math.cos(theta);
  59064. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  59065. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  59066. };
  59067. /**
  59068. * Clones the current emitter and returns a copy of it
  59069. * @returns the new emitter
  59070. */
  59071. HemisphericParticleEmitter.prototype.clone = function () {
  59072. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  59073. BABYLON.Tools.DeepCopy(this, newOne);
  59074. return newOne;
  59075. };
  59076. /**
  59077. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59078. * @param effect defines the update shader
  59079. */
  59080. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  59081. effect.setFloat("radius", this.radius);
  59082. effect.setFloat("radiusRange", this.radiusRange);
  59083. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59084. };
  59085. /**
  59086. * Returns a string to use to update the GPU particles update shader
  59087. * @returns a string containng the defines string
  59088. */
  59089. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  59090. return "#define HEMISPHERICEMITTER";
  59091. };
  59092. /**
  59093. * Returns the string "HemisphericParticleEmitter"
  59094. * @returns a string containing the class name
  59095. */
  59096. HemisphericParticleEmitter.prototype.getClassName = function () {
  59097. return "HemisphericParticleEmitter";
  59098. };
  59099. /**
  59100. * Serializes the particle system to a JSON object.
  59101. * @returns the JSON object
  59102. */
  59103. HemisphericParticleEmitter.prototype.serialize = function () {
  59104. var serializationObject = {};
  59105. serializationObject.type = this.getClassName();
  59106. serializationObject.radius = this.radius;
  59107. serializationObject.radiusRange = this.radiusRange;
  59108. serializationObject.directionRandomizer = this.directionRandomizer;
  59109. return serializationObject;
  59110. };
  59111. /**
  59112. * Parse properties from a JSON object
  59113. * @param serializationObject defines the JSON object
  59114. */
  59115. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  59116. this.radius = serializationObject.radius;
  59117. this.radiusRange = serializationObject.radiusRange;
  59118. this.directionRandomizer = serializationObject.directionRandomizer;
  59119. };
  59120. return HemisphericParticleEmitter;
  59121. }());
  59122. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  59123. })(BABYLON || (BABYLON = {}));
  59124. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  59125. var BABYLON;
  59126. (function (BABYLON) {
  59127. /**
  59128. * Particle emitter emitting particles from a point.
  59129. * It emits the particles randomly between 2 given directions.
  59130. */
  59131. var PointParticleEmitter = /** @class */ (function () {
  59132. /**
  59133. * Creates a new instance PointParticleEmitter
  59134. */
  59135. function PointParticleEmitter() {
  59136. /**
  59137. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59138. */
  59139. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59140. /**
  59141. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59142. */
  59143. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59144. }
  59145. /**
  59146. * Called by the particle System when the direction is computed for the created particle.
  59147. * @param worldMatrix is the world matrix of the particle system
  59148. * @param directionToUpdate is the direction vector to update with the result
  59149. * @param particle is the particle we are computed the direction for
  59150. */
  59151. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59152. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59153. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59154. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59155. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59156. };
  59157. /**
  59158. * Called by the particle System when the position is computed for the created particle.
  59159. * @param worldMatrix is the world matrix of the particle system
  59160. * @param positionToUpdate is the position vector to update with the result
  59161. * @param particle is the particle we are computed the position for
  59162. */
  59163. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59164. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  59165. };
  59166. /**
  59167. * Clones the current emitter and returns a copy of it
  59168. * @returns the new emitter
  59169. */
  59170. PointParticleEmitter.prototype.clone = function () {
  59171. var newOne = new PointParticleEmitter();
  59172. BABYLON.Tools.DeepCopy(this, newOne);
  59173. return newOne;
  59174. };
  59175. /**
  59176. * Called by the GPUParticleSystem to setup the update shader
  59177. * @param effect defines the update shader
  59178. */
  59179. PointParticleEmitter.prototype.applyToShader = function (effect) {
  59180. effect.setVector3("direction1", this.direction1);
  59181. effect.setVector3("direction2", this.direction2);
  59182. };
  59183. /**
  59184. * Returns a string to use to update the GPU particles update shader
  59185. * @returns a string containng the defines string
  59186. */
  59187. PointParticleEmitter.prototype.getEffectDefines = function () {
  59188. return "#define POINTEMITTER";
  59189. };
  59190. /**
  59191. * Returns the string "PointParticleEmitter"
  59192. * @returns a string containing the class name
  59193. */
  59194. PointParticleEmitter.prototype.getClassName = function () {
  59195. return "PointParticleEmitter";
  59196. };
  59197. /**
  59198. * Serializes the particle system to a JSON object.
  59199. * @returns the JSON object
  59200. */
  59201. PointParticleEmitter.prototype.serialize = function () {
  59202. var serializationObject = {};
  59203. serializationObject.type = this.getClassName();
  59204. serializationObject.direction1 = this.direction1.asArray();
  59205. serializationObject.direction2 = this.direction2.asArray();
  59206. return serializationObject;
  59207. };
  59208. /**
  59209. * Parse properties from a JSON object
  59210. * @param serializationObject defines the JSON object
  59211. */
  59212. PointParticleEmitter.prototype.parse = function (serializationObject) {
  59213. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59214. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59215. };
  59216. return PointParticleEmitter;
  59217. }());
  59218. BABYLON.PointParticleEmitter = PointParticleEmitter;
  59219. })(BABYLON || (BABYLON = {}));
  59220. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  59221. var BABYLON;
  59222. (function (BABYLON) {
  59223. // Adds the parsers to the scene parsers.
  59224. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  59225. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  59226. if (!individualParser) {
  59227. return;
  59228. }
  59229. // Particles Systems
  59230. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  59231. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  59232. var parsedParticleSystem = parsedData.particleSystems[index];
  59233. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  59234. }
  59235. }
  59236. });
  59237. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  59238. if (parsedParticleSystem.activeParticleCount) {
  59239. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59240. return ps;
  59241. }
  59242. else {
  59243. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59244. return ps;
  59245. }
  59246. });
  59247. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  59248. if (uniformsNames === void 0) { uniformsNames = []; }
  59249. if (samplers === void 0) { samplers = []; }
  59250. if (defines === void 0) { defines = ""; }
  59251. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  59252. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  59253. if (defines.indexOf(" BILLBOARD") === -1) {
  59254. defines += "\n#define BILLBOARD\n";
  59255. }
  59256. if (samplers.indexOf("diffuseSampler") === -1) {
  59257. samplers.push("diffuseSampler");
  59258. }
  59259. return this.createEffect({
  59260. vertex: "particles",
  59261. fragmentElement: fragmentName
  59262. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  59263. };
  59264. })(BABYLON || (BABYLON = {}));
  59265. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  59266. var BABYLON;
  59267. (function (BABYLON) {
  59268. /**
  59269. * Type of sub emitter
  59270. */
  59271. var SubEmitterType;
  59272. (function (SubEmitterType) {
  59273. /**
  59274. * Attached to the particle over it's lifetime
  59275. */
  59276. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  59277. /**
  59278. * Created when the particle dies
  59279. */
  59280. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  59281. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  59282. /**
  59283. * Sub emitter class used to emit particles from an existing particle
  59284. */
  59285. var SubEmitter = /** @class */ (function () {
  59286. /**
  59287. * Creates a sub emitter
  59288. * @param particleSystem the particle system to be used by the sub emitter
  59289. */
  59290. function SubEmitter(
  59291. /**
  59292. * the particle system to be used by the sub emitter
  59293. */
  59294. particleSystem) {
  59295. this.particleSystem = particleSystem;
  59296. /**
  59297. * Type of the submitter (Default: END)
  59298. */
  59299. this.type = SubEmitterType.END;
  59300. /**
  59301. * 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)
  59302. * Note: This only is supported when using an emitter of type Mesh
  59303. */
  59304. this.inheritDirection = false;
  59305. /**
  59306. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  59307. */
  59308. this.inheritedVelocityAmount = 0;
  59309. }
  59310. /**
  59311. * Clones the sub emitter
  59312. * @returns the cloned sub emitter
  59313. */
  59314. SubEmitter.prototype.clone = function () {
  59315. // Clone particle system
  59316. var emitter = this.particleSystem.emitter;
  59317. if (!emitter) {
  59318. emitter = new BABYLON.Vector3();
  59319. }
  59320. else if (emitter instanceof BABYLON.Vector3) {
  59321. emitter = emitter.clone();
  59322. }
  59323. else if (emitter instanceof BABYLON.AbstractMesh) {
  59324. emitter = new BABYLON.Mesh("", emitter._scene);
  59325. }
  59326. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  59327. // Clone properties
  59328. clone.type = this.type;
  59329. clone.inheritDirection = this.inheritDirection;
  59330. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  59331. clone.particleSystem._disposeEmitterOnDispose = true;
  59332. return clone;
  59333. };
  59334. return SubEmitter;
  59335. }());
  59336. BABYLON.SubEmitter = SubEmitter;
  59337. })(BABYLON || (BABYLON = {}));
  59338. //# sourceMappingURL=babylon.subEmitter.js.map
  59339. var BABYLON;
  59340. (function (BABYLON) {
  59341. var ShaderMaterial = /** @class */ (function (_super) {
  59342. __extends(ShaderMaterial, _super);
  59343. function ShaderMaterial(name, scene, shaderPath, options) {
  59344. var _this = _super.call(this, name, scene) || this;
  59345. _this._textures = {};
  59346. _this._textureArrays = {};
  59347. _this._floats = {};
  59348. _this._ints = {};
  59349. _this._floatsArrays = {};
  59350. _this._colors3 = {};
  59351. _this._colors3Arrays = {};
  59352. _this._colors4 = {};
  59353. _this._vectors2 = {};
  59354. _this._vectors3 = {};
  59355. _this._vectors4 = {};
  59356. _this._matrices = {};
  59357. _this._matrices3x3 = {};
  59358. _this._matrices2x2 = {};
  59359. _this._vectors2Arrays = {};
  59360. _this._vectors3Arrays = {};
  59361. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59362. _this._shaderPath = shaderPath;
  59363. options.needAlphaBlending = options.needAlphaBlending || false;
  59364. options.needAlphaTesting = options.needAlphaTesting || false;
  59365. options.attributes = options.attributes || ["position", "normal", "uv"];
  59366. options.uniforms = options.uniforms || ["worldViewProjection"];
  59367. options.uniformBuffers = options.uniformBuffers || [];
  59368. options.samplers = options.samplers || [];
  59369. options.defines = options.defines || [];
  59370. _this._options = options;
  59371. return _this;
  59372. }
  59373. ShaderMaterial.prototype.getClassName = function () {
  59374. return "ShaderMaterial";
  59375. };
  59376. ShaderMaterial.prototype.needAlphaBlending = function () {
  59377. return this._options.needAlphaBlending;
  59378. };
  59379. ShaderMaterial.prototype.needAlphaTesting = function () {
  59380. return this._options.needAlphaTesting;
  59381. };
  59382. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59383. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59384. this._options.uniforms.push(uniformName);
  59385. }
  59386. };
  59387. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59388. if (this._options.samplers.indexOf(name) === -1) {
  59389. this._options.samplers.push(name);
  59390. }
  59391. this._textures[name] = texture;
  59392. return this;
  59393. };
  59394. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59395. if (this._options.samplers.indexOf(name) === -1) {
  59396. this._options.samplers.push(name);
  59397. }
  59398. this._checkUniform(name);
  59399. this._textureArrays[name] = textures;
  59400. return this;
  59401. };
  59402. ShaderMaterial.prototype.setFloat = function (name, value) {
  59403. this._checkUniform(name);
  59404. this._floats[name] = value;
  59405. return this;
  59406. };
  59407. ShaderMaterial.prototype.setInt = function (name, value) {
  59408. this._checkUniform(name);
  59409. this._ints[name] = value;
  59410. return this;
  59411. };
  59412. ShaderMaterial.prototype.setFloats = function (name, value) {
  59413. this._checkUniform(name);
  59414. this._floatsArrays[name] = value;
  59415. return this;
  59416. };
  59417. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59418. this._checkUniform(name);
  59419. this._colors3[name] = value;
  59420. return this;
  59421. };
  59422. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59423. this._checkUniform(name);
  59424. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59425. color.toArray(arr, arr.length);
  59426. return arr;
  59427. }, []);
  59428. return this;
  59429. };
  59430. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59431. this._checkUniform(name);
  59432. this._colors4[name] = value;
  59433. return this;
  59434. };
  59435. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59436. this._checkUniform(name);
  59437. this._vectors2[name] = value;
  59438. return this;
  59439. };
  59440. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59441. this._checkUniform(name);
  59442. this._vectors3[name] = value;
  59443. return this;
  59444. };
  59445. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59446. this._checkUniform(name);
  59447. this._vectors4[name] = value;
  59448. return this;
  59449. };
  59450. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59451. this._checkUniform(name);
  59452. this._matrices[name] = value;
  59453. return this;
  59454. };
  59455. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59456. this._checkUniform(name);
  59457. this._matrices3x3[name] = value;
  59458. return this;
  59459. };
  59460. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59461. this._checkUniform(name);
  59462. this._matrices2x2[name] = value;
  59463. return this;
  59464. };
  59465. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59466. this._checkUniform(name);
  59467. this._vectors2Arrays[name] = value;
  59468. return this;
  59469. };
  59470. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59471. this._checkUniform(name);
  59472. this._vectors3Arrays[name] = value;
  59473. return this;
  59474. };
  59475. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59476. if (!mesh) {
  59477. return true;
  59478. }
  59479. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59480. return false;
  59481. }
  59482. return false;
  59483. };
  59484. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59485. var scene = this.getScene();
  59486. var engine = scene.getEngine();
  59487. if (!this.checkReadyOnEveryCall) {
  59488. if (this._renderId === scene.getRenderId()) {
  59489. if (this._checkCache(scene, mesh, useInstances)) {
  59490. return true;
  59491. }
  59492. }
  59493. }
  59494. // Instances
  59495. var defines = [];
  59496. var attribs = [];
  59497. var fallbacks = new BABYLON.EffectFallbacks();
  59498. if (useInstances) {
  59499. defines.push("#define INSTANCES");
  59500. }
  59501. for (var index = 0; index < this._options.defines.length; index++) {
  59502. defines.push(this._options.defines[index]);
  59503. }
  59504. for (var index = 0; index < this._options.attributes.length; index++) {
  59505. attribs.push(this._options.attributes[index]);
  59506. }
  59507. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59508. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59509. defines.push("#define VERTEXCOLOR");
  59510. }
  59511. // Bones
  59512. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59513. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59514. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59515. if (mesh.numBoneInfluencers > 4) {
  59516. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59517. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59518. }
  59519. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59520. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59521. fallbacks.addCPUSkinningFallback(0, mesh);
  59522. if (this._options.uniforms.indexOf("mBones") === -1) {
  59523. this._options.uniforms.push("mBones");
  59524. }
  59525. }
  59526. else {
  59527. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59528. }
  59529. // Textures
  59530. for (var name in this._textures) {
  59531. if (!this._textures[name].isReady()) {
  59532. return false;
  59533. }
  59534. }
  59535. // Alpha test
  59536. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59537. defines.push("#define ALPHATEST");
  59538. }
  59539. var previousEffect = this._effect;
  59540. var join = defines.join("\n");
  59541. this._effect = engine.createEffect(this._shaderPath, {
  59542. attributes: attribs,
  59543. uniformsNames: this._options.uniforms,
  59544. uniformBuffersNames: this._options.uniformBuffers,
  59545. samplers: this._options.samplers,
  59546. defines: join,
  59547. fallbacks: fallbacks,
  59548. onCompiled: this.onCompiled,
  59549. onError: this.onError
  59550. }, engine);
  59551. if (!this._effect.isReady()) {
  59552. return false;
  59553. }
  59554. if (previousEffect !== this._effect) {
  59555. scene.resetCachedMaterial();
  59556. }
  59557. this._renderId = scene.getRenderId();
  59558. return true;
  59559. };
  59560. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59561. var scene = this.getScene();
  59562. if (!this._effect) {
  59563. return;
  59564. }
  59565. if (this._options.uniforms.indexOf("world") !== -1) {
  59566. this._effect.setMatrix("world", world);
  59567. }
  59568. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59569. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59570. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59571. }
  59572. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59573. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59574. }
  59575. };
  59576. ShaderMaterial.prototype.bind = function (world, mesh) {
  59577. // Std values
  59578. this.bindOnlyWorldMatrix(world);
  59579. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59580. if (this._options.uniforms.indexOf("view") !== -1) {
  59581. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59582. }
  59583. if (this._options.uniforms.indexOf("projection") !== -1) {
  59584. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59585. }
  59586. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59587. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59588. }
  59589. // Bones
  59590. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59591. var name;
  59592. // Texture
  59593. for (name in this._textures) {
  59594. this._effect.setTexture(name, this._textures[name]);
  59595. }
  59596. // Texture arrays
  59597. for (name in this._textureArrays) {
  59598. this._effect.setTextureArray(name, this._textureArrays[name]);
  59599. }
  59600. // Int
  59601. for (name in this._ints) {
  59602. this._effect.setInt(name, this._ints[name]);
  59603. }
  59604. // Float
  59605. for (name in this._floats) {
  59606. this._effect.setFloat(name, this._floats[name]);
  59607. }
  59608. // Floats
  59609. for (name in this._floatsArrays) {
  59610. this._effect.setArray(name, this._floatsArrays[name]);
  59611. }
  59612. // Color3
  59613. for (name in this._colors3) {
  59614. this._effect.setColor3(name, this._colors3[name]);
  59615. }
  59616. for (name in this._colors3Arrays) {
  59617. this._effect.setArray3(name, this._colors3Arrays[name]);
  59618. }
  59619. // Color4
  59620. for (name in this._colors4) {
  59621. var color = this._colors4[name];
  59622. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59623. }
  59624. // Vector2
  59625. for (name in this._vectors2) {
  59626. this._effect.setVector2(name, this._vectors2[name]);
  59627. }
  59628. // Vector3
  59629. for (name in this._vectors3) {
  59630. this._effect.setVector3(name, this._vectors3[name]);
  59631. }
  59632. // Vector4
  59633. for (name in this._vectors4) {
  59634. this._effect.setVector4(name, this._vectors4[name]);
  59635. }
  59636. // Matrix
  59637. for (name in this._matrices) {
  59638. this._effect.setMatrix(name, this._matrices[name]);
  59639. }
  59640. // Matrix 3x3
  59641. for (name in this._matrices3x3) {
  59642. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59643. }
  59644. // Matrix 2x2
  59645. for (name in this._matrices2x2) {
  59646. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59647. }
  59648. // Vector2Array
  59649. for (name in this._vectors2Arrays) {
  59650. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59651. }
  59652. // Vector3Array
  59653. for (name in this._vectors3Arrays) {
  59654. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59655. }
  59656. }
  59657. this._afterBind(mesh);
  59658. };
  59659. ShaderMaterial.prototype.getActiveTextures = function () {
  59660. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59661. for (var name in this._textures) {
  59662. activeTextures.push(this._textures[name]);
  59663. }
  59664. for (var name in this._textureArrays) {
  59665. var array = this._textureArrays[name];
  59666. for (var index = 0; index < array.length; index++) {
  59667. activeTextures.push(array[index]);
  59668. }
  59669. }
  59670. return activeTextures;
  59671. };
  59672. ShaderMaterial.prototype.hasTexture = function (texture) {
  59673. if (_super.prototype.hasTexture.call(this, texture)) {
  59674. return true;
  59675. }
  59676. for (var name in this._textures) {
  59677. if (this._textures[name] === texture) {
  59678. return true;
  59679. }
  59680. }
  59681. for (var name in this._textureArrays) {
  59682. var array = this._textureArrays[name];
  59683. for (var index = 0; index < array.length; index++) {
  59684. if (array[index] === texture) {
  59685. return true;
  59686. }
  59687. }
  59688. }
  59689. return false;
  59690. };
  59691. ShaderMaterial.prototype.clone = function (name) {
  59692. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59693. return newShaderMaterial;
  59694. };
  59695. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59696. if (forceDisposeTextures) {
  59697. var name;
  59698. for (name in this._textures) {
  59699. this._textures[name].dispose();
  59700. }
  59701. for (name in this._textureArrays) {
  59702. var array = this._textureArrays[name];
  59703. for (var index = 0; index < array.length; index++) {
  59704. array[index].dispose();
  59705. }
  59706. }
  59707. }
  59708. this._textures = {};
  59709. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59710. };
  59711. ShaderMaterial.prototype.serialize = function () {
  59712. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59713. serializationObject.customType = "BABYLON.ShaderMaterial";
  59714. serializationObject.options = this._options;
  59715. serializationObject.shaderPath = this._shaderPath;
  59716. var name;
  59717. // Texture
  59718. serializationObject.textures = {};
  59719. for (name in this._textures) {
  59720. serializationObject.textures[name] = this._textures[name].serialize();
  59721. }
  59722. // Texture arrays
  59723. serializationObject.textureArrays = {};
  59724. for (name in this._textureArrays) {
  59725. serializationObject.textureArrays[name] = [];
  59726. var array = this._textureArrays[name];
  59727. for (var index = 0; index < array.length; index++) {
  59728. serializationObject.textureArrays[name].push(array[index].serialize());
  59729. }
  59730. }
  59731. // Float
  59732. serializationObject.floats = {};
  59733. for (name in this._floats) {
  59734. serializationObject.floats[name] = this._floats[name];
  59735. }
  59736. // Float s
  59737. serializationObject.FloatArrays = {};
  59738. for (name in this._floatsArrays) {
  59739. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59740. }
  59741. // Color3
  59742. serializationObject.colors3 = {};
  59743. for (name in this._colors3) {
  59744. serializationObject.colors3[name] = this._colors3[name].asArray();
  59745. }
  59746. // Color3 array
  59747. serializationObject.colors3Arrays = {};
  59748. for (name in this._colors3Arrays) {
  59749. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59750. }
  59751. // Color4
  59752. serializationObject.colors4 = {};
  59753. for (name in this._colors4) {
  59754. serializationObject.colors4[name] = this._colors4[name].asArray();
  59755. }
  59756. // Vector2
  59757. serializationObject.vectors2 = {};
  59758. for (name in this._vectors2) {
  59759. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59760. }
  59761. // Vector3
  59762. serializationObject.vectors3 = {};
  59763. for (name in this._vectors3) {
  59764. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59765. }
  59766. // Vector4
  59767. serializationObject.vectors4 = {};
  59768. for (name in this._vectors4) {
  59769. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59770. }
  59771. // Matrix
  59772. serializationObject.matrices = {};
  59773. for (name in this._matrices) {
  59774. serializationObject.matrices[name] = this._matrices[name].asArray();
  59775. }
  59776. // Matrix 3x3
  59777. serializationObject.matrices3x3 = {};
  59778. for (name in this._matrices3x3) {
  59779. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59780. }
  59781. // Matrix 2x2
  59782. serializationObject.matrices2x2 = {};
  59783. for (name in this._matrices2x2) {
  59784. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59785. }
  59786. // Vector2Array
  59787. serializationObject.vectors2Arrays = {};
  59788. for (name in this._vectors2Arrays) {
  59789. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59790. }
  59791. // Vector3Array
  59792. serializationObject.vectors3Arrays = {};
  59793. for (name in this._vectors3Arrays) {
  59794. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59795. }
  59796. return serializationObject;
  59797. };
  59798. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59799. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59800. var name;
  59801. // Texture
  59802. for (name in source.textures) {
  59803. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59804. }
  59805. // Texture arrays
  59806. for (name in source.textureArrays) {
  59807. var array = source.textureArrays[name];
  59808. var textureArray = new Array();
  59809. for (var index = 0; index < array.length; index++) {
  59810. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59811. }
  59812. material.setTextureArray(name, textureArray);
  59813. }
  59814. // Float
  59815. for (name in source.floats) {
  59816. material.setFloat(name, source.floats[name]);
  59817. }
  59818. // Float s
  59819. for (name in source.floatsArrays) {
  59820. material.setFloats(name, source.floatsArrays[name]);
  59821. }
  59822. // Color3
  59823. for (name in source.colors3) {
  59824. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59825. }
  59826. // Color3 arrays
  59827. for (name in source.colors3Arrays) {
  59828. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59829. if (i % 3 === 0) {
  59830. arr.push([num]);
  59831. }
  59832. else {
  59833. arr[arr.length - 1].push(num);
  59834. }
  59835. return arr;
  59836. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59837. material.setColor3Array(name, colors);
  59838. }
  59839. // Color4
  59840. for (name in source.colors4) {
  59841. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59842. }
  59843. // Vector2
  59844. for (name in source.vectors2) {
  59845. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59846. }
  59847. // Vector3
  59848. for (name in source.vectors3) {
  59849. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59850. }
  59851. // Vector4
  59852. for (name in source.vectors4) {
  59853. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59854. }
  59855. // Matrix
  59856. for (name in source.matrices) {
  59857. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59858. }
  59859. // Matrix 3x3
  59860. for (name in source.matrices3x3) {
  59861. material.setMatrix3x3(name, source.matrices3x3[name]);
  59862. }
  59863. // Matrix 2x2
  59864. for (name in source.matrices2x2) {
  59865. material.setMatrix2x2(name, source.matrices2x2[name]);
  59866. }
  59867. // Vector2Array
  59868. for (name in source.vectors2Arrays) {
  59869. material.setArray2(name, source.vectors2Arrays[name]);
  59870. }
  59871. // Vector3Array
  59872. for (name in source.vectors3Arrays) {
  59873. material.setArray3(name, source.vectors3Arrays[name]);
  59874. }
  59875. return material;
  59876. };
  59877. return ShaderMaterial;
  59878. }(BABYLON.Material));
  59879. BABYLON.ShaderMaterial = ShaderMaterial;
  59880. })(BABYLON || (BABYLON = {}));
  59881. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59882. var BABYLON;
  59883. (function (BABYLON) {
  59884. var GroundMesh = /** @class */ (function (_super) {
  59885. __extends(GroundMesh, _super);
  59886. function GroundMesh(name, scene) {
  59887. var _this = _super.call(this, name, scene) || this;
  59888. _this.generateOctree = false;
  59889. return _this;
  59890. }
  59891. GroundMesh.prototype.getClassName = function () {
  59892. return "GroundMesh";
  59893. };
  59894. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59895. get: function () {
  59896. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59897. },
  59898. enumerable: true,
  59899. configurable: true
  59900. });
  59901. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59902. get: function () {
  59903. return this._subdivisionsX;
  59904. },
  59905. enumerable: true,
  59906. configurable: true
  59907. });
  59908. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59909. get: function () {
  59910. return this._subdivisionsY;
  59911. },
  59912. enumerable: true,
  59913. configurable: true
  59914. });
  59915. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59916. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59917. this._subdivisionsX = chunksCount;
  59918. this._subdivisionsY = chunksCount;
  59919. this.subdivide(chunksCount);
  59920. // Call the octree system optimization if it is defined.
  59921. var thisAsAny = this;
  59922. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  59923. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59924. }
  59925. };
  59926. /**
  59927. * Returns a height (y) value in the Worl system :
  59928. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59929. * Returns the ground y position if (x, z) are outside the ground surface.
  59930. */
  59931. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59932. var world = this.getWorldMatrix();
  59933. var invMat = BABYLON.Tmp.Matrix[5];
  59934. world.invertToRef(invMat);
  59935. var tmpVect = BABYLON.Tmp.Vector3[8];
  59936. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59937. x = tmpVect.x;
  59938. z = tmpVect.z;
  59939. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59940. return this.position.y;
  59941. }
  59942. if (!this._heightQuads || this._heightQuads.length == 0) {
  59943. this._initHeightQuads();
  59944. this._computeHeightQuads();
  59945. }
  59946. var facet = this._getFacetAt(x, z);
  59947. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59948. // return y in the World system
  59949. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59950. return tmpVect.y;
  59951. };
  59952. /**
  59953. * Returns a normalized vector (Vector3) orthogonal to the ground
  59954. * at the ground coordinates (x, z) expressed in the World system.
  59955. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59956. */
  59957. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59958. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59959. this.getNormalAtCoordinatesToRef(x, z, normal);
  59960. return normal;
  59961. };
  59962. /**
  59963. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59964. * at the ground coordinates (x, z) expressed in the World system.
  59965. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59966. * Returns the GroundMesh.
  59967. */
  59968. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59969. var world = this.getWorldMatrix();
  59970. var tmpMat = BABYLON.Tmp.Matrix[5];
  59971. world.invertToRef(tmpMat);
  59972. var tmpVect = BABYLON.Tmp.Vector3[8];
  59973. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59974. x = tmpVect.x;
  59975. z = tmpVect.z;
  59976. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59977. return this;
  59978. }
  59979. if (!this._heightQuads || this._heightQuads.length == 0) {
  59980. this._initHeightQuads();
  59981. this._computeHeightQuads();
  59982. }
  59983. var facet = this._getFacetAt(x, z);
  59984. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59985. return this;
  59986. };
  59987. /**
  59988. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59989. * if the ground has been updated.
  59990. * This can be used in the render loop.
  59991. * Returns the GroundMesh.
  59992. */
  59993. GroundMesh.prototype.updateCoordinateHeights = function () {
  59994. if (!this._heightQuads || this._heightQuads.length == 0) {
  59995. this._initHeightQuads();
  59996. }
  59997. this._computeHeightQuads();
  59998. return this;
  59999. };
  60000. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60001. GroundMesh.prototype._getFacetAt = function (x, z) {
  60002. // retrieve col and row from x, z coordinates in the ground local system
  60003. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60004. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60005. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60006. var facet;
  60007. if (z < quad.slope.x * x + quad.slope.y) {
  60008. facet = quad.facet1;
  60009. }
  60010. else {
  60011. facet = quad.facet2;
  60012. }
  60013. return facet;
  60014. };
  60015. // Creates and populates the heightMap array with "facet" elements :
  60016. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60017. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60018. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60019. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60020. // Returns the GroundMesh.
  60021. GroundMesh.prototype._initHeightQuads = function () {
  60022. var subdivisionsX = this._subdivisionsX;
  60023. var subdivisionsY = this._subdivisionsY;
  60024. this._heightQuads = new Array();
  60025. for (var row = 0; row < subdivisionsY; row++) {
  60026. for (var col = 0; col < subdivisionsX; col++) {
  60027. 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) };
  60028. this._heightQuads[row * subdivisionsX + col] = quad;
  60029. }
  60030. }
  60031. return this;
  60032. };
  60033. // Compute each quad element values and update the the heightMap array :
  60034. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60035. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60036. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60037. // Returns the GroundMesh.
  60038. GroundMesh.prototype._computeHeightQuads = function () {
  60039. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60040. if (!positions) {
  60041. return this;
  60042. }
  60043. var v1 = BABYLON.Tmp.Vector3[3];
  60044. var v2 = BABYLON.Tmp.Vector3[2];
  60045. var v3 = BABYLON.Tmp.Vector3[1];
  60046. var v4 = BABYLON.Tmp.Vector3[0];
  60047. var v1v2 = BABYLON.Tmp.Vector3[4];
  60048. var v1v3 = BABYLON.Tmp.Vector3[5];
  60049. var v1v4 = BABYLON.Tmp.Vector3[6];
  60050. var norm1 = BABYLON.Tmp.Vector3[7];
  60051. var norm2 = BABYLON.Tmp.Vector3[8];
  60052. var i = 0;
  60053. var j = 0;
  60054. var k = 0;
  60055. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60056. var h = 0;
  60057. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60058. var d2 = 0;
  60059. var subdivisionsX = this._subdivisionsX;
  60060. var subdivisionsY = this._subdivisionsY;
  60061. for (var row = 0; row < subdivisionsY; row++) {
  60062. for (var col = 0; col < subdivisionsX; col++) {
  60063. i = col * 3;
  60064. j = row * (subdivisionsX + 1) * 3;
  60065. k = (row + 1) * (subdivisionsX + 1) * 3;
  60066. v1.x = positions[j + i];
  60067. v1.y = positions[j + i + 1];
  60068. v1.z = positions[j + i + 2];
  60069. v2.x = positions[j + i + 3];
  60070. v2.y = positions[j + i + 4];
  60071. v2.z = positions[j + i + 5];
  60072. v3.x = positions[k + i];
  60073. v3.y = positions[k + i + 1];
  60074. v3.z = positions[k + i + 2];
  60075. v4.x = positions[k + i + 3];
  60076. v4.y = positions[k + i + 4];
  60077. v4.z = positions[k + i + 5];
  60078. // 2D slope V1V4
  60079. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60080. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60081. // facet equations :
  60082. // we compute each facet normal vector
  60083. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60084. // we compute the value d by applying the equation to v1 which belongs to the plane
  60085. // then we store the facet equation in a Vector4
  60086. v2.subtractToRef(v1, v1v2);
  60087. v3.subtractToRef(v1, v1v3);
  60088. v4.subtractToRef(v1, v1v4);
  60089. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60090. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60091. norm1.normalize();
  60092. norm2.normalize();
  60093. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60094. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60095. var quad = this._heightQuads[row * subdivisionsX + col];
  60096. quad.slope.copyFromFloats(cd, h);
  60097. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60098. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60099. }
  60100. }
  60101. return this;
  60102. };
  60103. GroundMesh.prototype.serialize = function (serializationObject) {
  60104. _super.prototype.serialize.call(this, serializationObject);
  60105. serializationObject.subdivisionsX = this._subdivisionsX;
  60106. serializationObject.subdivisionsY = this._subdivisionsY;
  60107. serializationObject.minX = this._minX;
  60108. serializationObject.maxX = this._maxX;
  60109. serializationObject.minZ = this._minZ;
  60110. serializationObject.maxZ = this._maxZ;
  60111. serializationObject.width = this._width;
  60112. serializationObject.height = this._height;
  60113. };
  60114. GroundMesh.Parse = function (parsedMesh, scene) {
  60115. var result = new GroundMesh(parsedMesh.name, scene);
  60116. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60117. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60118. result._minX = parsedMesh.minX;
  60119. result._maxX = parsedMesh.maxX;
  60120. result._minZ = parsedMesh.minZ;
  60121. result._maxZ = parsedMesh.maxZ;
  60122. result._width = parsedMesh.width;
  60123. result._height = parsedMesh.height;
  60124. return result;
  60125. };
  60126. return GroundMesh;
  60127. }(BABYLON.Mesh));
  60128. BABYLON.GroundMesh = GroundMesh;
  60129. })(BABYLON || (BABYLON = {}));
  60130. //# sourceMappingURL=babylon.groundMesh.js.map
  60131. var BABYLON;
  60132. (function (BABYLON) {
  60133. /**
  60134. * Creates an instance based on a source mesh.
  60135. */
  60136. var InstancedMesh = /** @class */ (function (_super) {
  60137. __extends(InstancedMesh, _super);
  60138. function InstancedMesh(name, source) {
  60139. var _this = _super.call(this, name, source.getScene()) || this;
  60140. source.instances.push(_this);
  60141. _this._sourceMesh = source;
  60142. _this.position.copyFrom(source.position);
  60143. _this.rotation.copyFrom(source.rotation);
  60144. _this.scaling.copyFrom(source.scaling);
  60145. if (source.rotationQuaternion) {
  60146. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60147. }
  60148. _this.infiniteDistance = source.infiniteDistance;
  60149. _this.setPivotMatrix(source.getPivotMatrix());
  60150. _this.refreshBoundingInfo();
  60151. _this._syncSubMeshes();
  60152. return _this;
  60153. }
  60154. /**
  60155. * Returns the string "InstancedMesh".
  60156. */
  60157. InstancedMesh.prototype.getClassName = function () {
  60158. return "InstancedMesh";
  60159. };
  60160. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60161. // Methods
  60162. get: function () {
  60163. return this._sourceMesh.receiveShadows;
  60164. },
  60165. enumerable: true,
  60166. configurable: true
  60167. });
  60168. Object.defineProperty(InstancedMesh.prototype, "material", {
  60169. get: function () {
  60170. return this._sourceMesh.material;
  60171. },
  60172. enumerable: true,
  60173. configurable: true
  60174. });
  60175. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60176. get: function () {
  60177. return this._sourceMesh.visibility;
  60178. },
  60179. enumerable: true,
  60180. configurable: true
  60181. });
  60182. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60183. get: function () {
  60184. return this._sourceMesh.skeleton;
  60185. },
  60186. enumerable: true,
  60187. configurable: true
  60188. });
  60189. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60190. get: function () {
  60191. return this._sourceMesh.renderingGroupId;
  60192. },
  60193. set: function (value) {
  60194. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60195. return;
  60196. }
  60197. //no-op with warning
  60198. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60199. },
  60200. enumerable: true,
  60201. configurable: true
  60202. });
  60203. /**
  60204. * Returns the total number of vertices (integer).
  60205. */
  60206. InstancedMesh.prototype.getTotalVertices = function () {
  60207. return this._sourceMesh.getTotalVertices();
  60208. };
  60209. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60210. get: function () {
  60211. return this._sourceMesh;
  60212. },
  60213. enumerable: true,
  60214. configurable: true
  60215. });
  60216. /**
  60217. * Is this node ready to be used/rendered
  60218. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60219. * @return {boolean} is it ready
  60220. */
  60221. InstancedMesh.prototype.isReady = function (completeCheck) {
  60222. if (completeCheck === void 0) { completeCheck = false; }
  60223. return this._sourceMesh.isReady(completeCheck, true);
  60224. };
  60225. /**
  60226. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60227. */
  60228. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60229. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60230. };
  60231. /**
  60232. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60233. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60234. * The `data` are either a numeric array either a Float32Array.
  60235. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60236. * 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).
  60237. * Note that a new underlying VertexBuffer object is created each call.
  60238. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60239. *
  60240. * Possible `kind` values :
  60241. * - BABYLON.VertexBuffer.PositionKind
  60242. * - BABYLON.VertexBuffer.UVKind
  60243. * - BABYLON.VertexBuffer.UV2Kind
  60244. * - BABYLON.VertexBuffer.UV3Kind
  60245. * - BABYLON.VertexBuffer.UV4Kind
  60246. * - BABYLON.VertexBuffer.UV5Kind
  60247. * - BABYLON.VertexBuffer.UV6Kind
  60248. * - BABYLON.VertexBuffer.ColorKind
  60249. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60250. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60251. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60252. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60253. *
  60254. * Returns the Mesh.
  60255. */
  60256. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60257. if (this.sourceMesh) {
  60258. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60259. }
  60260. return this.sourceMesh;
  60261. };
  60262. /**
  60263. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60264. * If the mesh has no geometry, it is simply returned as it is.
  60265. * The `data` are either a numeric array either a Float32Array.
  60266. * No new underlying VertexBuffer object is created.
  60267. * 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.
  60268. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60269. *
  60270. * Possible `kind` values :
  60271. * - BABYLON.VertexBuffer.PositionKind
  60272. * - BABYLON.VertexBuffer.UVKind
  60273. * - BABYLON.VertexBuffer.UV2Kind
  60274. * - BABYLON.VertexBuffer.UV3Kind
  60275. * - BABYLON.VertexBuffer.UV4Kind
  60276. * - BABYLON.VertexBuffer.UV5Kind
  60277. * - BABYLON.VertexBuffer.UV6Kind
  60278. * - BABYLON.VertexBuffer.ColorKind
  60279. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60280. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60281. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60282. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60283. *
  60284. * Returns the Mesh.
  60285. */
  60286. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60287. if (this.sourceMesh) {
  60288. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60289. }
  60290. return this.sourceMesh;
  60291. };
  60292. /**
  60293. * Sets the mesh indices.
  60294. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60295. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60296. * This method creates a new index buffer each call.
  60297. * Returns the Mesh.
  60298. */
  60299. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60300. if (totalVertices === void 0) { totalVertices = null; }
  60301. if (this.sourceMesh) {
  60302. this.sourceMesh.setIndices(indices, totalVertices);
  60303. }
  60304. return this.sourceMesh;
  60305. };
  60306. /**
  60307. * Boolean : True if the mesh owns the requested kind of data.
  60308. */
  60309. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60310. return this._sourceMesh.isVerticesDataPresent(kind);
  60311. };
  60312. /**
  60313. * Returns an array of indices (IndicesArray).
  60314. */
  60315. InstancedMesh.prototype.getIndices = function () {
  60316. return this._sourceMesh.getIndices();
  60317. };
  60318. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60319. get: function () {
  60320. return this._sourceMesh._positions;
  60321. },
  60322. enumerable: true,
  60323. configurable: true
  60324. });
  60325. /**
  60326. * Sets a new updated BoundingInfo to the mesh.
  60327. * Returns the mesh.
  60328. */
  60329. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60330. var meshBB = this._sourceMesh.getBoundingInfo();
  60331. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60332. this._updateBoundingInfo();
  60333. return this;
  60334. };
  60335. /** @hidden */
  60336. InstancedMesh.prototype._preActivate = function () {
  60337. if (this._currentLOD) {
  60338. this._currentLOD._preActivate();
  60339. }
  60340. return this;
  60341. };
  60342. /** @hidden */
  60343. InstancedMesh.prototype._activate = function (renderId) {
  60344. if (this._currentLOD) {
  60345. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60346. }
  60347. return this;
  60348. };
  60349. /**
  60350. * Returns the current associated LOD AbstractMesh.
  60351. */
  60352. InstancedMesh.prototype.getLOD = function (camera) {
  60353. if (!camera) {
  60354. return this;
  60355. }
  60356. var boundingInfo = this.getBoundingInfo();
  60357. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60358. if (this._currentLOD === this.sourceMesh) {
  60359. return this;
  60360. }
  60361. return this._currentLOD;
  60362. };
  60363. /** @hidden */
  60364. InstancedMesh.prototype._syncSubMeshes = function () {
  60365. this.releaseSubMeshes();
  60366. if (this._sourceMesh.subMeshes) {
  60367. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60368. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60369. }
  60370. }
  60371. return this;
  60372. };
  60373. /** @hidden */
  60374. InstancedMesh.prototype._generatePointsArray = function () {
  60375. return this._sourceMesh._generatePointsArray();
  60376. };
  60377. /**
  60378. * Creates a new InstancedMesh from the current mesh.
  60379. * - name (string) : the cloned mesh name
  60380. * - newParent (optional Node) : the optional Node to parent the clone to.
  60381. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60382. *
  60383. * Returns the clone.
  60384. */
  60385. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60386. var result = this._sourceMesh.createInstance(name);
  60387. // Deep copy
  60388. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60389. // Bounding info
  60390. this.refreshBoundingInfo();
  60391. // Parent
  60392. if (newParent) {
  60393. result.parent = newParent;
  60394. }
  60395. if (!doNotCloneChildren) {
  60396. // Children
  60397. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60398. var mesh = this.getScene().meshes[index];
  60399. if (mesh.parent === this) {
  60400. mesh.clone(mesh.name, result);
  60401. }
  60402. }
  60403. }
  60404. result.computeWorldMatrix(true);
  60405. return result;
  60406. };
  60407. /**
  60408. * Disposes the InstancedMesh.
  60409. * Returns nothing.
  60410. */
  60411. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60412. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60413. // Remove from mesh
  60414. var index = this._sourceMesh.instances.indexOf(this);
  60415. this._sourceMesh.instances.splice(index, 1);
  60416. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60417. };
  60418. return InstancedMesh;
  60419. }(BABYLON.AbstractMesh));
  60420. BABYLON.InstancedMesh = InstancedMesh;
  60421. })(BABYLON || (BABYLON = {}));
  60422. //# sourceMappingURL=babylon.instancedMesh.js.map
  60423. var BABYLON;
  60424. (function (BABYLON) {
  60425. var LinesMesh = /** @class */ (function (_super) {
  60426. __extends(LinesMesh, _super);
  60427. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60428. if (scene === void 0) { scene = null; }
  60429. if (parent === void 0) { parent = null; }
  60430. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60431. _this.useVertexColor = useVertexColor;
  60432. _this.useVertexAlpha = useVertexAlpha;
  60433. _this.color = new BABYLON.Color3(1, 1, 1);
  60434. _this.alpha = 1;
  60435. if (source) {
  60436. _this.color = source.color.clone();
  60437. _this.alpha = source.alpha;
  60438. _this.useVertexColor = source.useVertexColor;
  60439. _this.useVertexAlpha = source.useVertexAlpha;
  60440. }
  60441. _this._intersectionThreshold = 0.1;
  60442. var defines = [];
  60443. var options = {
  60444. attributes: [BABYLON.VertexBuffer.PositionKind],
  60445. uniforms: ["world", "viewProjection"],
  60446. needAlphaBlending: true,
  60447. defines: defines
  60448. };
  60449. if (useVertexAlpha === false) {
  60450. options.needAlphaBlending = false;
  60451. }
  60452. if (!useVertexColor) {
  60453. options.uniforms.push("color");
  60454. }
  60455. else {
  60456. options.defines.push("#define VERTEXCOLOR");
  60457. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60458. }
  60459. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60460. return _this;
  60461. }
  60462. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60463. /**
  60464. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60465. * This margin is expressed in world space coordinates, so its value may vary.
  60466. * Default value is 0.1
  60467. * @returns the intersection Threshold value.
  60468. */
  60469. get: function () {
  60470. return this._intersectionThreshold;
  60471. },
  60472. /**
  60473. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60474. * This margin is expressed in world space coordinates, so its value may vary.
  60475. * @param value the new threshold to apply
  60476. */
  60477. set: function (value) {
  60478. if (this._intersectionThreshold === value) {
  60479. return;
  60480. }
  60481. this._intersectionThreshold = value;
  60482. if (this.geometry) {
  60483. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60484. }
  60485. },
  60486. enumerable: true,
  60487. configurable: true
  60488. });
  60489. /**
  60490. * Returns the string "LineMesh"
  60491. */
  60492. LinesMesh.prototype.getClassName = function () {
  60493. return "LinesMesh";
  60494. };
  60495. Object.defineProperty(LinesMesh.prototype, "material", {
  60496. /**
  60497. * @hidden
  60498. */
  60499. get: function () {
  60500. return this._colorShader;
  60501. },
  60502. /**
  60503. * @hidden
  60504. */
  60505. set: function (value) {
  60506. // Do nothing
  60507. },
  60508. enumerable: true,
  60509. configurable: true
  60510. });
  60511. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60512. /**
  60513. * @hidden
  60514. */
  60515. get: function () {
  60516. return false;
  60517. },
  60518. enumerable: true,
  60519. configurable: true
  60520. });
  60521. LinesMesh.prototype.createInstance = function (name) {
  60522. throw new Error("LinesMeshes do not support createInstance.");
  60523. };
  60524. /** @hidden */
  60525. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60526. if (!this._geometry) {
  60527. return this;
  60528. }
  60529. // VBOs
  60530. this._geometry._bind(this._colorShader.getEffect());
  60531. // Color
  60532. if (!this.useVertexColor) {
  60533. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60534. }
  60535. return this;
  60536. };
  60537. /** @hidden */
  60538. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60539. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60540. return this;
  60541. }
  60542. var engine = this.getScene().getEngine();
  60543. // Draw order
  60544. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60545. return this;
  60546. };
  60547. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60548. this._colorShader.dispose();
  60549. _super.prototype.dispose.call(this, doNotRecurse);
  60550. };
  60551. /**
  60552. * Returns a new LineMesh object cloned from the current one.
  60553. */
  60554. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60555. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60556. };
  60557. return LinesMesh;
  60558. }(BABYLON.Mesh));
  60559. BABYLON.LinesMesh = LinesMesh;
  60560. })(BABYLON || (BABYLON = {}));
  60561. //# sourceMappingURL=babylon.linesMesh.js.map
  60562. var BABYLON;
  60563. (function (BABYLON) {
  60564. /**
  60565. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60566. * The underlying implementation relies on an associative array to ensure the best performances.
  60567. * The value can be anything including 'null' but except 'undefined'
  60568. */
  60569. var StringDictionary = /** @class */ (function () {
  60570. function StringDictionary() {
  60571. this._count = 0;
  60572. this._data = {};
  60573. }
  60574. /**
  60575. * This will clear this dictionary and copy the content from the 'source' one.
  60576. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60577. * @param source the dictionary to take the content from and copy to this dictionary
  60578. */
  60579. StringDictionary.prototype.copyFrom = function (source) {
  60580. var _this = this;
  60581. this.clear();
  60582. source.forEach(function (t, v) { return _this.add(t, v); });
  60583. };
  60584. /**
  60585. * Get a value based from its key
  60586. * @param key the given key to get the matching value from
  60587. * @return the value if found, otherwise undefined is returned
  60588. */
  60589. StringDictionary.prototype.get = function (key) {
  60590. var val = this._data[key];
  60591. if (val !== undefined) {
  60592. return val;
  60593. }
  60594. return undefined;
  60595. };
  60596. /**
  60597. * Get a value from its key or add it if it doesn't exist.
  60598. * This method will ensure you that a given key/data will be present in the dictionary.
  60599. * @param key the given key to get the matching value from
  60600. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60601. * The factory will only be invoked if there's no data for the given key.
  60602. * @return the value corresponding to the key.
  60603. */
  60604. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60605. var val = this.get(key);
  60606. if (val !== undefined) {
  60607. return val;
  60608. }
  60609. val = factory(key);
  60610. if (val) {
  60611. this.add(key, val);
  60612. }
  60613. return val;
  60614. };
  60615. /**
  60616. * Get a value from its key if present in the dictionary otherwise add it
  60617. * @param key the key to get the value from
  60618. * @param val if there's no such key/value pair in the dictionary add it with this value
  60619. * @return the value corresponding to the key
  60620. */
  60621. StringDictionary.prototype.getOrAdd = function (key, val) {
  60622. var curVal = this.get(key);
  60623. if (curVal !== undefined) {
  60624. return curVal;
  60625. }
  60626. this.add(key, val);
  60627. return val;
  60628. };
  60629. /**
  60630. * Check if there's a given key in the dictionary
  60631. * @param key the key to check for
  60632. * @return true if the key is present, false otherwise
  60633. */
  60634. StringDictionary.prototype.contains = function (key) {
  60635. return this._data[key] !== undefined;
  60636. };
  60637. /**
  60638. * Add a new key and its corresponding value
  60639. * @param key the key to add
  60640. * @param value the value corresponding to the key
  60641. * @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
  60642. */
  60643. StringDictionary.prototype.add = function (key, value) {
  60644. if (this._data[key] !== undefined) {
  60645. return false;
  60646. }
  60647. this._data[key] = value;
  60648. ++this._count;
  60649. return true;
  60650. };
  60651. StringDictionary.prototype.set = function (key, value) {
  60652. if (this._data[key] === undefined) {
  60653. return false;
  60654. }
  60655. this._data[key] = value;
  60656. return true;
  60657. };
  60658. /**
  60659. * Get the element of the given key and remove it from the dictionary
  60660. * @param key
  60661. */
  60662. StringDictionary.prototype.getAndRemove = function (key) {
  60663. var val = this.get(key);
  60664. if (val !== undefined) {
  60665. delete this._data[key];
  60666. --this._count;
  60667. return val;
  60668. }
  60669. return null;
  60670. };
  60671. /**
  60672. * Remove a key/value from the dictionary.
  60673. * @param key the key to remove
  60674. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60675. */
  60676. StringDictionary.prototype.remove = function (key) {
  60677. if (this.contains(key)) {
  60678. delete this._data[key];
  60679. --this._count;
  60680. return true;
  60681. }
  60682. return false;
  60683. };
  60684. /**
  60685. * Clear the whole content of the dictionary
  60686. */
  60687. StringDictionary.prototype.clear = function () {
  60688. this._data = {};
  60689. this._count = 0;
  60690. };
  60691. Object.defineProperty(StringDictionary.prototype, "count", {
  60692. get: function () {
  60693. return this._count;
  60694. },
  60695. enumerable: true,
  60696. configurable: true
  60697. });
  60698. /**
  60699. * Execute a callback on each key/val of the dictionary.
  60700. * Note that you can remove any element in this dictionary in the callback implementation
  60701. * @param callback the callback to execute on a given key/value pair
  60702. */
  60703. StringDictionary.prototype.forEach = function (callback) {
  60704. for (var cur in this._data) {
  60705. var val = this._data[cur];
  60706. callback(cur, val);
  60707. }
  60708. };
  60709. /**
  60710. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60711. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60712. * Note that you can remove any element in this dictionary in the callback implementation
  60713. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60714. */
  60715. StringDictionary.prototype.first = function (callback) {
  60716. for (var cur in this._data) {
  60717. var val = this._data[cur];
  60718. var res = callback(cur, val);
  60719. if (res) {
  60720. return res;
  60721. }
  60722. }
  60723. return null;
  60724. };
  60725. return StringDictionary;
  60726. }());
  60727. BABYLON.StringDictionary = StringDictionary;
  60728. })(BABYLON || (BABYLON = {}));
  60729. //# sourceMappingURL=babylon.stringDictionary.js.map
  60730. var BABYLON;
  60731. (function (BABYLON) {
  60732. var Debug;
  60733. (function (Debug) {
  60734. /**
  60735. * Class used to render a debug view of a given skeleton
  60736. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  60737. */
  60738. var SkeletonViewer = /** @class */ (function () {
  60739. /**
  60740. * Creates a new SkeletonViewer
  60741. * @param skeleton defines the skeleton to render
  60742. * @param mesh defines the mesh attached to the skeleton
  60743. * @param scene defines the hosting scene
  60744. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  60745. * @param renderingGroupId defines the rendering group id to use with the viewer
  60746. */
  60747. function SkeletonViewer(
  60748. /** defines the skeleton to render */
  60749. skeleton,
  60750. /** defines the mesh attached to the skeleton */
  60751. mesh, scene,
  60752. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  60753. autoUpdateBonesMatrices,
  60754. /** defines the rendering group id to use with the viewer */
  60755. renderingGroupId) {
  60756. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60757. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60758. this.skeleton = skeleton;
  60759. this.mesh = mesh;
  60760. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60761. this.renderingGroupId = renderingGroupId;
  60762. /** Gets or sets the color used to render the skeleton */
  60763. this.color = BABYLON.Color3.White();
  60764. this._debugLines = new Array();
  60765. this._isEnabled = false;
  60766. this._scene = scene;
  60767. this.update();
  60768. this._renderFunction = this.update.bind(this);
  60769. }
  60770. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60771. get: function () {
  60772. return this._isEnabled;
  60773. },
  60774. /** Gets or sets a boolean indicating if the viewer is enabled */
  60775. set: function (value) {
  60776. if (this._isEnabled === value) {
  60777. return;
  60778. }
  60779. this._isEnabled = value;
  60780. if (value) {
  60781. this._scene.registerBeforeRender(this._renderFunction);
  60782. }
  60783. else {
  60784. this._scene.unregisterBeforeRender(this._renderFunction);
  60785. }
  60786. },
  60787. enumerable: true,
  60788. configurable: true
  60789. });
  60790. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60791. if (x === void 0) { x = 0; }
  60792. if (y === void 0) { y = 0; }
  60793. if (z === void 0) { z = 0; }
  60794. var tmat = BABYLON.Tmp.Matrix[0];
  60795. var parentBone = bone.getParent();
  60796. tmat.copyFrom(bone.getLocalMatrix());
  60797. if (x !== 0 || y !== 0 || z !== 0) {
  60798. var tmat2 = BABYLON.Tmp.Matrix[1];
  60799. BABYLON.Matrix.IdentityToRef(tmat2);
  60800. tmat2.m[12] = x;
  60801. tmat2.m[13] = y;
  60802. tmat2.m[14] = z;
  60803. tmat2.multiplyToRef(tmat, tmat);
  60804. }
  60805. if (parentBone) {
  60806. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60807. }
  60808. tmat.multiplyToRef(meshMat, tmat);
  60809. position.x = tmat.m[12];
  60810. position.y = tmat.m[13];
  60811. position.z = tmat.m[14];
  60812. };
  60813. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60814. var len = bones.length;
  60815. var meshPos = this.mesh.position;
  60816. for (var i = 0; i < len; i++) {
  60817. var bone = bones[i];
  60818. var points = this._debugLines[i];
  60819. if (!points) {
  60820. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60821. this._debugLines[i] = points;
  60822. }
  60823. this._getBonePosition(points[0], bone, meshMat);
  60824. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60825. points[0].subtractInPlace(meshPos);
  60826. points[1].subtractInPlace(meshPos);
  60827. }
  60828. };
  60829. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60830. var len = bones.length;
  60831. var boneNum = 0;
  60832. var meshPos = this.mesh.position;
  60833. for (var i = len - 1; i >= 0; i--) {
  60834. var childBone = bones[i];
  60835. var parentBone = childBone.getParent();
  60836. if (!parentBone) {
  60837. continue;
  60838. }
  60839. var points = this._debugLines[boneNum];
  60840. if (!points) {
  60841. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60842. this._debugLines[boneNum] = points;
  60843. }
  60844. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60845. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60846. points[0].subtractInPlace(meshPos);
  60847. points[1].subtractInPlace(meshPos);
  60848. boneNum++;
  60849. }
  60850. };
  60851. /** Update the viewer to sync with current skeleton state */
  60852. SkeletonViewer.prototype.update = function () {
  60853. if (this.autoUpdateBonesMatrices) {
  60854. this.skeleton.computeAbsoluteTransforms();
  60855. }
  60856. if (this.skeleton.bones[0].length === undefined) {
  60857. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60858. }
  60859. else {
  60860. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60861. }
  60862. if (!this._debugMesh) {
  60863. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60864. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60865. }
  60866. else {
  60867. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60868. }
  60869. this._debugMesh.position.copyFrom(this.mesh.position);
  60870. this._debugMesh.color = this.color;
  60871. };
  60872. /** Release associated resources */
  60873. SkeletonViewer.prototype.dispose = function () {
  60874. if (this._debugMesh) {
  60875. this.isEnabled = false;
  60876. this._debugMesh.dispose();
  60877. this._debugMesh = null;
  60878. }
  60879. };
  60880. return SkeletonViewer;
  60881. }());
  60882. Debug.SkeletonViewer = SkeletonViewer;
  60883. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60884. })(BABYLON || (BABYLON = {}));
  60885. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60886. /**
  60887. * Module Debug contains the (visual) components to debug a scene correctly
  60888. */
  60889. var BABYLON;
  60890. (function (BABYLON) {
  60891. var Debug;
  60892. (function (Debug) {
  60893. /**
  60894. * The Axes viewer will show 3 axes in a specific point in space
  60895. */
  60896. var AxesViewer = /** @class */ (function () {
  60897. /**
  60898. * Creates a new AxesViewer
  60899. * @param scene defines the hosting scene
  60900. * @param scaleLines defines a number used to scale line length (1 by default)
  60901. */
  60902. function AxesViewer(scene, scaleLines) {
  60903. if (scaleLines === void 0) { scaleLines = 1; }
  60904. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60905. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60906. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60907. /**
  60908. * Gets or sets a number used to scale line length
  60909. */
  60910. this.scaleLines = 1;
  60911. this.scaleLines = scaleLines;
  60912. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60913. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60914. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60915. this._xmesh.renderingGroupId = 2;
  60916. this._ymesh.renderingGroupId = 2;
  60917. this._zmesh.renderingGroupId = 2;
  60918. this._xmesh.material.checkReadyOnlyOnce = true;
  60919. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60920. this._ymesh.material.checkReadyOnlyOnce = true;
  60921. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60922. this._zmesh.material.checkReadyOnlyOnce = true;
  60923. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60924. this.scene = scene;
  60925. }
  60926. /**
  60927. * Force the viewer to update
  60928. * @param position defines the position of the viewer
  60929. * @param xaxis defines the x axis of the viewer
  60930. * @param yaxis defines the y axis of the viewer
  60931. * @param zaxis defines the z axis of the viewer
  60932. */
  60933. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60934. var scaleLines = this.scaleLines;
  60935. if (this._xmesh) {
  60936. this._xmesh.position.copyFrom(position);
  60937. }
  60938. if (this._ymesh) {
  60939. this._ymesh.position.copyFrom(position);
  60940. }
  60941. if (this._zmesh) {
  60942. this._zmesh.position.copyFrom(position);
  60943. }
  60944. var point2 = this._xline[1];
  60945. point2.x = xaxis.x * scaleLines;
  60946. point2.y = xaxis.y * scaleLines;
  60947. point2.z = xaxis.z * scaleLines;
  60948. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60949. point2 = this._yline[1];
  60950. point2.x = yaxis.x * scaleLines;
  60951. point2.y = yaxis.y * scaleLines;
  60952. point2.z = yaxis.z * scaleLines;
  60953. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60954. point2 = this._zline[1];
  60955. point2.x = zaxis.x * scaleLines;
  60956. point2.y = zaxis.y * scaleLines;
  60957. point2.z = zaxis.z * scaleLines;
  60958. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60959. };
  60960. /** Releases resources */
  60961. AxesViewer.prototype.dispose = function () {
  60962. if (this._xmesh) {
  60963. this._xmesh.dispose();
  60964. }
  60965. if (this._ymesh) {
  60966. this._ymesh.dispose();
  60967. }
  60968. if (this._zmesh) {
  60969. this._zmesh.dispose();
  60970. }
  60971. this._xmesh = null;
  60972. this._ymesh = null;
  60973. this._zmesh = null;
  60974. this.scene = null;
  60975. };
  60976. return AxesViewer;
  60977. }());
  60978. Debug.AxesViewer = AxesViewer;
  60979. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60980. })(BABYLON || (BABYLON = {}));
  60981. //# sourceMappingURL=babylon.axesViewer.js.map
  60982. var BABYLON;
  60983. (function (BABYLON) {
  60984. var Debug;
  60985. (function (Debug) {
  60986. /**
  60987. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60988. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60989. */
  60990. var BoneAxesViewer = /** @class */ (function (_super) {
  60991. __extends(BoneAxesViewer, _super);
  60992. /**
  60993. * Creates a new BoneAxesViewer
  60994. * @param scene defines the hosting scene
  60995. * @param bone defines the target bone
  60996. * @param mesh defines the target mesh
  60997. * @param scaleLines defines a scaling factor for line length (1 by default)
  60998. */
  60999. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  61000. if (scaleLines === void 0) { scaleLines = 1; }
  61001. var _this = _super.call(this, scene, scaleLines) || this;
  61002. /** Gets current position */
  61003. _this.pos = BABYLON.Vector3.Zero();
  61004. /** Gets direction of X axis */
  61005. _this.xaxis = BABYLON.Vector3.Zero();
  61006. /** Gets direction of Y axis */
  61007. _this.yaxis = BABYLON.Vector3.Zero();
  61008. /** Gets direction of Z axis */
  61009. _this.zaxis = BABYLON.Vector3.Zero();
  61010. _this.mesh = mesh;
  61011. _this.bone = bone;
  61012. return _this;
  61013. }
  61014. /**
  61015. * Force the viewer to update
  61016. */
  61017. BoneAxesViewer.prototype.update = function () {
  61018. if (!this.mesh || !this.bone) {
  61019. return;
  61020. }
  61021. var bone = this.bone;
  61022. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  61023. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  61024. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  61025. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  61026. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  61027. };
  61028. /** Releases resources */
  61029. BoneAxesViewer.prototype.dispose = function () {
  61030. if (this.mesh) {
  61031. this.mesh = null;
  61032. this.bone = null;
  61033. _super.prototype.dispose.call(this);
  61034. }
  61035. };
  61036. return BoneAxesViewer;
  61037. }(Debug.AxesViewer));
  61038. Debug.BoneAxesViewer = BoneAxesViewer;
  61039. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61040. })(BABYLON || (BABYLON = {}));
  61041. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  61042. var BABYLON;
  61043. (function (BABYLON) {
  61044. var RayHelper = /** @class */ (function () {
  61045. function RayHelper(ray) {
  61046. this.ray = ray;
  61047. }
  61048. RayHelper.CreateAndShow = function (ray, scene, color) {
  61049. var helper = new RayHelper(ray);
  61050. helper.show(scene, color);
  61051. return helper;
  61052. };
  61053. RayHelper.prototype.show = function (scene, color) {
  61054. if (!this._renderFunction && this.ray) {
  61055. var ray = this.ray;
  61056. this._renderFunction = this._render.bind(this);
  61057. this._scene = scene;
  61058. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  61059. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  61060. if (this._renderFunction) {
  61061. this._scene.registerBeforeRender(this._renderFunction);
  61062. }
  61063. }
  61064. if (color && this._renderLine) {
  61065. this._renderLine.color.copyFrom(color);
  61066. }
  61067. };
  61068. RayHelper.prototype.hide = function () {
  61069. if (this._renderFunction && this._scene) {
  61070. this._scene.unregisterBeforeRender(this._renderFunction);
  61071. this._scene = null;
  61072. this._renderFunction = null;
  61073. if (this._renderLine) {
  61074. this._renderLine.dispose();
  61075. this._renderLine = null;
  61076. }
  61077. this._renderPoints = [];
  61078. }
  61079. };
  61080. RayHelper.prototype._render = function () {
  61081. var ray = this.ray;
  61082. if (!ray) {
  61083. return;
  61084. }
  61085. var point = this._renderPoints[1];
  61086. var len = Math.min(ray.length, 1000000);
  61087. point.copyFrom(ray.direction);
  61088. point.scaleInPlace(len);
  61089. point.addInPlace(ray.origin);
  61090. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  61091. };
  61092. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  61093. this._attachedToMesh = mesh;
  61094. var ray = this.ray;
  61095. if (!ray) {
  61096. return;
  61097. }
  61098. if (!ray.direction) {
  61099. ray.direction = BABYLON.Vector3.Zero();
  61100. }
  61101. if (!ray.origin) {
  61102. ray.origin = BABYLON.Vector3.Zero();
  61103. }
  61104. if (length) {
  61105. ray.length = length;
  61106. }
  61107. if (!meshSpaceOrigin) {
  61108. meshSpaceOrigin = BABYLON.Vector3.Zero();
  61109. }
  61110. if (!meshSpaceDirection) {
  61111. // -1 so that this will work with Mesh.lookAt
  61112. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  61113. }
  61114. if (!this._meshSpaceDirection) {
  61115. this._meshSpaceDirection = meshSpaceDirection.clone();
  61116. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  61117. }
  61118. else {
  61119. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  61120. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  61121. }
  61122. if (!this._updateToMeshFunction) {
  61123. this._updateToMeshFunction = this._updateToMesh.bind(this);
  61124. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  61125. }
  61126. this._updateToMesh();
  61127. };
  61128. RayHelper.prototype.detachFromMesh = function () {
  61129. if (this._attachedToMesh) {
  61130. if (this._updateToMeshFunction) {
  61131. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  61132. }
  61133. this._attachedToMesh = null;
  61134. this._updateToMeshFunction = null;
  61135. }
  61136. };
  61137. RayHelper.prototype._updateToMesh = function () {
  61138. var ray = this.ray;
  61139. if (!this._attachedToMesh || !ray) {
  61140. return;
  61141. }
  61142. if (this._attachedToMesh._isDisposed) {
  61143. this.detachFromMesh();
  61144. return;
  61145. }
  61146. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  61147. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  61148. };
  61149. RayHelper.prototype.dispose = function () {
  61150. this.hide();
  61151. this.detachFromMesh();
  61152. this.ray = null;
  61153. };
  61154. return RayHelper;
  61155. }());
  61156. BABYLON.RayHelper = RayHelper;
  61157. })(BABYLON || (BABYLON = {}));
  61158. //# sourceMappingURL=babylon.rayHelper.js.map
  61159. var BABYLON;
  61160. (function (BABYLON) {
  61161. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  61162. get: function () {
  61163. if (!this._debugLayer) {
  61164. this._debugLayer = new DebugLayer(this);
  61165. }
  61166. return this._debugLayer;
  61167. },
  61168. enumerable: true,
  61169. configurable: true
  61170. });
  61171. var DebugLayer = /** @class */ (function () {
  61172. function DebugLayer(scene) {
  61173. var _this = this;
  61174. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  61175. this.onPropertyChangedObservable = new BABYLON.Observable();
  61176. this._scene = scene;
  61177. this._scene.onDisposeObservable.add(function () {
  61178. // Debug layer
  61179. if (_this._scene._debugLayer) {
  61180. _this._scene._debugLayer.hide();
  61181. }
  61182. });
  61183. }
  61184. /** Creates the inspector window. */
  61185. DebugLayer.prototype._createInspector = function (config) {
  61186. if (config === void 0) { config = {}; }
  61187. var popup = config.popup || false;
  61188. var initialTab = config.initialTab || 0;
  61189. var parentElement = config.parentElement || null;
  61190. if (!this._inspector) {
  61191. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  61192. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  61193. } // else nothing to do as instance is already created
  61194. };
  61195. DebugLayer.prototype.isVisible = function () {
  61196. if (!this._inspector) {
  61197. return false;
  61198. }
  61199. return true;
  61200. };
  61201. DebugLayer.prototype.hide = function () {
  61202. if (this._inspector) {
  61203. try {
  61204. this._inspector.dispose();
  61205. }
  61206. catch (e) {
  61207. // If the inspector has been removed directly from the inspector tool
  61208. }
  61209. this.onPropertyChangedObservable.clear();
  61210. this._inspector = null;
  61211. }
  61212. };
  61213. /**
  61214. *
  61215. * Launch the debugLayer.
  61216. *
  61217. * initialTab:
  61218. * | Value | Tab Name |
  61219. * | --- | --- |
  61220. * | 0 | Scene |
  61221. * | 1 | Console |
  61222. * | 2 | Stats |
  61223. * | 3 | Textures |
  61224. * | 4 | Mesh |
  61225. * | 5 | Light |
  61226. * | 6 | Material |
  61227. * | 7 | GLTF |
  61228. * | 8 | GUI |
  61229. * | 9 | Physics |
  61230. * | 10 | Camera |
  61231. * | 11 | Audio |
  61232. *
  61233. */
  61234. DebugLayer.prototype.show = function (config) {
  61235. if (config === void 0) { config = {}; }
  61236. if (typeof this.BJSINSPECTOR == 'undefined') {
  61237. // Load inspector and add it to the DOM
  61238. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  61239. }
  61240. else {
  61241. // Otherwise creates the inspector
  61242. this._createInspector(config);
  61243. }
  61244. };
  61245. /**
  61246. * Gets the active tab
  61247. * @return the index of the active tab or -1 if the inspector is hidden
  61248. */
  61249. DebugLayer.prototype.getActiveTab = function () {
  61250. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  61251. };
  61252. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  61253. return DebugLayer;
  61254. }());
  61255. BABYLON.DebugLayer = DebugLayer;
  61256. })(BABYLON || (BABYLON = {}));
  61257. //# sourceMappingURL=babylon.debugLayer.js.map
  61258. var BABYLON;
  61259. (function (BABYLON) {
  61260. var Debug;
  61261. (function (Debug) {
  61262. /**
  61263. * Used to show the physics impostor around the specific mesh
  61264. */
  61265. var PhysicsViewer = /** @class */ (function () {
  61266. /**
  61267. * Creates a new PhysicsViewer
  61268. * @param scene defines the hosting scene
  61269. */
  61270. function PhysicsViewer(scene) {
  61271. /** @hidden */
  61272. this._impostors = [];
  61273. /** @hidden */
  61274. this._meshes = [];
  61275. /** @hidden */
  61276. this._numMeshes = 0;
  61277. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61278. var physicEngine = this._scene.getPhysicsEngine();
  61279. if (physicEngine) {
  61280. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  61281. }
  61282. }
  61283. /** @hidden */
  61284. PhysicsViewer.prototype._updateDebugMeshes = function () {
  61285. var plugin = this._physicsEnginePlugin;
  61286. for (var i = 0; i < this._numMeshes; i++) {
  61287. var impostor = this._impostors[i];
  61288. if (!impostor) {
  61289. continue;
  61290. }
  61291. if (impostor.isDisposed) {
  61292. this.hideImpostor(this._impostors[i--]);
  61293. }
  61294. else {
  61295. var mesh = this._meshes[i];
  61296. if (mesh && plugin) {
  61297. plugin.syncMeshWithImpostor(mesh, impostor);
  61298. }
  61299. }
  61300. }
  61301. };
  61302. /**
  61303. * Renders a specified physic impostor
  61304. * @param impostor defines the impostor to render
  61305. */
  61306. PhysicsViewer.prototype.showImpostor = function (impostor) {
  61307. if (!this._scene) {
  61308. return;
  61309. }
  61310. for (var i = 0; i < this._numMeshes; i++) {
  61311. if (this._impostors[i] == impostor) {
  61312. return;
  61313. }
  61314. }
  61315. var debugMesh = this._getDebugMesh(impostor, this._scene);
  61316. if (debugMesh) {
  61317. this._impostors[this._numMeshes] = impostor;
  61318. this._meshes[this._numMeshes] = debugMesh;
  61319. if (this._numMeshes === 0) {
  61320. this._renderFunction = this._updateDebugMeshes.bind(this);
  61321. this._scene.registerBeforeRender(this._renderFunction);
  61322. }
  61323. this._numMeshes++;
  61324. }
  61325. };
  61326. /**
  61327. * Hides a specified physic impostor
  61328. * @param impostor defines the impostor to hide
  61329. */
  61330. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  61331. if (!impostor || !this._scene) {
  61332. return;
  61333. }
  61334. var removed = false;
  61335. for (var i = 0; i < this._numMeshes; i++) {
  61336. if (this._impostors[i] == impostor) {
  61337. var mesh = this._meshes[i];
  61338. if (!mesh) {
  61339. continue;
  61340. }
  61341. this._scene.removeMesh(mesh);
  61342. mesh.dispose();
  61343. this._numMeshes--;
  61344. if (this._numMeshes > 0) {
  61345. this._meshes[i] = this._meshes[this._numMeshes];
  61346. this._impostors[i] = this._impostors[this._numMeshes];
  61347. this._meshes[this._numMeshes] = null;
  61348. this._impostors[this._numMeshes] = null;
  61349. }
  61350. else {
  61351. this._meshes[0] = null;
  61352. this._impostors[0] = null;
  61353. }
  61354. removed = true;
  61355. break;
  61356. }
  61357. }
  61358. if (removed && this._numMeshes === 0) {
  61359. this._scene.unregisterBeforeRender(this._renderFunction);
  61360. }
  61361. };
  61362. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  61363. if (!this._debugMaterial) {
  61364. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  61365. this._debugMaterial.wireframe = true;
  61366. }
  61367. return this._debugMaterial;
  61368. };
  61369. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  61370. if (!this._debugBoxMesh) {
  61371. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  61372. this._debugBoxMesh.renderingGroupId = 1;
  61373. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61374. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  61375. scene.removeMesh(this._debugBoxMesh);
  61376. }
  61377. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  61378. };
  61379. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  61380. if (!this._debugSphereMesh) {
  61381. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  61382. this._debugSphereMesh.renderingGroupId = 1;
  61383. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61384. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  61385. scene.removeMesh(this._debugSphereMesh);
  61386. }
  61387. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  61388. };
  61389. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  61390. var mesh = null;
  61391. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  61392. mesh = this._getDebugBoxMesh(scene);
  61393. impostor.getBoxSizeToRef(mesh.scaling);
  61394. }
  61395. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  61396. mesh = this._getDebugSphereMesh(scene);
  61397. var radius = impostor.getRadius();
  61398. mesh.scaling.x = radius * 2;
  61399. mesh.scaling.y = radius * 2;
  61400. mesh.scaling.z = radius * 2;
  61401. }
  61402. return mesh;
  61403. };
  61404. /** Releases all resources */
  61405. PhysicsViewer.prototype.dispose = function () {
  61406. for (var i = 0; i < this._numMeshes; i++) {
  61407. this.hideImpostor(this._impostors[i]);
  61408. }
  61409. if (this._debugBoxMesh) {
  61410. this._debugBoxMesh.dispose();
  61411. }
  61412. if (this._debugSphereMesh) {
  61413. this._debugSphereMesh.dispose();
  61414. }
  61415. if (this._debugMaterial) {
  61416. this._debugMaterial.dispose();
  61417. }
  61418. this._impostors.length = 0;
  61419. this._scene = null;
  61420. this._physicsEnginePlugin = null;
  61421. };
  61422. return PhysicsViewer;
  61423. }());
  61424. Debug.PhysicsViewer = PhysicsViewer;
  61425. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61426. })(BABYLON || (BABYLON = {}));
  61427. //# sourceMappingURL=babylon.physicsViewer.js.map
  61428. var BABYLON;
  61429. (function (BABYLON) {
  61430. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  61431. get: function () {
  61432. return this._forceShowBoundingBoxes || false;
  61433. },
  61434. set: function (value) {
  61435. this._forceShowBoundingBoxes = value;
  61436. // Lazyly creates a BB renderer if needed.
  61437. if (value) {
  61438. this.getBoundingBoxRenderer();
  61439. }
  61440. },
  61441. enumerable: true,
  61442. configurable: true
  61443. });
  61444. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  61445. if (!this._boundingBoxRenderer) {
  61446. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  61447. }
  61448. return this._boundingBoxRenderer;
  61449. };
  61450. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  61451. get: function () {
  61452. return this._showBoundingBox || false;
  61453. },
  61454. set: function (value) {
  61455. this._showBoundingBox = value;
  61456. // Lazyly creates a BB renderer if needed.
  61457. if (value) {
  61458. this.getScene().getBoundingBoxRenderer();
  61459. }
  61460. },
  61461. enumerable: true,
  61462. configurable: true
  61463. });
  61464. var BoundingBoxRenderer = /** @class */ (function () {
  61465. function BoundingBoxRenderer(scene) {
  61466. /**
  61467. * The component name helpfull to identify the component in the list of scene components.
  61468. */
  61469. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  61470. this.frontColor = new BABYLON.Color3(1, 1, 1);
  61471. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  61472. this.showBackLines = true;
  61473. this.renderList = new BABYLON.SmartArray(32);
  61474. this._vertexBuffers = {};
  61475. this.scene = scene;
  61476. scene._addComponent(this);
  61477. }
  61478. /**
  61479. * Registers the component in a given scene
  61480. */
  61481. BoundingBoxRenderer.prototype.register = function () {
  61482. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  61483. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  61484. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  61485. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  61486. };
  61487. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  61488. if (mesh.showSubMeshesBoundingBox) {
  61489. var boundingInfo = subMesh.getBoundingInfo();
  61490. if (boundingInfo !== null && boundingInfo !== undefined) {
  61491. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  61492. this.renderList.push(boundingInfo.boundingBox);
  61493. }
  61494. }
  61495. };
  61496. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  61497. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  61498. var boundingInfo = sourceMesh.getBoundingInfo();
  61499. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  61500. this.renderList.push(boundingInfo.boundingBox);
  61501. }
  61502. };
  61503. BoundingBoxRenderer.prototype._prepareRessources = function () {
  61504. if (this._colorShader) {
  61505. return;
  61506. }
  61507. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  61508. attributes: [BABYLON.VertexBuffer.PositionKind],
  61509. uniforms: ["world", "viewProjection", "color"]
  61510. });
  61511. var engine = this.scene.getEngine();
  61512. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  61513. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61514. this._createIndexBuffer();
  61515. };
  61516. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  61517. var engine = this.scene.getEngine();
  61518. 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]);
  61519. };
  61520. /**
  61521. * Rebuilds the elements related to this component in case of
  61522. * context lost for instance.
  61523. */
  61524. BoundingBoxRenderer.prototype.rebuild = function () {
  61525. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61526. if (vb) {
  61527. vb._rebuild();
  61528. }
  61529. this._createIndexBuffer();
  61530. };
  61531. BoundingBoxRenderer.prototype.reset = function () {
  61532. this.renderList.reset();
  61533. };
  61534. /**
  61535. * Render the bounding boxes of a specific rendering group
  61536. * @param renderingGroupId defines the rendering group to render
  61537. */
  61538. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  61539. if (this.renderList.length === 0) {
  61540. return;
  61541. }
  61542. this._prepareRessources();
  61543. if (!this._colorShader.isReady()) {
  61544. return;
  61545. }
  61546. var engine = this.scene.getEngine();
  61547. engine.setDepthWrite(false);
  61548. this._colorShader._preBind();
  61549. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61550. var boundingBox = this.renderList.data[boundingBoxIndex];
  61551. if (boundingBox._tag !== renderingGroupId) {
  61552. continue;
  61553. }
  61554. var min = boundingBox.minimum;
  61555. var max = boundingBox.maximum;
  61556. var diff = max.subtract(min);
  61557. var median = min.add(diff.scale(0.5));
  61558. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61559. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61560. .multiply(boundingBox.getWorldMatrix());
  61561. // VBOs
  61562. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61563. if (this.showBackLines) {
  61564. // Back
  61565. engine.setDepthFunctionToGreaterOrEqual();
  61566. this.scene.resetCachedMaterial();
  61567. this._colorShader.setColor4("color", this.backColor.toColor4());
  61568. this._colorShader.bind(worldMatrix);
  61569. // Draw order
  61570. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61571. }
  61572. // Front
  61573. engine.setDepthFunctionToLess();
  61574. this.scene.resetCachedMaterial();
  61575. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61576. this._colorShader.bind(worldMatrix);
  61577. // Draw order
  61578. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61579. }
  61580. this._colorShader.unbind();
  61581. engine.setDepthFunctionToLessOrEqual();
  61582. engine.setDepthWrite(true);
  61583. };
  61584. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  61585. this._prepareRessources();
  61586. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  61587. return;
  61588. }
  61589. var engine = this.scene.getEngine();
  61590. engine.setDepthWrite(false);
  61591. engine.setColorWrite(false);
  61592. this._colorShader._preBind();
  61593. var boundingBox = mesh._boundingInfo.boundingBox;
  61594. var min = boundingBox.minimum;
  61595. var max = boundingBox.maximum;
  61596. var diff = max.subtract(min);
  61597. var median = min.add(diff.scale(0.5));
  61598. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61599. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61600. .multiply(boundingBox.getWorldMatrix());
  61601. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61602. engine.setDepthFunctionToLess();
  61603. this.scene.resetCachedMaterial();
  61604. this._colorShader.bind(worldMatrix);
  61605. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61606. this._colorShader.unbind();
  61607. engine.setDepthFunctionToLessOrEqual();
  61608. engine.setDepthWrite(true);
  61609. engine.setColorWrite(true);
  61610. };
  61611. BoundingBoxRenderer.prototype.dispose = function () {
  61612. if (!this._colorShader) {
  61613. return;
  61614. }
  61615. this.renderList.dispose();
  61616. this._colorShader.dispose();
  61617. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61618. if (buffer) {
  61619. buffer.dispose();
  61620. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61621. }
  61622. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  61623. };
  61624. return BoundingBoxRenderer;
  61625. }());
  61626. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61627. })(BABYLON || (BABYLON = {}));
  61628. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61629. var BABYLON;
  61630. (function (BABYLON) {
  61631. BABYLON.Engine.prototype.createTransformFeedback = function () {
  61632. return this._gl.createTransformFeedback();
  61633. };
  61634. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  61635. this._gl.deleteTransformFeedback(value);
  61636. };
  61637. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  61638. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  61639. };
  61640. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  61641. if (usePoints === void 0) { usePoints = true; }
  61642. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  61643. };
  61644. BABYLON.Engine.prototype.endTransformFeedback = function () {
  61645. this._gl.endTransformFeedback();
  61646. };
  61647. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  61648. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  61649. };
  61650. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  61651. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  61652. };
  61653. })(BABYLON || (BABYLON = {}));
  61654. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  61655. var BABYLON;
  61656. (function (BABYLON) {
  61657. /**
  61658. * This represents a GPU particle system in Babylon
  61659. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  61660. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  61661. */
  61662. var GPUParticleSystem = /** @class */ (function (_super) {
  61663. __extends(GPUParticleSystem, _super);
  61664. /**
  61665. * Instantiates a GPU particle system.
  61666. * 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.
  61667. * @param name The name of the particle system
  61668. * @param options The options used to create the system
  61669. * @param scene The scene the particle system belongs to
  61670. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  61671. */
  61672. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  61673. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61674. var _this = _super.call(this, name) || this;
  61675. /**
  61676. * The layer mask we are rendering the particles through.
  61677. */
  61678. _this.layerMask = 0x0FFFFFFF;
  61679. _this._accumulatedCount = 0;
  61680. _this._targetIndex = 0;
  61681. _this._currentRenderId = -1;
  61682. _this._started = false;
  61683. _this._stopped = false;
  61684. _this._timeDelta = 0;
  61685. _this._attributesStrideSize = 21;
  61686. _this._actualFrame = 0;
  61687. _this._rawTextureWidth = 256;
  61688. /**
  61689. * An event triggered when the system is disposed.
  61690. */
  61691. _this.onDisposeObservable = new BABYLON.Observable();
  61692. /**
  61693. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  61694. * to override the particles.
  61695. */
  61696. _this.forceDepthWrite = false;
  61697. _this._preWarmDone = false;
  61698. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61699. // Setup the default processing configuration to the scene.
  61700. _this._attachImageProcessingConfiguration(null);
  61701. _this._engine = _this._scene.getEngine();
  61702. if (!options.randomTextureSize) {
  61703. delete options.randomTextureSize;
  61704. }
  61705. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  61706. var optionsAsNumber = options;
  61707. if (isFinite(optionsAsNumber)) {
  61708. fullOptions.capacity = optionsAsNumber;
  61709. }
  61710. _this._capacity = fullOptions.capacity;
  61711. _this._activeCount = fullOptions.capacity;
  61712. _this._currentActiveCount = 0;
  61713. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  61714. _this._scene.particleSystems.push(_this);
  61715. _this._updateEffectOptions = {
  61716. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  61717. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  61718. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  61719. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  61720. uniformBuffersNames: [],
  61721. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  61722. defines: "",
  61723. fallbacks: null,
  61724. onCompiled: null,
  61725. onError: null,
  61726. indexParameters: null,
  61727. maxSimultaneousLights: 0,
  61728. transformFeedbackVaryings: []
  61729. };
  61730. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  61731. // Random data
  61732. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  61733. var d = [];
  61734. for (var i = 0; i < maxTextureSize; ++i) {
  61735. d.push(Math.random());
  61736. d.push(Math.random());
  61737. d.push(Math.random());
  61738. d.push(Math.random());
  61739. }
  61740. _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);
  61741. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61742. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61743. d = [];
  61744. for (var i = 0; i < maxTextureSize; ++i) {
  61745. d.push(Math.random());
  61746. d.push(Math.random());
  61747. d.push(Math.random());
  61748. d.push(Math.random());
  61749. }
  61750. _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);
  61751. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61752. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61753. _this._randomTextureSize = maxTextureSize;
  61754. return _this;
  61755. }
  61756. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  61757. /**
  61758. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  61759. */
  61760. get: function () {
  61761. if (!BABYLON.Engine.LastCreatedEngine) {
  61762. return false;
  61763. }
  61764. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  61765. },
  61766. enumerable: true,
  61767. configurable: true
  61768. });
  61769. /**
  61770. * Gets the maximum number of particles active at the same time.
  61771. * @returns The max number of active particles.
  61772. */
  61773. GPUParticleSystem.prototype.getCapacity = function () {
  61774. return this._capacity;
  61775. };
  61776. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  61777. /**
  61778. * Gets or set the number of active particles
  61779. */
  61780. get: function () {
  61781. return this._activeCount;
  61782. },
  61783. set: function (value) {
  61784. this._activeCount = Math.min(value, this._capacity);
  61785. },
  61786. enumerable: true,
  61787. configurable: true
  61788. });
  61789. /**
  61790. * Is this system ready to be used/rendered
  61791. * @return true if the system is ready
  61792. */
  61793. GPUParticleSystem.prototype.isReady = function () {
  61794. if (!this._updateEffect) {
  61795. this._recreateUpdateEffect();
  61796. this._recreateRenderEffect();
  61797. return false;
  61798. }
  61799. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61800. return false;
  61801. }
  61802. return true;
  61803. };
  61804. /**
  61805. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61806. * @returns True if it has been started, otherwise false.
  61807. */
  61808. GPUParticleSystem.prototype.isStarted = function () {
  61809. return this._started;
  61810. };
  61811. /**
  61812. * Starts the particle system and begins to emit
  61813. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  61814. */
  61815. GPUParticleSystem.prototype.start = function (delay) {
  61816. var _this = this;
  61817. if (delay === void 0) { delay = this.startDelay; }
  61818. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  61819. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  61820. }
  61821. if (delay) {
  61822. setTimeout(function () {
  61823. _this.start(0);
  61824. }, delay);
  61825. return;
  61826. }
  61827. this._started = true;
  61828. this._stopped = false;
  61829. this._preWarmDone = false;
  61830. };
  61831. /**
  61832. * Stops the particle system.
  61833. */
  61834. GPUParticleSystem.prototype.stop = function () {
  61835. this._stopped = true;
  61836. };
  61837. /**
  61838. * Remove all active particles
  61839. */
  61840. GPUParticleSystem.prototype.reset = function () {
  61841. this._releaseBuffers();
  61842. this._releaseVAOs();
  61843. this._currentActiveCount = 0;
  61844. this._targetIndex = 0;
  61845. };
  61846. /**
  61847. * Returns the string "GPUParticleSystem"
  61848. * @returns a string containing the class name
  61849. */
  61850. GPUParticleSystem.prototype.getClassName = function () {
  61851. return "GPUParticleSystem";
  61852. };
  61853. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  61854. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  61855. this._releaseBuffers();
  61856. return this;
  61857. };
  61858. /**
  61859. * Adds a new color gradient
  61860. * @param gradient defines the gradient to use (between 0 and 1)
  61861. * @param color defines the color to affect to the specified gradient
  61862. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61863. * @returns the current particle system
  61864. */
  61865. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61866. if (!this._colorGradients) {
  61867. this._colorGradients = [];
  61868. }
  61869. var colorGradient = new BABYLON.ColorGradient();
  61870. colorGradient.gradient = gradient;
  61871. colorGradient.color1 = color1;
  61872. this._colorGradients.push(colorGradient);
  61873. this._colorGradients.sort(function (a, b) {
  61874. if (a.gradient < b.gradient) {
  61875. return -1;
  61876. }
  61877. else if (a.gradient > b.gradient) {
  61878. return 1;
  61879. }
  61880. return 0;
  61881. });
  61882. if (this._colorGradientsTexture) {
  61883. this._colorGradientsTexture.dispose();
  61884. this._colorGradientsTexture = null;
  61885. }
  61886. this._releaseBuffers();
  61887. return this;
  61888. };
  61889. /**
  61890. * Remove a specific color gradient
  61891. * @param gradient defines the gradient to remove
  61892. * @returns the current particle system
  61893. */
  61894. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61895. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  61896. this._colorGradientsTexture = null;
  61897. return this;
  61898. };
  61899. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61900. var valueGradient = new BABYLON.FactorGradient();
  61901. valueGradient.gradient = gradient;
  61902. valueGradient.factor1 = factor;
  61903. factorGradients.push(valueGradient);
  61904. factorGradients.sort(function (a, b) {
  61905. if (a.gradient < b.gradient) {
  61906. return -1;
  61907. }
  61908. else if (a.gradient > b.gradient) {
  61909. return 1;
  61910. }
  61911. return 0;
  61912. });
  61913. this._releaseBuffers();
  61914. };
  61915. /**
  61916. * Adds a new size gradient
  61917. * @param gradient defines the gradient to use (between 0 and 1)
  61918. * @param factor defines the size factor to affect to the specified gradient
  61919. * @returns the current particle system
  61920. */
  61921. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61922. if (!this._sizeGradients) {
  61923. this._sizeGradients = [];
  61924. }
  61925. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61926. if (this._sizeGradientsTexture) {
  61927. this._sizeGradientsTexture.dispose();
  61928. this._sizeGradientsTexture = null;
  61929. }
  61930. this._releaseBuffers();
  61931. return this;
  61932. };
  61933. /**
  61934. * Remove a specific size gradient
  61935. * @param gradient defines the gradient to remove
  61936. * @returns the current particle system
  61937. */
  61938. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61939. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61940. this._sizeGradientsTexture = null;
  61941. return this;
  61942. };
  61943. /**
  61944. * Adds a new angular speed gradient
  61945. * @param gradient defines the gradient to use (between 0 and 1)
  61946. * @param factor defines the angular speed to affect to the specified gradient
  61947. * @returns the current particle system
  61948. */
  61949. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61950. if (!this._angularSpeedGradients) {
  61951. this._angularSpeedGradients = [];
  61952. }
  61953. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61954. if (this._angularSpeedGradientsTexture) {
  61955. this._angularSpeedGradientsTexture.dispose();
  61956. this._angularSpeedGradientsTexture = null;
  61957. }
  61958. this._releaseBuffers();
  61959. return this;
  61960. };
  61961. /**
  61962. * Remove a specific angular speed gradient
  61963. * @param gradient defines the gradient to remove
  61964. * @returns the current particle system
  61965. */
  61966. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61967. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61968. this._angularSpeedGradientsTexture = null;
  61969. return this;
  61970. };
  61971. /**
  61972. * Adds a new velocity gradient
  61973. * @param gradient defines the gradient to use (between 0 and 1)
  61974. * @param factor defines the velocity to affect to the specified gradient
  61975. * @returns the current particle system
  61976. */
  61977. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61978. if (!this._velocityGradients) {
  61979. this._velocityGradients = [];
  61980. }
  61981. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61982. if (this._velocityGradientsTexture) {
  61983. this._velocityGradientsTexture.dispose();
  61984. this._velocityGradientsTexture = null;
  61985. }
  61986. this._releaseBuffers();
  61987. return this;
  61988. };
  61989. /**
  61990. * Remove a specific velocity gradient
  61991. * @param gradient defines the gradient to remove
  61992. * @returns the current particle system
  61993. */
  61994. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61995. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61996. this._velocityGradientsTexture = null;
  61997. return this;
  61998. };
  61999. /**
  62000. * Adds a new limit velocity gradient
  62001. * @param gradient defines the gradient to use (between 0 and 1)
  62002. * @param factor defines the limit velocity value to affect to the specified gradient
  62003. * @returns the current particle system
  62004. */
  62005. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  62006. if (!this._limitVelocityGradients) {
  62007. this._limitVelocityGradients = [];
  62008. }
  62009. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  62010. if (this._limitVelocityGradientsTexture) {
  62011. this._limitVelocityGradientsTexture.dispose();
  62012. this._limitVelocityGradientsTexture = null;
  62013. }
  62014. this._releaseBuffers();
  62015. return this;
  62016. };
  62017. /**
  62018. * Remove a specific limit velocity gradient
  62019. * @param gradient defines the gradient to remove
  62020. * @returns the current particle system
  62021. */
  62022. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  62023. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  62024. this._limitVelocityGradientsTexture = null;
  62025. return this;
  62026. };
  62027. /**
  62028. * Adds a new drag gradient
  62029. * @param gradient defines the gradient to use (between 0 and 1)
  62030. * @param factor defines the drag value to affect to the specified gradient
  62031. * @returns the current particle system
  62032. */
  62033. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  62034. if (!this._dragGradients) {
  62035. this._dragGradients = [];
  62036. }
  62037. this._addFactorGradient(this._dragGradients, gradient, factor);
  62038. if (this._dragGradientsTexture) {
  62039. this._dragGradientsTexture.dispose();
  62040. this._dragGradientsTexture = null;
  62041. }
  62042. this._releaseBuffers();
  62043. return this;
  62044. };
  62045. /**
  62046. * Remove a specific drag gradient
  62047. * @param gradient defines the gradient to remove
  62048. * @returns the current particle system
  62049. */
  62050. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  62051. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  62052. this._dragGradientsTexture = null;
  62053. return this;
  62054. };
  62055. /**
  62056. * Not supported by GPUParticleSystem
  62057. * @param gradient defines the gradient to use (between 0 and 1)
  62058. * @param factor defines the emit rate value to affect to the specified gradient
  62059. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  62060. * @returns the current particle system
  62061. */
  62062. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  62063. // Do nothing as emit rate is not supported by GPUParticleSystem
  62064. return this;
  62065. };
  62066. /**
  62067. * Not supported by GPUParticleSystem
  62068. * @param gradient defines the gradient to remove
  62069. * @returns the current particle system
  62070. */
  62071. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  62072. // Do nothing as emit rate is not supported by GPUParticleSystem
  62073. return this;
  62074. };
  62075. /**
  62076. * Not supported by GPUParticleSystem
  62077. * @param gradient defines the gradient to use (between 0 and 1)
  62078. * @param factor defines the start size value to affect to the specified gradient
  62079. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  62080. * @returns the current particle system
  62081. */
  62082. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  62083. // Do nothing as start size is not supported by GPUParticleSystem
  62084. return this;
  62085. };
  62086. /**
  62087. * Not supported by GPUParticleSystem
  62088. * @param gradient defines the gradient to remove
  62089. * @returns the current particle system
  62090. */
  62091. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  62092. // Do nothing as start size is not supported by GPUParticleSystem
  62093. return this;
  62094. };
  62095. /**
  62096. * Not supported by GPUParticleSystem
  62097. * @param gradient defines the gradient to use (between 0 and 1)
  62098. * @param min defines the color remap minimal range
  62099. * @param max defines the color remap maximal range
  62100. * @returns the current particle system
  62101. */
  62102. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  62103. // Do nothing as start size is not supported by GPUParticleSystem
  62104. return this;
  62105. };
  62106. /**
  62107. * Not supported by GPUParticleSystem
  62108. * @param gradient defines the gradient to remove
  62109. * @returns the current particle system
  62110. */
  62111. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  62112. // Do nothing as start size is not supported by GPUParticleSystem
  62113. return this;
  62114. };
  62115. /**
  62116. * Not supported by GPUParticleSystem
  62117. * @param gradient defines the gradient to use (between 0 and 1)
  62118. * @param min defines the alpha remap minimal range
  62119. * @param max defines the alpha remap maximal range
  62120. * @returns the current particle system
  62121. */
  62122. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  62123. // Do nothing as start size is not supported by GPUParticleSystem
  62124. return this;
  62125. };
  62126. /**
  62127. * Not supported by GPUParticleSystem
  62128. * @param gradient defines the gradient to remove
  62129. * @returns the current particle system
  62130. */
  62131. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  62132. // Do nothing as start size is not supported by GPUParticleSystem
  62133. return this;
  62134. };
  62135. /**
  62136. * Not supported by GPUParticleSystem
  62137. * @param gradient defines the gradient to use (between 0 and 1)
  62138. * @param color defines the color to affect to the specified gradient
  62139. * @returns the current particle system
  62140. */
  62141. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  62142. //Not supported by GPUParticleSystem
  62143. return this;
  62144. };
  62145. /**
  62146. * Not supported by GPUParticleSystem
  62147. * @param gradient defines the gradient to remove
  62148. * @returns the current particle system
  62149. */
  62150. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  62151. //Not supported by GPUParticleSystem
  62152. return this;
  62153. };
  62154. /**
  62155. * Not supported by GPUParticleSystem
  62156. * @returns the list of ramp gradients
  62157. */
  62158. GPUParticleSystem.prototype.getRampGradients = function () {
  62159. return null;
  62160. };
  62161. GPUParticleSystem.prototype._reset = function () {
  62162. this._releaseBuffers();
  62163. };
  62164. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  62165. var updateVertexBuffers = {};
  62166. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  62167. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  62168. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  62169. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  62170. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  62171. var offset = 12;
  62172. if (!this._colorGradientsTexture) {
  62173. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  62174. offset += 4;
  62175. }
  62176. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  62177. offset += 3;
  62178. if (!this._isBillboardBased) {
  62179. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  62180. offset += 3;
  62181. }
  62182. if (this._angularSpeedGradientsTexture) {
  62183. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  62184. offset += 1;
  62185. }
  62186. else {
  62187. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  62188. offset += 2;
  62189. }
  62190. if (this._isAnimationSheetEnabled) {
  62191. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  62192. offset += 1;
  62193. if (this.spriteRandomStartCell) {
  62194. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  62195. offset += 1;
  62196. }
  62197. }
  62198. if (this.noiseTexture) {
  62199. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  62200. offset += 3;
  62201. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  62202. offset += 3;
  62203. }
  62204. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  62205. this._engine.bindArrayBuffer(null);
  62206. return vao;
  62207. };
  62208. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  62209. var renderVertexBuffers = {};
  62210. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  62211. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  62212. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  62213. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  62214. var offset = 12;
  62215. if (!this._colorGradientsTexture) {
  62216. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  62217. offset += 4;
  62218. }
  62219. offset += 3; // Direction
  62220. if (!this._isBillboardBased) {
  62221. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  62222. offset += 3;
  62223. }
  62224. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  62225. if (this._angularSpeedGradientsTexture) {
  62226. offset++;
  62227. }
  62228. else {
  62229. offset += 2;
  62230. }
  62231. if (this._isAnimationSheetEnabled) {
  62232. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  62233. offset += 1;
  62234. if (this.spriteRandomStartCell) {
  62235. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  62236. offset += 1;
  62237. }
  62238. }
  62239. if (this.noiseTexture) {
  62240. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  62241. offset += 3;
  62242. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  62243. offset += 3;
  62244. }
  62245. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  62246. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  62247. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  62248. this._engine.bindArrayBuffer(null);
  62249. return vao;
  62250. };
  62251. GPUParticleSystem.prototype._initialize = function (force) {
  62252. if (force === void 0) { force = false; }
  62253. if (this._buffer0 && !force) {
  62254. return;
  62255. }
  62256. var engine = this._scene.getEngine();
  62257. var data = new Array();
  62258. if (!this.isBillboardBased) {
  62259. this._attributesStrideSize += 3;
  62260. }
  62261. if (this._colorGradientsTexture) {
  62262. this._attributesStrideSize -= 4;
  62263. }
  62264. if (this._angularSpeedGradientsTexture) {
  62265. this._attributesStrideSize -= 1;
  62266. }
  62267. if (this._isAnimationSheetEnabled) {
  62268. this._attributesStrideSize += 1;
  62269. if (this.spriteRandomStartCell) {
  62270. this._attributesStrideSize += 1;
  62271. }
  62272. }
  62273. if (this.noiseTexture) {
  62274. this._attributesStrideSize += 6;
  62275. }
  62276. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  62277. // position
  62278. data.push(0.0);
  62279. data.push(0.0);
  62280. data.push(0.0);
  62281. // Age and life
  62282. data.push(0.0); // create the particle as a dead one to create a new one at start
  62283. data.push(0.0);
  62284. // Seed
  62285. data.push(Math.random());
  62286. data.push(Math.random());
  62287. data.push(Math.random());
  62288. data.push(Math.random());
  62289. // Size
  62290. data.push(0.0);
  62291. data.push(0.0);
  62292. data.push(0.0);
  62293. if (!this._colorGradientsTexture) {
  62294. // color
  62295. data.push(0.0);
  62296. data.push(0.0);
  62297. data.push(0.0);
  62298. data.push(0.0);
  62299. }
  62300. // direction
  62301. data.push(0.0);
  62302. data.push(0.0);
  62303. data.push(0.0);
  62304. if (!this.isBillboardBased) {
  62305. // initialDirection
  62306. data.push(0.0);
  62307. data.push(0.0);
  62308. data.push(0.0);
  62309. }
  62310. // angle
  62311. data.push(0.0);
  62312. if (!this._angularSpeedGradientsTexture) {
  62313. data.push(0.0);
  62314. }
  62315. if (this._isAnimationSheetEnabled) {
  62316. data.push(0.0);
  62317. if (this.spriteRandomStartCell) {
  62318. data.push(0.0);
  62319. }
  62320. }
  62321. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  62322. data.push(Math.random());
  62323. data.push(Math.random());
  62324. data.push(Math.random());
  62325. data.push(Math.random());
  62326. data.push(Math.random());
  62327. data.push(Math.random());
  62328. }
  62329. }
  62330. // Sprite data
  62331. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  62332. -0.5, 0.5, 0, 1,
  62333. -0.5, -0.5, 0, 0,
  62334. 0.5, -0.5, 1, 0]);
  62335. // Buffers
  62336. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62337. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62338. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  62339. // Update VAO
  62340. this._updateVAO = [];
  62341. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  62342. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  62343. // Render VAO
  62344. this._renderVAO = [];
  62345. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  62346. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  62347. // Links
  62348. this._sourceBuffer = this._buffer0;
  62349. this._targetBuffer = this._buffer1;
  62350. };
  62351. /** @hidden */
  62352. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  62353. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  62354. if (this._isBillboardBased) {
  62355. defines += "\n#define BILLBOARD";
  62356. }
  62357. if (this._colorGradientsTexture) {
  62358. defines += "\n#define COLORGRADIENTS";
  62359. }
  62360. if (this._sizeGradientsTexture) {
  62361. defines += "\n#define SIZEGRADIENTS";
  62362. }
  62363. if (this._angularSpeedGradientsTexture) {
  62364. defines += "\n#define ANGULARSPEEDGRADIENTS";
  62365. }
  62366. if (this._velocityGradientsTexture) {
  62367. defines += "\n#define VELOCITYGRADIENTS";
  62368. }
  62369. if (this._limitVelocityGradientsTexture) {
  62370. defines += "\n#define LIMITVELOCITYGRADIENTS";
  62371. }
  62372. if (this._dragGradientsTexture) {
  62373. defines += "\n#define DRAGGRADIENTS";
  62374. }
  62375. if (this.isAnimationSheetEnabled) {
  62376. defines += "\n#define ANIMATESHEET";
  62377. if (this.spriteRandomStartCell) {
  62378. defines += "\n#define ANIMATESHEETRANDOMSTART";
  62379. }
  62380. }
  62381. if (this.noiseTexture) {
  62382. defines += "\n#define NOISE";
  62383. }
  62384. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  62385. return;
  62386. }
  62387. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  62388. if (!this._colorGradientsTexture) {
  62389. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  62390. }
  62391. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  62392. if (!this._isBillboardBased) {
  62393. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  62394. }
  62395. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  62396. if (this.isAnimationSheetEnabled) {
  62397. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  62398. if (this.spriteRandomStartCell) {
  62399. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  62400. }
  62401. }
  62402. if (this.noiseTexture) {
  62403. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  62404. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  62405. }
  62406. this._updateEffectOptions.defines = defines;
  62407. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  62408. };
  62409. /** @hidden */
  62410. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  62411. var defines = "";
  62412. if (this._scene.clipPlane) {
  62413. defines = "\n#define CLIPPLANE";
  62414. }
  62415. if (this._scene.clipPlane2) {
  62416. defines = "\n#define CLIPPLANE2";
  62417. }
  62418. if (this._scene.clipPlane3) {
  62419. defines = "\n#define CLIPPLANE3";
  62420. }
  62421. if (this._scene.clipPlane4) {
  62422. defines = "\n#define CLIPPLANE4";
  62423. }
  62424. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  62425. defines = "\n#define BLENDMULTIPLYMODE";
  62426. }
  62427. if (this._isBillboardBased) {
  62428. defines += "\n#define BILLBOARD";
  62429. switch (this.billboardMode) {
  62430. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  62431. defines += "\n#define BILLBOARDY";
  62432. break;
  62433. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  62434. default:
  62435. break;
  62436. }
  62437. }
  62438. if (this._colorGradientsTexture) {
  62439. defines += "\n#define COLORGRADIENTS";
  62440. }
  62441. if (this.isAnimationSheetEnabled) {
  62442. defines += "\n#define ANIMATESHEET";
  62443. }
  62444. if (this._imageProcessingConfiguration) {
  62445. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  62446. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  62447. }
  62448. if (this._renderEffect && this._renderEffect.defines === defines) {
  62449. return;
  62450. }
  62451. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  62452. var samplers = ["textureSampler", "colorGradientSampler"];
  62453. if (BABYLON.ImageProcessingConfiguration) {
  62454. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  62455. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  62456. }
  62457. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  62458. };
  62459. /**
  62460. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  62461. * @param preWarm defines if we are in the pre-warmimg phase
  62462. */
  62463. GPUParticleSystem.prototype.animate = function (preWarm) {
  62464. if (preWarm === void 0) { preWarm = false; }
  62465. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  62466. this._actualFrame += this._timeDelta;
  62467. if (!this._stopped) {
  62468. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  62469. this.stop();
  62470. }
  62471. }
  62472. };
  62473. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  62474. var texture = this[textureName];
  62475. if (!factorGradients || !factorGradients.length || texture) {
  62476. return;
  62477. }
  62478. var data = new Float32Array(this._rawTextureWidth);
  62479. for (var x = 0; x < this._rawTextureWidth; x++) {
  62480. var ratio = x / this._rawTextureWidth;
  62481. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  62482. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  62483. });
  62484. }
  62485. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62486. };
  62487. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  62488. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  62489. };
  62490. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  62491. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  62492. };
  62493. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  62494. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  62495. };
  62496. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  62497. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  62498. };
  62499. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  62500. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  62501. };
  62502. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  62503. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  62504. return;
  62505. }
  62506. var data = new Uint8Array(this._rawTextureWidth * 4);
  62507. var tmpColor = BABYLON.Tmp.Color4[0];
  62508. for (var x = 0; x < this._rawTextureWidth; x++) {
  62509. var ratio = x / this._rawTextureWidth;
  62510. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  62511. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  62512. data[x * 4] = tmpColor.r * 255;
  62513. data[x * 4 + 1] = tmpColor.g * 255;
  62514. data[x * 4 + 2] = tmpColor.b * 255;
  62515. data[x * 4 + 3] = tmpColor.a * 255;
  62516. });
  62517. }
  62518. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62519. };
  62520. /**
  62521. * Renders the particle system in its current state
  62522. * @param preWarm defines if the system should only update the particles but not render them
  62523. * @returns the current number of particles
  62524. */
  62525. GPUParticleSystem.prototype.render = function (preWarm) {
  62526. if (preWarm === void 0) { preWarm = false; }
  62527. if (!this._started) {
  62528. return 0;
  62529. }
  62530. this._createColorGradientTexture();
  62531. this._createSizeGradientTexture();
  62532. this._createAngularSpeedGradientTexture();
  62533. this._createVelocityGradientTexture();
  62534. this._createLimitVelocityGradientTexture();
  62535. this._createDragGradientTexture();
  62536. this._recreateUpdateEffect();
  62537. this._recreateRenderEffect();
  62538. if (!this.isReady()) {
  62539. return 0;
  62540. }
  62541. if (!preWarm) {
  62542. if (!this._preWarmDone && this.preWarmCycles) {
  62543. for (var index = 0; index < this.preWarmCycles; index++) {
  62544. this.animate(true);
  62545. this.render(true);
  62546. }
  62547. this._preWarmDone = true;
  62548. }
  62549. if (this._currentRenderId === this._scene.getRenderId()) {
  62550. return 0;
  62551. }
  62552. this._currentRenderId = this._scene.getRenderId();
  62553. }
  62554. // Get everything ready to render
  62555. this._initialize();
  62556. this._accumulatedCount += this.emitRate * this._timeDelta;
  62557. if (this._accumulatedCount > 1) {
  62558. var intPart = this._accumulatedCount | 0;
  62559. this._accumulatedCount -= intPart;
  62560. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  62561. }
  62562. if (!this._currentActiveCount) {
  62563. return 0;
  62564. }
  62565. // Enable update effect
  62566. this._engine.enableEffect(this._updateEffect);
  62567. this._engine.setState(false);
  62568. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  62569. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  62570. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  62571. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  62572. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  62573. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  62574. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  62575. if (!this._colorGradientsTexture) {
  62576. this._updateEffect.setDirectColor4("color1", this.color1);
  62577. this._updateEffect.setDirectColor4("color2", this.color2);
  62578. }
  62579. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  62580. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  62581. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  62582. this._updateEffect.setVector3("gravity", this.gravity);
  62583. if (this._sizeGradientsTexture) {
  62584. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  62585. }
  62586. if (this._angularSpeedGradientsTexture) {
  62587. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  62588. }
  62589. if (this._velocityGradientsTexture) {
  62590. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  62591. }
  62592. if (this._limitVelocityGradientsTexture) {
  62593. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  62594. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  62595. }
  62596. if (this._dragGradientsTexture) {
  62597. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  62598. }
  62599. if (this.particleEmitterType) {
  62600. this.particleEmitterType.applyToShader(this._updateEffect);
  62601. }
  62602. if (this._isAnimationSheetEnabled) {
  62603. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  62604. }
  62605. if (this.noiseTexture) {
  62606. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  62607. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  62608. }
  62609. var emitterWM;
  62610. if (this.emitter.position) {
  62611. var emitterMesh = this.emitter;
  62612. emitterWM = emitterMesh.getWorldMatrix();
  62613. }
  62614. else {
  62615. var emitterPosition = this.emitter;
  62616. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  62617. }
  62618. this._updateEffect.setMatrix("emitterWM", emitterWM);
  62619. // Bind source VAO
  62620. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  62621. // Update
  62622. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  62623. this._engine.setRasterizerState(false);
  62624. this._engine.beginTransformFeedback(true);
  62625. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  62626. this._engine.endTransformFeedback();
  62627. this._engine.setRasterizerState(true);
  62628. this._engine.bindTransformFeedbackBuffer(null);
  62629. if (!preWarm) {
  62630. // Enable render effect
  62631. this._engine.enableEffect(this._renderEffect);
  62632. var viewMatrix = this._scene.getViewMatrix();
  62633. this._renderEffect.setMatrix("view", viewMatrix);
  62634. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  62635. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  62636. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  62637. if (this._colorGradientsTexture) {
  62638. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  62639. }
  62640. else {
  62641. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  62642. }
  62643. if (this._isAnimationSheetEnabled && this.particleTexture) {
  62644. var baseSize = this.particleTexture.getBaseSize();
  62645. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  62646. }
  62647. if (this._isBillboardBased) {
  62648. var camera = this._scene.activeCamera;
  62649. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  62650. }
  62651. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  62652. var invView = viewMatrix.clone();
  62653. invView.invert();
  62654. this._renderEffect.setMatrix("invView", invView);
  62655. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  62656. }
  62657. // image processing
  62658. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  62659. this._imageProcessingConfiguration.bind(this._renderEffect);
  62660. }
  62661. // Draw order
  62662. switch (this.blendMode) {
  62663. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  62664. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  62665. break;
  62666. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  62667. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  62668. break;
  62669. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  62670. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62671. break;
  62672. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  62673. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  62674. break;
  62675. }
  62676. if (this.forceDepthWrite) {
  62677. this._engine.setDepthWrite(true);
  62678. }
  62679. // Bind source VAO
  62680. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  62681. // Render
  62682. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  62683. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62684. }
  62685. // Switch VAOs
  62686. this._targetIndex++;
  62687. if (this._targetIndex === 2) {
  62688. this._targetIndex = 0;
  62689. }
  62690. // Switch buffers
  62691. var tmpBuffer = this._sourceBuffer;
  62692. this._sourceBuffer = this._targetBuffer;
  62693. this._targetBuffer = tmpBuffer;
  62694. return this._currentActiveCount;
  62695. };
  62696. /**
  62697. * Rebuilds the particle system
  62698. */
  62699. GPUParticleSystem.prototype.rebuild = function () {
  62700. this._initialize(true);
  62701. };
  62702. GPUParticleSystem.prototype._releaseBuffers = function () {
  62703. if (this._buffer0) {
  62704. this._buffer0.dispose();
  62705. this._buffer0 = null;
  62706. }
  62707. if (this._buffer1) {
  62708. this._buffer1.dispose();
  62709. this._buffer1 = null;
  62710. }
  62711. if (this._spriteBuffer) {
  62712. this._spriteBuffer.dispose();
  62713. this._spriteBuffer = null;
  62714. }
  62715. };
  62716. GPUParticleSystem.prototype._releaseVAOs = function () {
  62717. if (!this._updateVAO) {
  62718. return;
  62719. }
  62720. for (var index = 0; index < this._updateVAO.length; index++) {
  62721. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  62722. }
  62723. this._updateVAO = [];
  62724. for (var index = 0; index < this._renderVAO.length; index++) {
  62725. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  62726. }
  62727. this._renderVAO = [];
  62728. };
  62729. /**
  62730. * Disposes the particle system and free the associated resources
  62731. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  62732. */
  62733. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  62734. if (disposeTexture === void 0) { disposeTexture = true; }
  62735. var index = this._scene.particleSystems.indexOf(this);
  62736. if (index > -1) {
  62737. this._scene.particleSystems.splice(index, 1);
  62738. }
  62739. this._releaseBuffers();
  62740. this._releaseVAOs();
  62741. if (this._colorGradientsTexture) {
  62742. this._colorGradientsTexture.dispose();
  62743. this._colorGradientsTexture = null;
  62744. }
  62745. if (this._sizeGradientsTexture) {
  62746. this._sizeGradientsTexture.dispose();
  62747. this._sizeGradientsTexture = null;
  62748. }
  62749. if (this._angularSpeedGradientsTexture) {
  62750. this._angularSpeedGradientsTexture.dispose();
  62751. this._angularSpeedGradientsTexture = null;
  62752. }
  62753. if (this._velocityGradientsTexture) {
  62754. this._velocityGradientsTexture.dispose();
  62755. this._velocityGradientsTexture = null;
  62756. }
  62757. if (this._limitVelocityGradientsTexture) {
  62758. this._limitVelocityGradientsTexture.dispose();
  62759. this._limitVelocityGradientsTexture = null;
  62760. }
  62761. if (this._dragGradientsTexture) {
  62762. this._dragGradientsTexture.dispose();
  62763. this._dragGradientsTexture = null;
  62764. }
  62765. if (this._randomTexture) {
  62766. this._randomTexture.dispose();
  62767. this._randomTexture = null;
  62768. }
  62769. if (this._randomTexture2) {
  62770. this._randomTexture2.dispose();
  62771. this._randomTexture2 = null;
  62772. }
  62773. if (disposeTexture && this.particleTexture) {
  62774. this.particleTexture.dispose();
  62775. this.particleTexture = null;
  62776. }
  62777. if (disposeTexture && this.noiseTexture) {
  62778. this.noiseTexture.dispose();
  62779. this.noiseTexture = null;
  62780. }
  62781. // Callback
  62782. this.onDisposeObservable.notifyObservers(this);
  62783. this.onDisposeObservable.clear();
  62784. };
  62785. /**
  62786. * Clones the particle system.
  62787. * @param name The name of the cloned object
  62788. * @param newEmitter The new emitter to use
  62789. * @returns the cloned particle system
  62790. */
  62791. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  62792. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  62793. BABYLON.Tools.DeepCopy(this, result);
  62794. if (newEmitter === undefined) {
  62795. newEmitter = this.emitter;
  62796. }
  62797. result.emitter = newEmitter;
  62798. if (this.particleTexture) {
  62799. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  62800. }
  62801. return result;
  62802. };
  62803. /**
  62804. * Serializes the particle system to a JSON object.
  62805. * @returns the JSON object
  62806. */
  62807. GPUParticleSystem.prototype.serialize = function () {
  62808. var serializationObject = {};
  62809. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  62810. serializationObject.activeParticleCount = this.activeParticleCount;
  62811. return serializationObject;
  62812. };
  62813. /**
  62814. * Parses a JSON object to create a GPU particle system.
  62815. * @param parsedParticleSystem The JSON object to parse
  62816. * @param scene The scene to create the particle system in
  62817. * @param rootUrl The root url to use to load external dependencies like texture
  62818. * @returns the parsed GPU particle system
  62819. */
  62820. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  62821. var name = parsedParticleSystem.name;
  62822. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  62823. if (parsedParticleSystem.activeParticleCount) {
  62824. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  62825. }
  62826. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62827. return particleSystem;
  62828. };
  62829. return GPUParticleSystem;
  62830. }(BABYLON.BaseParticleSystem));
  62831. BABYLON.GPUParticleSystem = GPUParticleSystem;
  62832. })(BABYLON || (BABYLON = {}));
  62833. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  62834. var BABYLON;
  62835. (function (BABYLON) {
  62836. /**
  62837. * Represents one particle of a solid particle system.
  62838. */
  62839. var SolidParticle = /** @class */ (function () {
  62840. /**
  62841. * Creates a Solid Particle object.
  62842. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  62843. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  62844. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  62845. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  62846. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  62847. * @param shapeId (integer) is the model shape identifier in the SPS.
  62848. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  62849. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  62850. */
  62851. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  62852. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  62853. /**
  62854. * particle global index
  62855. */
  62856. this.idx = 0;
  62857. /**
  62858. * The color of the particle
  62859. */
  62860. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  62861. /**
  62862. * The world space position of the particle.
  62863. */
  62864. this.position = BABYLON.Vector3.Zero();
  62865. /**
  62866. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  62867. */
  62868. this.rotation = BABYLON.Vector3.Zero();
  62869. /**
  62870. * The scaling of the particle.
  62871. */
  62872. this.scaling = BABYLON.Vector3.One();
  62873. /**
  62874. * The uvs of the particle.
  62875. */
  62876. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  62877. /**
  62878. * The current speed of the particle.
  62879. */
  62880. this.velocity = BABYLON.Vector3.Zero();
  62881. /**
  62882. * The pivot point in the particle local space.
  62883. */
  62884. this.pivot = BABYLON.Vector3.Zero();
  62885. /**
  62886. * Must the particle be translated from its pivot point in its local space ?
  62887. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  62888. * Default : false
  62889. */
  62890. this.translateFromPivot = false;
  62891. /**
  62892. * Is the particle active or not ?
  62893. */
  62894. this.alive = true;
  62895. /**
  62896. * Is the particle visible or not ?
  62897. */
  62898. this.isVisible = true;
  62899. /**
  62900. * Index of this particle in the global "positions" array (Internal use)
  62901. * @hidden
  62902. */
  62903. this._pos = 0;
  62904. /**
  62905. * @hidden Index of this particle in the global "indices" array (Internal use)
  62906. */
  62907. this._ind = 0;
  62908. /**
  62909. * ModelShape id of this particle
  62910. */
  62911. this.shapeId = 0;
  62912. /**
  62913. * Index of the particle in its shape id (Internal use)
  62914. */
  62915. this.idxInShape = 0;
  62916. /**
  62917. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  62918. */
  62919. this._stillInvisible = false;
  62920. /**
  62921. * @hidden Last computed particle rotation matrix
  62922. */
  62923. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  62924. /**
  62925. * Parent particle Id, if any.
  62926. * Default null.
  62927. */
  62928. this.parentId = null;
  62929. /**
  62930. * @hidden Internal global position in the SPS.
  62931. */
  62932. this._globalPosition = BABYLON.Vector3.Zero();
  62933. this.idx = particleIndex;
  62934. this._pos = positionIndex;
  62935. this._ind = indiceIndex;
  62936. this._model = model;
  62937. this.shapeId = shapeId;
  62938. this.idxInShape = idxInShape;
  62939. this._sps = sps;
  62940. if (modelBoundingInfo) {
  62941. this._modelBoundingInfo = modelBoundingInfo;
  62942. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  62943. }
  62944. }
  62945. Object.defineProperty(SolidParticle.prototype, "scale", {
  62946. /**
  62947. * Legacy support, changed scale to scaling
  62948. */
  62949. get: function () {
  62950. return this.scaling;
  62951. },
  62952. /**
  62953. * Legacy support, changed scale to scaling
  62954. */
  62955. set: function (scale) {
  62956. this.scaling = scale;
  62957. },
  62958. enumerable: true,
  62959. configurable: true
  62960. });
  62961. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  62962. /**
  62963. * Legacy support, changed quaternion to rotationQuaternion
  62964. */
  62965. get: function () {
  62966. return this.rotationQuaternion;
  62967. },
  62968. /**
  62969. * Legacy support, changed quaternion to rotationQuaternion
  62970. */
  62971. set: function (q) {
  62972. this.rotationQuaternion = q;
  62973. },
  62974. enumerable: true,
  62975. configurable: true
  62976. });
  62977. /**
  62978. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  62979. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  62980. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  62981. * @returns true if it intersects
  62982. */
  62983. SolidParticle.prototype.intersectsMesh = function (target) {
  62984. if (!this._boundingInfo || !target._boundingInfo) {
  62985. return false;
  62986. }
  62987. if (this._sps._bSphereOnly) {
  62988. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  62989. }
  62990. return this._boundingInfo.intersects(target._boundingInfo, false);
  62991. };
  62992. return SolidParticle;
  62993. }());
  62994. BABYLON.SolidParticle = SolidParticle;
  62995. /**
  62996. * Represents the shape of the model used by one particle of a solid particle system.
  62997. * SPS internal tool, don't use it manually.
  62998. */
  62999. var ModelShape = /** @class */ (function () {
  63000. /**
  63001. * 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.
  63002. * SPS internal tool, don't use it manually.
  63003. * @hidden
  63004. */
  63005. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  63006. /**
  63007. * length of the shape in the model indices array (internal use)
  63008. * @hidden
  63009. */
  63010. this._indicesLength = 0;
  63011. this.shapeID = id;
  63012. this._shape = shape;
  63013. this._indicesLength = indicesLength;
  63014. this._shapeUV = shapeUV;
  63015. this._positionFunction = posFunction;
  63016. this._vertexFunction = vtxFunction;
  63017. }
  63018. return ModelShape;
  63019. }());
  63020. BABYLON.ModelShape = ModelShape;
  63021. /**
  63022. * Represents a Depth Sorted Particle in the solid particle system.
  63023. */
  63024. var DepthSortedParticle = /** @class */ (function () {
  63025. function DepthSortedParticle() {
  63026. /**
  63027. * Index of the particle in the "indices" array
  63028. */
  63029. this.ind = 0;
  63030. /**
  63031. * Length of the particle shape in the "indices" array
  63032. */
  63033. this.indicesLength = 0;
  63034. /**
  63035. * Squared distance from the particle to the camera
  63036. */
  63037. this.sqDistance = 0.0;
  63038. }
  63039. return DepthSortedParticle;
  63040. }());
  63041. BABYLON.DepthSortedParticle = DepthSortedParticle;
  63042. })(BABYLON || (BABYLON = {}));
  63043. //# sourceMappingURL=babylon.solidParticle.js.map
  63044. var BABYLON;
  63045. (function (BABYLON) {
  63046. /**
  63047. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  63048. *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.
  63049. * The SPS is also a particle system. It provides some methods to manage the particles.
  63050. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  63051. *
  63052. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  63053. */
  63054. var SolidParticleSystem = /** @class */ (function () {
  63055. /**
  63056. * Creates a SPS (Solid Particle System) object.
  63057. * @param name (String) is the SPS name, this will be the underlying mesh name.
  63058. * @param scene (Scene) is the scene in which the SPS is added.
  63059. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  63060. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  63061. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  63062. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  63063. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  63064. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  63065. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  63066. */
  63067. function SolidParticleSystem(name, scene, options) {
  63068. /**
  63069. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  63070. * Example : var p = SPS.particles[i];
  63071. */
  63072. this.particles = new Array();
  63073. /**
  63074. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  63075. */
  63076. this.nbParticles = 0;
  63077. /**
  63078. * If the particles must ever face the camera (default false). Useful for planar particles.
  63079. */
  63080. this.billboard = false;
  63081. /**
  63082. * Recompute normals when adding a shape
  63083. */
  63084. this.recomputeNormals = true;
  63085. /**
  63086. * This a counter ofr your own usage. It's not set by any SPS functions.
  63087. */
  63088. this.counter = 0;
  63089. /**
  63090. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  63091. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  63092. */
  63093. this.vars = {};
  63094. /**
  63095. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  63096. * @hidden
  63097. */
  63098. this._bSphereOnly = false;
  63099. /**
  63100. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  63101. * @hidden
  63102. */
  63103. this._bSphereRadiusFactor = 1.0;
  63104. this._positions = new Array();
  63105. this._indices = new Array();
  63106. this._normals = new Array();
  63107. this._colors = new Array();
  63108. this._uvs = new Array();
  63109. this._index = 0; // indices index
  63110. this._updatable = true;
  63111. this._pickable = false;
  63112. this._isVisibilityBoxLocked = false;
  63113. this._alwaysVisible = false;
  63114. this._depthSort = false;
  63115. this._shapeCounter = 0;
  63116. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  63117. this._color = new BABYLON.Color4(0, 0, 0, 0);
  63118. this._computeParticleColor = true;
  63119. this._computeParticleTexture = true;
  63120. this._computeParticleRotation = true;
  63121. this._computeParticleVertex = false;
  63122. this._computeBoundingBox = false;
  63123. this._depthSortParticles = true;
  63124. this._cam_axisZ = BABYLON.Vector3.Zero();
  63125. this._cam_axisY = BABYLON.Vector3.Zero();
  63126. this._cam_axisX = BABYLON.Vector3.Zero();
  63127. this._axisZ = BABYLON.Axis.Z;
  63128. this._camDir = BABYLON.Vector3.Zero();
  63129. this._camInvertedPosition = BABYLON.Vector3.Zero();
  63130. this._rotMatrix = new BABYLON.Matrix();
  63131. this._invertMatrix = new BABYLON.Matrix();
  63132. this._rotated = BABYLON.Vector3.Zero();
  63133. this._quaternion = new BABYLON.Quaternion();
  63134. this._vertex = BABYLON.Vector3.Zero();
  63135. this._normal = BABYLON.Vector3.Zero();
  63136. this._yaw = 0.0;
  63137. this._pitch = 0.0;
  63138. this._roll = 0.0;
  63139. this._halfroll = 0.0;
  63140. this._halfpitch = 0.0;
  63141. this._halfyaw = 0.0;
  63142. this._sinRoll = 0.0;
  63143. this._cosRoll = 0.0;
  63144. this._sinPitch = 0.0;
  63145. this._cosPitch = 0.0;
  63146. this._sinYaw = 0.0;
  63147. this._cosYaw = 0.0;
  63148. this._mustUnrotateFixedNormals = false;
  63149. this._minimum = BABYLON.Vector3.Zero();
  63150. this._maximum = BABYLON.Vector3.Zero();
  63151. this._minBbox = BABYLON.Vector3.Zero();
  63152. this._maxBbox = BABYLON.Vector3.Zero();
  63153. this._particlesIntersect = false;
  63154. this._depthSortFunction = function (p1, p2) {
  63155. return (p2.sqDistance - p1.sqDistance);
  63156. };
  63157. this._needs32Bits = false;
  63158. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  63159. this._scaledPivot = BABYLON.Vector3.Zero();
  63160. this._particleHasParent = false;
  63161. this.name = name;
  63162. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63163. this._camera = scene.activeCamera;
  63164. this._pickable = options ? options.isPickable : false;
  63165. this._depthSort = options ? options.enableDepthSort : false;
  63166. this._particlesIntersect = options ? options.particleIntersection : false;
  63167. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  63168. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  63169. if (options && options.updatable !== undefined) {
  63170. this._updatable = options.updatable;
  63171. }
  63172. else {
  63173. this._updatable = true;
  63174. }
  63175. if (this._pickable) {
  63176. this.pickedParticles = [];
  63177. }
  63178. if (this._depthSort) {
  63179. this.depthSortedParticles = [];
  63180. }
  63181. }
  63182. /**
  63183. * Builds the SPS underlying mesh. Returns a standard Mesh.
  63184. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  63185. * @returns the created mesh
  63186. */
  63187. SolidParticleSystem.prototype.buildMesh = function () {
  63188. if (this.nbParticles === 0) {
  63189. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  63190. this.addShape(triangle, 1);
  63191. triangle.dispose();
  63192. }
  63193. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  63194. this._positions32 = new Float32Array(this._positions);
  63195. this._uvs32 = new Float32Array(this._uvs);
  63196. this._colors32 = new Float32Array(this._colors);
  63197. if (this.recomputeNormals) {
  63198. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  63199. }
  63200. this._normals32 = new Float32Array(this._normals);
  63201. this._fixedNormal32 = new Float32Array(this._normals);
  63202. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  63203. this._unrotateFixedNormals();
  63204. }
  63205. var vertexData = new BABYLON.VertexData();
  63206. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  63207. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  63208. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  63209. if (this._uvs32.length > 0) {
  63210. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  63211. }
  63212. if (this._colors32.length > 0) {
  63213. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  63214. }
  63215. var mesh = new BABYLON.Mesh(this.name, this._scene);
  63216. vertexData.applyToMesh(mesh, this._updatable);
  63217. this.mesh = mesh;
  63218. this.mesh.isPickable = this._pickable;
  63219. // free memory
  63220. if (!this._depthSort) {
  63221. this._indices = null;
  63222. }
  63223. this._positions = null;
  63224. this._normals = null;
  63225. this._uvs = null;
  63226. this._colors = null;
  63227. if (!this._updatable) {
  63228. this.particles.length = 0;
  63229. }
  63230. return mesh;
  63231. };
  63232. /**
  63233. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  63234. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  63235. * Thus the particles generated from `digest()` have their property `position` set yet.
  63236. * @param mesh ( Mesh ) is the mesh to be digested
  63237. * @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
  63238. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  63239. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  63240. * @returns the current SPS
  63241. */
  63242. SolidParticleSystem.prototype.digest = function (mesh, options) {
  63243. var size = (options && options.facetNb) || 1;
  63244. var number = (options && options.number) || 0;
  63245. var delta = (options && options.delta) || 0;
  63246. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63247. var meshInd = mesh.getIndices();
  63248. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63249. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63250. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63251. var f = 0; // facet counter
  63252. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  63253. // compute size from number
  63254. if (number) {
  63255. number = (number > totalFacets) ? totalFacets : number;
  63256. size = Math.round(totalFacets / number);
  63257. delta = 0;
  63258. }
  63259. else {
  63260. size = (size > totalFacets) ? totalFacets : size;
  63261. }
  63262. var facetPos = []; // submesh positions
  63263. var facetInd = []; // submesh indices
  63264. var facetUV = []; // submesh UV
  63265. var facetCol = []; // submesh colors
  63266. var barycenter = BABYLON.Vector3.Zero();
  63267. var sizeO = size;
  63268. while (f < totalFacets) {
  63269. size = sizeO + Math.floor((1 + delta) * Math.random());
  63270. if (f > totalFacets - size) {
  63271. size = totalFacets - f;
  63272. }
  63273. // reset temp arrays
  63274. facetPos.length = 0;
  63275. facetInd.length = 0;
  63276. facetUV.length = 0;
  63277. facetCol.length = 0;
  63278. // iterate over "size" facets
  63279. var fi = 0;
  63280. for (var j = f * 3; j < (f + size) * 3; j++) {
  63281. facetInd.push(fi);
  63282. var i = meshInd[j];
  63283. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  63284. if (meshUV) {
  63285. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  63286. }
  63287. if (meshCol) {
  63288. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  63289. }
  63290. fi++;
  63291. }
  63292. // create a model shape for each single particle
  63293. var idx = this.nbParticles;
  63294. var shape = this._posToShape(facetPos);
  63295. var shapeUV = this._uvsToShapeUV(facetUV);
  63296. // compute the barycenter of the shape
  63297. var v;
  63298. for (v = 0; v < shape.length; v++) {
  63299. barycenter.addInPlace(shape[v]);
  63300. }
  63301. barycenter.scaleInPlace(1 / shape.length);
  63302. // shift the shape from its barycenter to the origin
  63303. for (v = 0; v < shape.length; v++) {
  63304. shape[v].subtractInPlace(barycenter);
  63305. }
  63306. var bInfo;
  63307. if (this._particlesIntersect) {
  63308. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  63309. }
  63310. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  63311. // add the particle in the SPS
  63312. var currentPos = this._positions.length;
  63313. var currentInd = this._indices.length;
  63314. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  63315. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  63316. // initialize the particle position
  63317. this.particles[this.nbParticles].position.addInPlace(barycenter);
  63318. this._index += shape.length;
  63319. idx++;
  63320. this.nbParticles++;
  63321. this._shapeCounter++;
  63322. f += size;
  63323. }
  63324. return this;
  63325. };
  63326. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  63327. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  63328. var index = 0;
  63329. var idx = 0;
  63330. for (var p = 0; p < this.particles.length; p++) {
  63331. this._particle = this.particles[p];
  63332. this._shape = this._particle._model._shape;
  63333. if (this._particle.rotationQuaternion) {
  63334. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63335. }
  63336. else {
  63337. this._yaw = this._particle.rotation.y;
  63338. this._pitch = this._particle.rotation.x;
  63339. this._roll = this._particle.rotation.z;
  63340. this._quaternionRotationYPR();
  63341. }
  63342. this._quaternionToRotationMatrix();
  63343. this._rotMatrix.invertToRef(this._invertMatrix);
  63344. for (var pt = 0; pt < this._shape.length; pt++) {
  63345. idx = index + pt * 3;
  63346. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  63347. this._fixedNormal32[idx] = this._normal.x;
  63348. this._fixedNormal32[idx + 1] = this._normal.y;
  63349. this._fixedNormal32[idx + 2] = this._normal.z;
  63350. }
  63351. index = idx + 3;
  63352. }
  63353. };
  63354. //reset copy
  63355. SolidParticleSystem.prototype._resetCopy = function () {
  63356. this._copy.position.x = 0;
  63357. this._copy.position.y = 0;
  63358. this._copy.position.z = 0;
  63359. this._copy.rotation.x = 0;
  63360. this._copy.rotation.y = 0;
  63361. this._copy.rotation.z = 0;
  63362. this._copy.rotationQuaternion = null;
  63363. this._copy.scaling.x = 1.0;
  63364. this._copy.scaling.y = 1.0;
  63365. this._copy.scaling.z = 1.0;
  63366. this._copy.uvs.x = 0;
  63367. this._copy.uvs.y = 0;
  63368. this._copy.uvs.z = 1.0;
  63369. this._copy.uvs.w = 1.0;
  63370. this._copy.color = null;
  63371. this._copy.translateFromPivot = false;
  63372. };
  63373. // _meshBuilder : inserts the shape model in the global SPS mesh
  63374. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  63375. var i;
  63376. var u = 0;
  63377. var c = 0;
  63378. var n = 0;
  63379. this._resetCopy();
  63380. if (options && options.positionFunction) { // call to custom positionFunction
  63381. options.positionFunction(this._copy, idx, idxInShape);
  63382. this._mustUnrotateFixedNormals = true;
  63383. }
  63384. if (this._copy.rotationQuaternion) {
  63385. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63386. }
  63387. else {
  63388. this._yaw = this._copy.rotation.y;
  63389. this._pitch = this._copy.rotation.x;
  63390. this._roll = this._copy.rotation.z;
  63391. this._quaternionRotationYPR();
  63392. }
  63393. this._quaternionToRotationMatrix();
  63394. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  63395. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  63396. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  63397. if (this._copy.translateFromPivot) {
  63398. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63399. }
  63400. else {
  63401. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63402. }
  63403. for (i = 0; i < shape.length; i++) {
  63404. this._vertex.x = shape[i].x;
  63405. this._vertex.y = shape[i].y;
  63406. this._vertex.z = shape[i].z;
  63407. if (options && options.vertexFunction) {
  63408. options.vertexFunction(this._copy, this._vertex, i);
  63409. }
  63410. this._vertex.x *= this._copy.scaling.x;
  63411. this._vertex.y *= this._copy.scaling.y;
  63412. this._vertex.z *= this._copy.scaling.z;
  63413. this._vertex.x -= this._scaledPivot.x;
  63414. this._vertex.y -= this._scaledPivot.y;
  63415. this._vertex.z -= this._scaledPivot.z;
  63416. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63417. this._rotated.addInPlace(this._pivotBackTranslation);
  63418. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  63419. if (meshUV) {
  63420. 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);
  63421. u += 2;
  63422. }
  63423. if (this._copy.color) {
  63424. this._color = this._copy.color;
  63425. }
  63426. else if (meshCol && meshCol[c] !== undefined) {
  63427. this._color.r = meshCol[c];
  63428. this._color.g = meshCol[c + 1];
  63429. this._color.b = meshCol[c + 2];
  63430. this._color.a = meshCol[c + 3];
  63431. }
  63432. else {
  63433. this._color.r = 1.0;
  63434. this._color.g = 1.0;
  63435. this._color.b = 1.0;
  63436. this._color.a = 1.0;
  63437. }
  63438. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  63439. c += 4;
  63440. if (!this.recomputeNormals && meshNor) {
  63441. this._normal.x = meshNor[n];
  63442. this._normal.y = meshNor[n + 1];
  63443. this._normal.z = meshNor[n + 2];
  63444. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  63445. normals.push(this._normal.x, this._normal.y, this._normal.z);
  63446. n += 3;
  63447. }
  63448. }
  63449. for (i = 0; i < meshInd.length; i++) {
  63450. var current_ind = p + meshInd[i];
  63451. indices.push(current_ind);
  63452. if (current_ind > 65535) {
  63453. this._needs32Bits = true;
  63454. }
  63455. }
  63456. if (this._pickable) {
  63457. var nbfaces = meshInd.length / 3;
  63458. for (i = 0; i < nbfaces; i++) {
  63459. this.pickedParticles.push({ idx: idx, faceId: i });
  63460. }
  63461. }
  63462. if (this._depthSort) {
  63463. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  63464. }
  63465. return this._copy;
  63466. };
  63467. // returns a shape array from positions array
  63468. SolidParticleSystem.prototype._posToShape = function (positions) {
  63469. var shape = [];
  63470. for (var i = 0; i < positions.length; i += 3) {
  63471. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  63472. }
  63473. return shape;
  63474. };
  63475. // returns a shapeUV array from a Vector4 uvs
  63476. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  63477. var shapeUV = [];
  63478. if (uvs) {
  63479. for (var i = 0; i < uvs.length; i++)
  63480. shapeUV.push(uvs[i]);
  63481. }
  63482. return shapeUV;
  63483. };
  63484. // adds a new particle object in the particles array
  63485. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  63486. if (bInfo === void 0) { bInfo = null; }
  63487. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  63488. this.particles.push(sp);
  63489. return sp;
  63490. };
  63491. /**
  63492. * Adds some particles to the SPS from the model shape. Returns the shape id.
  63493. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  63494. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  63495. * @param nb (positive integer) the number of particles to be created from this model
  63496. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  63497. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  63498. * @returns the number of shapes in the system
  63499. */
  63500. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  63501. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63502. var meshInd = mesh.getIndices();
  63503. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63504. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63505. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63506. var bbInfo;
  63507. if (this._particlesIntersect) {
  63508. bbInfo = mesh.getBoundingInfo();
  63509. }
  63510. var shape = this._posToShape(meshPos);
  63511. var shapeUV = this._uvsToShapeUV(meshUV);
  63512. var posfunc = options ? options.positionFunction : null;
  63513. var vtxfunc = options ? options.vertexFunction : null;
  63514. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  63515. // particles
  63516. var sp;
  63517. var currentCopy;
  63518. var idx = this.nbParticles;
  63519. for (var i = 0; i < nb; i++) {
  63520. var currentPos = this._positions.length;
  63521. var currentInd = this._indices.length;
  63522. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  63523. if (this._updatable) {
  63524. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  63525. sp.position.copyFrom(currentCopy.position);
  63526. sp.rotation.copyFrom(currentCopy.rotation);
  63527. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  63528. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  63529. }
  63530. if (currentCopy.color && sp.color) {
  63531. sp.color.copyFrom(currentCopy.color);
  63532. }
  63533. sp.scaling.copyFrom(currentCopy.scaling);
  63534. sp.uvs.copyFrom(currentCopy.uvs);
  63535. }
  63536. this._index += shape.length;
  63537. idx++;
  63538. }
  63539. this.nbParticles += nb;
  63540. this._shapeCounter++;
  63541. return this._shapeCounter - 1;
  63542. };
  63543. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  63544. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  63545. this._resetCopy();
  63546. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  63547. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  63548. }
  63549. if (this._copy.rotationQuaternion) {
  63550. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63551. }
  63552. else {
  63553. this._yaw = this._copy.rotation.y;
  63554. this._pitch = this._copy.rotation.x;
  63555. this._roll = this._copy.rotation.z;
  63556. this._quaternionRotationYPR();
  63557. }
  63558. this._quaternionToRotationMatrix();
  63559. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63560. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63561. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63562. if (this._copy.translateFromPivot) {
  63563. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63564. }
  63565. else {
  63566. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63567. }
  63568. this._shape = particle._model._shape;
  63569. for (var pt = 0; pt < this._shape.length; pt++) {
  63570. this._vertex.x = this._shape[pt].x;
  63571. this._vertex.y = this._shape[pt].y;
  63572. this._vertex.z = this._shape[pt].z;
  63573. if (particle._model._vertexFunction) {
  63574. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  63575. }
  63576. this._vertex.x *= this._copy.scaling.x;
  63577. this._vertex.y *= this._copy.scaling.y;
  63578. this._vertex.z *= this._copy.scaling.z;
  63579. this._vertex.x -= this._scaledPivot.x;
  63580. this._vertex.y -= this._scaledPivot.y;
  63581. this._vertex.z -= this._scaledPivot.z;
  63582. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63583. this._rotated.addInPlace(this._pivotBackTranslation);
  63584. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  63585. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  63586. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  63587. }
  63588. particle.position.x = 0.0;
  63589. particle.position.y = 0.0;
  63590. particle.position.z = 0.0;
  63591. particle.rotation.x = 0.0;
  63592. particle.rotation.y = 0.0;
  63593. particle.rotation.z = 0.0;
  63594. particle.rotationQuaternion = null;
  63595. particle.scaling.x = 1.0;
  63596. particle.scaling.y = 1.0;
  63597. particle.scaling.z = 1.0;
  63598. particle.uvs.x = 0.0;
  63599. particle.uvs.y = 0.0;
  63600. particle.uvs.z = 1.0;
  63601. particle.uvs.w = 1.0;
  63602. particle.pivot.x = 0.0;
  63603. particle.pivot.y = 0.0;
  63604. particle.pivot.z = 0.0;
  63605. particle.translateFromPivot = false;
  63606. particle.parentId = null;
  63607. };
  63608. /**
  63609. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  63610. * @returns the SPS.
  63611. */
  63612. SolidParticleSystem.prototype.rebuildMesh = function () {
  63613. for (var p = 0; p < this.particles.length; p++) {
  63614. this._rebuildParticle(this.particles[p]);
  63615. }
  63616. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63617. return this;
  63618. };
  63619. /**
  63620. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  63621. * This method calls `updateParticle()` for each particle of the SPS.
  63622. * For an animated SPS, it is usually called within the render loop.
  63623. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  63624. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  63625. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  63626. * @returns the SPS.
  63627. */
  63628. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  63629. if (start === void 0) { start = 0; }
  63630. if (end === void 0) { end = this.nbParticles - 1; }
  63631. if (update === void 0) { update = true; }
  63632. if (!this._updatable) {
  63633. return this;
  63634. }
  63635. // custom beforeUpdate
  63636. this.beforeUpdateParticles(start, end, update);
  63637. this._cam_axisX.x = 1.0;
  63638. this._cam_axisX.y = 0.0;
  63639. this._cam_axisX.z = 0.0;
  63640. this._cam_axisY.x = 0.0;
  63641. this._cam_axisY.y = 1.0;
  63642. this._cam_axisY.z = 0.0;
  63643. this._cam_axisZ.x = 0.0;
  63644. this._cam_axisZ.y = 0.0;
  63645. this._cam_axisZ.z = 1.0;
  63646. // cases when the World Matrix is to be computed first
  63647. if (this.billboard || this._depthSort) {
  63648. this.mesh.computeWorldMatrix(true);
  63649. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  63650. }
  63651. // if the particles will always face the camera
  63652. if (this.billboard) {
  63653. // compute the camera position and un-rotate it by the current mesh rotation
  63654. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  63655. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  63656. this._cam_axisZ.normalize();
  63657. // same for camera up vector extracted from the cam view matrix
  63658. var view = this._camera.getViewMatrix(true);
  63659. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  63660. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  63661. this._cam_axisY.normalize();
  63662. this._cam_axisX.normalize();
  63663. }
  63664. // if depthSort, compute the camera global position in the mesh local system
  63665. if (this._depthSort) {
  63666. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  63667. }
  63668. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  63669. var idx = 0; // current position index in the global array positions32
  63670. var index = 0; // position start index in the global array positions32 of the current particle
  63671. var colidx = 0; // current color index in the global array colors32
  63672. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  63673. var uvidx = 0; // current uv index in the global array uvs32
  63674. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  63675. var pt = 0; // current index in the particle model shape
  63676. if (this.mesh.isFacetDataEnabled) {
  63677. this._computeBoundingBox = true;
  63678. }
  63679. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  63680. if (this._computeBoundingBox) {
  63681. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  63682. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  63683. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  63684. }
  63685. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  63686. if (this.mesh._boundingInfo) {
  63687. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  63688. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  63689. }
  63690. }
  63691. }
  63692. // particle loop
  63693. index = this.particles[start]._pos;
  63694. var vpos = (index / 3) | 0;
  63695. colorIndex = vpos * 4;
  63696. uvIndex = vpos * 2;
  63697. for (var p = start; p <= end; p++) {
  63698. this._particle = this.particles[p];
  63699. this._shape = this._particle._model._shape;
  63700. this._shapeUV = this._particle._model._shapeUV;
  63701. // call to custom user function to update the particle properties
  63702. this.updateParticle(this._particle);
  63703. // camera-particle distance for depth sorting
  63704. if (this._depthSort && this._depthSortParticles) {
  63705. var dsp = this.depthSortedParticles[p];
  63706. dsp.ind = this._particle._ind;
  63707. dsp.indicesLength = this._particle._model._indicesLength;
  63708. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  63709. }
  63710. // skip the computations for inactive or already invisible particles
  63711. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  63712. // increment indexes for the next particle
  63713. pt = this._shape.length;
  63714. index += pt * 3;
  63715. colorIndex += pt * 4;
  63716. uvIndex += pt * 2;
  63717. continue;
  63718. }
  63719. if (this._particle.isVisible) {
  63720. this._particle._stillInvisible = false; // un-mark permanent invisibility
  63721. this._particleHasParent = (this._particle.parentId !== null);
  63722. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63723. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63724. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63725. // particle rotation matrix
  63726. if (this.billboard) {
  63727. this._particle.rotation.x = 0.0;
  63728. this._particle.rotation.y = 0.0;
  63729. }
  63730. if (this._computeParticleRotation || this.billboard) {
  63731. if (this._particle.rotationQuaternion) {
  63732. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63733. }
  63734. else {
  63735. this._yaw = this._particle.rotation.y;
  63736. this._pitch = this._particle.rotation.x;
  63737. this._roll = this._particle.rotation.z;
  63738. this._quaternionRotationYPR();
  63739. }
  63740. this._quaternionToRotationMatrix();
  63741. }
  63742. if (this._particleHasParent) {
  63743. this._parent = this.particles[this._particle.parentId];
  63744. 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];
  63745. 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];
  63746. 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];
  63747. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  63748. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  63749. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  63750. if (this._computeParticleRotation || this.billboard) {
  63751. 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];
  63752. 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];
  63753. 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];
  63754. 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];
  63755. 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];
  63756. 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];
  63757. 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];
  63758. 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];
  63759. 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];
  63760. }
  63761. }
  63762. else {
  63763. this._particle._globalPosition.x = this._particle.position.x;
  63764. this._particle._globalPosition.y = this._particle.position.y;
  63765. this._particle._globalPosition.z = this._particle.position.z;
  63766. if (this._computeParticleRotation || this.billboard) {
  63767. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  63768. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  63769. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  63770. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  63771. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  63772. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  63773. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  63774. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  63775. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  63776. }
  63777. }
  63778. if (this._particle.translateFromPivot) {
  63779. this._pivotBackTranslation.x = 0.0;
  63780. this._pivotBackTranslation.y = 0.0;
  63781. this._pivotBackTranslation.z = 0.0;
  63782. }
  63783. else {
  63784. this._pivotBackTranslation.x = this._scaledPivot.x;
  63785. this._pivotBackTranslation.y = this._scaledPivot.y;
  63786. this._pivotBackTranslation.z = this._scaledPivot.z;
  63787. }
  63788. // particle vertex loop
  63789. for (pt = 0; pt < this._shape.length; pt++) {
  63790. idx = index + pt * 3;
  63791. colidx = colorIndex + pt * 4;
  63792. uvidx = uvIndex + pt * 2;
  63793. this._vertex.x = this._shape[pt].x;
  63794. this._vertex.y = this._shape[pt].y;
  63795. this._vertex.z = this._shape[pt].z;
  63796. if (this._computeParticleVertex) {
  63797. this.updateParticleVertex(this._particle, this._vertex, pt);
  63798. }
  63799. // positions
  63800. this._vertex.x *= this._particle.scaling.x;
  63801. this._vertex.y *= this._particle.scaling.y;
  63802. this._vertex.z *= this._particle.scaling.z;
  63803. this._vertex.x -= this._scaledPivot.x;
  63804. this._vertex.y -= this._scaledPivot.y;
  63805. this._vertex.z -= this._scaledPivot.z;
  63806. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63807. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63808. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63809. this._rotated.x += this._pivotBackTranslation.x;
  63810. this._rotated.y += this._pivotBackTranslation.y;
  63811. this._rotated.z += this._pivotBackTranslation.z;
  63812. 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;
  63813. 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;
  63814. 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;
  63815. if (this._computeBoundingBox) {
  63816. if (this._positions32[idx] < this._minimum.x) {
  63817. this._minimum.x = this._positions32[idx];
  63818. }
  63819. if (this._positions32[idx] > this._maximum.x) {
  63820. this._maximum.x = this._positions32[idx];
  63821. }
  63822. if (this._positions32[idx + 1] < this._minimum.y) {
  63823. this._minimum.y = this._positions32[idx + 1];
  63824. }
  63825. if (this._positions32[idx + 1] > this._maximum.y) {
  63826. this._maximum.y = this._positions32[idx + 1];
  63827. }
  63828. if (this._positions32[idx + 2] < this._minimum.z) {
  63829. this._minimum.z = this._positions32[idx + 2];
  63830. }
  63831. if (this._positions32[idx + 2] > this._maximum.z) {
  63832. this._maximum.z = this._positions32[idx + 2];
  63833. }
  63834. }
  63835. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  63836. if (!this._computeParticleVertex) {
  63837. this._normal.x = this._fixedNormal32[idx];
  63838. this._normal.y = this._fixedNormal32[idx + 1];
  63839. this._normal.z = this._fixedNormal32[idx + 2];
  63840. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  63841. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  63842. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  63843. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  63844. 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;
  63845. 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;
  63846. }
  63847. if (this._computeParticleColor && this._particle.color) {
  63848. this._colors32[colidx] = this._particle.color.r;
  63849. this._colors32[colidx + 1] = this._particle.color.g;
  63850. this._colors32[colidx + 2] = this._particle.color.b;
  63851. this._colors32[colidx + 3] = this._particle.color.a;
  63852. }
  63853. if (this._computeParticleTexture) {
  63854. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63855. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63856. }
  63857. }
  63858. }
  63859. // particle just set invisible : scaled to zero and positioned at the origin
  63860. else {
  63861. this._particle._stillInvisible = true; // mark the particle as invisible
  63862. for (pt = 0; pt < this._shape.length; pt++) {
  63863. idx = index + pt * 3;
  63864. colidx = colorIndex + pt * 4;
  63865. uvidx = uvIndex + pt * 2;
  63866. this._positions32[idx] = 0.0;
  63867. this._positions32[idx + 1] = 0.0;
  63868. this._positions32[idx + 2] = 0.0;
  63869. this._normals32[idx] = 0.0;
  63870. this._normals32[idx + 1] = 0.0;
  63871. this._normals32[idx + 2] = 0.0;
  63872. if (this._computeParticleColor && this._particle.color) {
  63873. this._colors32[colidx] = this._particle.color.r;
  63874. this._colors32[colidx + 1] = this._particle.color.g;
  63875. this._colors32[colidx + 2] = this._particle.color.b;
  63876. this._colors32[colidx + 3] = this._particle.color.a;
  63877. }
  63878. if (this._computeParticleTexture) {
  63879. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63880. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63881. }
  63882. }
  63883. }
  63884. // if the particle intersections must be computed : update the bbInfo
  63885. if (this._particlesIntersect) {
  63886. var bInfo = this._particle._boundingInfo;
  63887. var bBox = bInfo.boundingBox;
  63888. var bSphere = bInfo.boundingSphere;
  63889. if (!this._bSphereOnly) {
  63890. // place, scale and rotate the particle bbox within the SPS local system, then update it
  63891. for (var b = 0; b < bBox.vectors.length; b++) {
  63892. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  63893. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  63894. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  63895. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63896. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63897. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63898. 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;
  63899. 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;
  63900. 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;
  63901. }
  63902. bBox._update(this.mesh._worldMatrix);
  63903. }
  63904. // place and scale the particle bouding sphere in the SPS local system, then update it
  63905. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  63906. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  63907. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  63908. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  63909. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  63910. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  63911. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  63912. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  63913. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  63914. 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));
  63915. bSphere._update(this.mesh._worldMatrix);
  63916. }
  63917. // increment indexes for the next particle
  63918. index = idx + 3;
  63919. colorIndex = colidx + 4;
  63920. uvIndex = uvidx + 2;
  63921. }
  63922. // if the VBO must be updated
  63923. if (update) {
  63924. if (this._computeParticleColor) {
  63925. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  63926. }
  63927. if (this._computeParticleTexture) {
  63928. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  63929. }
  63930. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63931. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  63932. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  63933. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  63934. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  63935. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  63936. for (var i = 0; i < this._normals32.length; i++) {
  63937. this._fixedNormal32[i] = this._normals32[i];
  63938. }
  63939. }
  63940. if (!this.mesh.areNormalsFrozen) {
  63941. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  63942. }
  63943. }
  63944. if (this._depthSort && this._depthSortParticles) {
  63945. this.depthSortedParticles.sort(this._depthSortFunction);
  63946. var dspl = this.depthSortedParticles.length;
  63947. var sorted = 0;
  63948. var lind = 0;
  63949. var sind = 0;
  63950. var sid = 0;
  63951. for (sorted = 0; sorted < dspl; sorted++) {
  63952. lind = this.depthSortedParticles[sorted].indicesLength;
  63953. sind = this.depthSortedParticles[sorted].ind;
  63954. for (var i = 0; i < lind; i++) {
  63955. this._indices32[sid] = this._indices[sind + i];
  63956. sid++;
  63957. }
  63958. }
  63959. this.mesh.updateIndices(this._indices32);
  63960. }
  63961. }
  63962. if (this._computeBoundingBox) {
  63963. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  63964. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  63965. }
  63966. this.afterUpdateParticles(start, end, update);
  63967. return this;
  63968. };
  63969. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  63970. this._halfroll = this._roll * 0.5;
  63971. this._halfpitch = this._pitch * 0.5;
  63972. this._halfyaw = this._yaw * 0.5;
  63973. this._sinRoll = Math.sin(this._halfroll);
  63974. this._cosRoll = Math.cos(this._halfroll);
  63975. this._sinPitch = Math.sin(this._halfpitch);
  63976. this._cosPitch = Math.cos(this._halfpitch);
  63977. this._sinYaw = Math.sin(this._halfyaw);
  63978. this._cosYaw = Math.cos(this._halfyaw);
  63979. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  63980. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  63981. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  63982. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  63983. };
  63984. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  63985. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  63986. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  63987. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  63988. this._rotMatrix.m[3] = 0;
  63989. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  63990. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  63991. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  63992. this._rotMatrix.m[7] = 0;
  63993. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  63994. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  63995. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  63996. this._rotMatrix.m[11] = 0;
  63997. this._rotMatrix.m[12] = 0;
  63998. this._rotMatrix.m[13] = 0;
  63999. this._rotMatrix.m[14] = 0;
  64000. this._rotMatrix.m[15] = 1.0;
  64001. };
  64002. /**
  64003. * Disposes the SPS.
  64004. */
  64005. SolidParticleSystem.prototype.dispose = function () {
  64006. this.mesh.dispose();
  64007. this.vars = null;
  64008. // drop references to internal big arrays for the GC
  64009. this._positions = null;
  64010. this._indices = null;
  64011. this._normals = null;
  64012. this._uvs = null;
  64013. this._colors = null;
  64014. this._indices32 = null;
  64015. this._positions32 = null;
  64016. this._normals32 = null;
  64017. this._fixedNormal32 = null;
  64018. this._uvs32 = null;
  64019. this._colors32 = null;
  64020. this.pickedParticles = null;
  64021. };
  64022. /**
  64023. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  64024. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  64025. * @returns the SPS.
  64026. */
  64027. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  64028. if (!this._isVisibilityBoxLocked) {
  64029. this.mesh.refreshBoundingInfo();
  64030. }
  64031. return this;
  64032. };
  64033. /**
  64034. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  64035. * @param size the size (float) of the visibility box
  64036. * note : this doesn't lock the SPS mesh bounding box.
  64037. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  64038. */
  64039. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  64040. var vis = size / 2;
  64041. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  64042. };
  64043. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  64044. /**
  64045. * Gets whether the SPS as always visible or not
  64046. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  64047. */
  64048. get: function () {
  64049. return this._alwaysVisible;
  64050. },
  64051. /**
  64052. * Sets the SPS as always visible or not
  64053. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  64054. */
  64055. set: function (val) {
  64056. this._alwaysVisible = val;
  64057. this.mesh.alwaysSelectAsActiveMesh = val;
  64058. },
  64059. enumerable: true,
  64060. configurable: true
  64061. });
  64062. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  64063. /**
  64064. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  64065. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  64066. */
  64067. get: function () {
  64068. return this._isVisibilityBoxLocked;
  64069. },
  64070. /**
  64071. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  64072. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  64073. */
  64074. set: function (val) {
  64075. this._isVisibilityBoxLocked = val;
  64076. var boundingInfo = this.mesh.getBoundingInfo();
  64077. boundingInfo.isLocked = val;
  64078. },
  64079. enumerable: true,
  64080. configurable: true
  64081. });
  64082. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  64083. /**
  64084. * Gets if `setParticles()` computes the particle rotations or not.
  64085. * Default value : true. The SPS is faster when it's set to false.
  64086. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  64087. */
  64088. get: function () {
  64089. return this._computeParticleRotation;
  64090. },
  64091. /**
  64092. * Tells to `setParticles()` to compute the particle rotations or not.
  64093. * Default value : true. The SPS is faster when it's set to false.
  64094. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  64095. */
  64096. set: function (val) {
  64097. this._computeParticleRotation = val;
  64098. },
  64099. enumerable: true,
  64100. configurable: true
  64101. });
  64102. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  64103. /**
  64104. * Gets if `setParticles()` computes the particle colors or not.
  64105. * Default value : true. The SPS is faster when it's set to false.
  64106. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  64107. */
  64108. get: function () {
  64109. return this._computeParticleColor;
  64110. },
  64111. /**
  64112. * Tells to `setParticles()` to compute the particle colors or not.
  64113. * Default value : true. The SPS is faster when it's set to false.
  64114. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  64115. */
  64116. set: function (val) {
  64117. this._computeParticleColor = val;
  64118. },
  64119. enumerable: true,
  64120. configurable: true
  64121. });
  64122. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  64123. /**
  64124. * Gets if `setParticles()` computes the particle textures or not.
  64125. * Default value : true. The SPS is faster when it's set to false.
  64126. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  64127. */
  64128. get: function () {
  64129. return this._computeParticleTexture;
  64130. },
  64131. set: function (val) {
  64132. this._computeParticleTexture = val;
  64133. },
  64134. enumerable: true,
  64135. configurable: true
  64136. });
  64137. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  64138. /**
  64139. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  64140. * Default value : false. The SPS is faster when it's set to false.
  64141. * Note : the particle custom vertex positions aren't stored values.
  64142. */
  64143. get: function () {
  64144. return this._computeParticleVertex;
  64145. },
  64146. /**
  64147. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  64148. * Default value : false. The SPS is faster when it's set to false.
  64149. * Note : the particle custom vertex positions aren't stored values.
  64150. */
  64151. set: function (val) {
  64152. this._computeParticleVertex = val;
  64153. },
  64154. enumerable: true,
  64155. configurable: true
  64156. });
  64157. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  64158. /**
  64159. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  64160. */
  64161. get: function () {
  64162. return this._computeBoundingBox;
  64163. },
  64164. /**
  64165. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  64166. */
  64167. set: function (val) {
  64168. this._computeBoundingBox = val;
  64169. },
  64170. enumerable: true,
  64171. configurable: true
  64172. });
  64173. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  64174. /**
  64175. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  64176. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  64177. * Default : `true`
  64178. */
  64179. get: function () {
  64180. return this._depthSortParticles;
  64181. },
  64182. /**
  64183. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  64184. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  64185. * Default : `true`
  64186. */
  64187. set: function (val) {
  64188. this._depthSortParticles = val;
  64189. },
  64190. enumerable: true,
  64191. configurable: true
  64192. });
  64193. // =======================================================================
  64194. // Particle behavior logic
  64195. // these following methods may be overwritten by the user to fit his needs
  64196. /**
  64197. * This function does nothing. It may be overwritten to set all the particle first values.
  64198. * The SPS doesn't call this function, you may have to call it by your own.
  64199. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64200. */
  64201. SolidParticleSystem.prototype.initParticles = function () {
  64202. };
  64203. /**
  64204. * This function does nothing. It may be overwritten to recycle a particle.
  64205. * The SPS doesn't call this function, you may have to call it by your own.
  64206. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64207. * @param particle The particle to recycle
  64208. * @returns the recycled particle
  64209. */
  64210. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  64211. return particle;
  64212. };
  64213. /**
  64214. * Updates a particle : this function should be overwritten by the user.
  64215. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  64216. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64217. * @example : just set a particle position or velocity and recycle conditions
  64218. * @param particle The particle to update
  64219. * @returns the updated particle
  64220. */
  64221. SolidParticleSystem.prototype.updateParticle = function (particle) {
  64222. return particle;
  64223. };
  64224. /**
  64225. * Updates a vertex of a particle : it can be overwritten by the user.
  64226. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  64227. * @param particle the current particle
  64228. * @param vertex the current index of the current particle
  64229. * @param pt the index of the current vertex in the particle shape
  64230. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  64231. * @example : just set a vertex particle position
  64232. * @returns the updated vertex
  64233. */
  64234. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  64235. return vertex;
  64236. };
  64237. /**
  64238. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  64239. * This does nothing and may be overwritten by the user.
  64240. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64241. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64242. * @param update the boolean update value actually passed to setParticles()
  64243. */
  64244. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  64245. };
  64246. /**
  64247. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  64248. * This will be passed three parameters.
  64249. * This does nothing and may be overwritten by the user.
  64250. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64251. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64252. * @param update the boolean update value actually passed to setParticles()
  64253. */
  64254. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  64255. };
  64256. return SolidParticleSystem;
  64257. }());
  64258. BABYLON.SolidParticleSystem = SolidParticleSystem;
  64259. })(BABYLON || (BABYLON = {}));
  64260. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  64261. var BABYLON;
  64262. (function (BABYLON) {
  64263. /**
  64264. * Class containing static functions to help procedurally build meshes
  64265. */
  64266. var MeshBuilder = /** @class */ (function () {
  64267. function MeshBuilder() {
  64268. }
  64269. MeshBuilder.updateSideOrientation = function (orientation) {
  64270. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  64271. return BABYLON.Mesh.DOUBLESIDE;
  64272. }
  64273. if (orientation === undefined || orientation === null) {
  64274. return BABYLON.Mesh.FRONTSIDE;
  64275. }
  64276. return orientation;
  64277. };
  64278. /**
  64279. * Creates a box mesh
  64280. * * The parameter `size` sets the size (float) of each box side (default 1)
  64281. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  64282. * * 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)
  64283. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64284. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64285. * * 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
  64286. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64287. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  64288. * @param name defines the name of the mesh
  64289. * @param options defines the options used to create the mesh
  64290. * @param scene defines the hosting scene
  64291. * @returns the box mesh
  64292. */
  64293. MeshBuilder.CreateBox = function (name, options, scene) {
  64294. if (scene === void 0) { scene = null; }
  64295. var box = new BABYLON.Mesh(name, scene);
  64296. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64297. box._originalBuilderSideOrientation = options.sideOrientation;
  64298. var vertexData = BABYLON.VertexData.CreateBox(options);
  64299. vertexData.applyToMesh(box, options.updatable);
  64300. return box;
  64301. };
  64302. /**
  64303. * Creates a sphere mesh
  64304. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  64305. * * 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`)
  64306. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  64307. * * 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
  64308. * * 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)
  64309. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64310. * * 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
  64311. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64312. * @param name defines the name of the mesh
  64313. * @param options defines the options used to create the mesh
  64314. * @param scene defines the hosting scene
  64315. * @returns the sphere mesh
  64316. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  64317. */
  64318. MeshBuilder.CreateSphere = function (name, options, scene) {
  64319. var sphere = new BABYLON.Mesh(name, scene);
  64320. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64321. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64322. var vertexData = BABYLON.VertexData.CreateSphere(options);
  64323. vertexData.applyToMesh(sphere, options.updatable);
  64324. return sphere;
  64325. };
  64326. /**
  64327. * Creates a plane polygonal mesh. By default, this is a disc
  64328. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  64329. * * 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
  64330. * * 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
  64331. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64332. * * 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
  64333. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64334. * @param name defines the name of the mesh
  64335. * @param options defines the options used to create the mesh
  64336. * @param scene defines the hosting scene
  64337. * @returns the plane polygonal mesh
  64338. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  64339. */
  64340. MeshBuilder.CreateDisc = function (name, options, scene) {
  64341. if (scene === void 0) { scene = null; }
  64342. var disc = new BABYLON.Mesh(name, scene);
  64343. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64344. disc._originalBuilderSideOrientation = options.sideOrientation;
  64345. var vertexData = BABYLON.VertexData.CreateDisc(options);
  64346. vertexData.applyToMesh(disc, options.updatable);
  64347. return disc;
  64348. };
  64349. /**
  64350. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  64351. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  64352. * * 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`)
  64353. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  64354. * * 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
  64355. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64356. * * 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
  64357. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64358. * @param name defines the name of the mesh
  64359. * @param options defines the options used to create the mesh
  64360. * @param scene defines the hosting scene
  64361. * @returns the icosahedron mesh
  64362. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  64363. */
  64364. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  64365. var sphere = new BABYLON.Mesh(name, scene);
  64366. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64367. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64368. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  64369. vertexData.applyToMesh(sphere, options.updatable);
  64370. return sphere;
  64371. };
  64372. ;
  64373. /**
  64374. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64375. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  64376. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  64377. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  64378. * * 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
  64379. * * 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
  64380. * * 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
  64381. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64382. * * 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
  64383. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64384. * * 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
  64385. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  64386. * * 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
  64387. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  64388. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64389. * @param name defines the name of the mesh
  64390. * @param options defines the options used to create the mesh
  64391. * @param scene defines the hosting scene
  64392. * @returns the ribbon mesh
  64393. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  64394. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64395. */
  64396. MeshBuilder.CreateRibbon = function (name, options, scene) {
  64397. if (scene === void 0) { scene = null; }
  64398. var pathArray = options.pathArray;
  64399. var closeArray = options.closeArray;
  64400. var closePath = options.closePath;
  64401. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64402. var instance = options.instance;
  64403. var updatable = options.updatable;
  64404. if (instance) { // existing ribbon instance update
  64405. // positionFunction : ribbon case
  64406. // only pathArray and sideOrientation parameters are taken into account for positions update
  64407. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  64408. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  64409. var positionFunction = function (positions) {
  64410. var minlg = pathArray[0].length;
  64411. var i = 0;
  64412. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  64413. for (var si = 1; si <= ns; si++) {
  64414. for (var p = 0; p < pathArray.length; p++) {
  64415. var path = pathArray[p];
  64416. var l = path.length;
  64417. minlg = (minlg < l) ? minlg : l;
  64418. var j = 0;
  64419. while (j < minlg) {
  64420. positions[i] = path[j].x;
  64421. positions[i + 1] = path[j].y;
  64422. positions[i + 2] = path[j].z;
  64423. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  64424. BABYLON.Tmp.Vector3[0].x = path[j].x;
  64425. }
  64426. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  64427. BABYLON.Tmp.Vector3[1].x = path[j].x;
  64428. }
  64429. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  64430. BABYLON.Tmp.Vector3[0].y = path[j].y;
  64431. }
  64432. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  64433. BABYLON.Tmp.Vector3[1].y = path[j].y;
  64434. }
  64435. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  64436. BABYLON.Tmp.Vector3[0].z = path[j].z;
  64437. }
  64438. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  64439. BABYLON.Tmp.Vector3[1].z = path[j].z;
  64440. }
  64441. j++;
  64442. i += 3;
  64443. }
  64444. if (instance._closePath) {
  64445. positions[i] = path[0].x;
  64446. positions[i + 1] = path[0].y;
  64447. positions[i + 2] = path[0].z;
  64448. i += 3;
  64449. }
  64450. }
  64451. }
  64452. };
  64453. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64454. positionFunction(positions);
  64455. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  64456. instance._boundingInfo.update(instance._worldMatrix);
  64457. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64458. if (options.colors) {
  64459. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64460. for (var c = 0; c < options.colors.length; c++) {
  64461. colors[c * 4] = options.colors[c].r;
  64462. colors[c * 4 + 1] = options.colors[c].g;
  64463. colors[c * 4 + 2] = options.colors[c].b;
  64464. colors[c * 4 + 3] = options.colors[c].a;
  64465. }
  64466. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  64467. }
  64468. if (options.uvs) {
  64469. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64470. for (var i = 0; i < options.uvs.length; i++) {
  64471. uvs[i * 2] = options.uvs[i].x;
  64472. uvs[i * 2 + 1] = options.uvs[i].y;
  64473. }
  64474. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  64475. }
  64476. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  64477. var indices = instance.getIndices();
  64478. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64479. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  64480. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  64481. if (instance._closePath) {
  64482. var indexFirst = 0;
  64483. var indexLast = 0;
  64484. for (var p = 0; p < pathArray.length; p++) {
  64485. indexFirst = instance._idx[p] * 3;
  64486. if (p + 1 < pathArray.length) {
  64487. indexLast = (instance._idx[p + 1] - 1) * 3;
  64488. }
  64489. else {
  64490. indexLast = normals.length - 3;
  64491. }
  64492. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  64493. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  64494. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  64495. normals[indexLast] = normals[indexFirst];
  64496. normals[indexLast + 1] = normals[indexFirst + 1];
  64497. normals[indexLast + 2] = normals[indexFirst + 2];
  64498. }
  64499. }
  64500. if (!(instance.areNormalsFrozen)) {
  64501. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  64502. }
  64503. }
  64504. return instance;
  64505. }
  64506. else { // new ribbon creation
  64507. var ribbon = new BABYLON.Mesh(name, scene);
  64508. ribbon._originalBuilderSideOrientation = sideOrientation;
  64509. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  64510. if (closePath) {
  64511. ribbon._idx = vertexData._idx;
  64512. }
  64513. ribbon._closePath = closePath;
  64514. ribbon._closeArray = closeArray;
  64515. vertexData.applyToMesh(ribbon, updatable);
  64516. return ribbon;
  64517. }
  64518. };
  64519. /**
  64520. * Creates a cylinder or a cone mesh
  64521. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  64522. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  64523. * * 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.
  64524. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  64525. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  64526. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  64527. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  64528. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  64529. * * 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).
  64530. * * 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
  64531. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  64532. * * 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
  64533. * * 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.
  64534. * * If `enclose` is false, a ring surface is one element.
  64535. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  64536. * * 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
  64537. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64538. * * 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
  64539. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64540. * @param name defines the name of the mesh
  64541. * @param options defines the options used to create the mesh
  64542. * @param scene defines the hosting scene
  64543. * @returns the cylinder mesh
  64544. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  64545. */
  64546. MeshBuilder.CreateCylinder = function (name, options, scene) {
  64547. var cylinder = new BABYLON.Mesh(name, scene);
  64548. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64549. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  64550. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  64551. vertexData.applyToMesh(cylinder, options.updatable);
  64552. return cylinder;
  64553. };
  64554. /**
  64555. * Creates a torus mesh
  64556. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  64557. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  64558. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  64559. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64560. * * 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
  64561. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64562. * @param name defines the name of the mesh
  64563. * @param options defines the options used to create the mesh
  64564. * @param scene defines the hosting scene
  64565. * @returns the torus mesh
  64566. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  64567. */
  64568. MeshBuilder.CreateTorus = function (name, options, scene) {
  64569. var torus = new BABYLON.Mesh(name, scene);
  64570. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64571. torus._originalBuilderSideOrientation = options.sideOrientation;
  64572. var vertexData = BABYLON.VertexData.CreateTorus(options);
  64573. vertexData.applyToMesh(torus, options.updatable);
  64574. return torus;
  64575. };
  64576. /**
  64577. * Creates a torus knot mesh
  64578. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  64579. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  64580. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  64581. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  64582. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64583. * * 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
  64584. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64585. * @param name defines the name of the mesh
  64586. * @param options defines the options used to create the mesh
  64587. * @param scene defines the hosting scene
  64588. * @returns the torus knot mesh
  64589. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  64590. */
  64591. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  64592. var torusKnot = new BABYLON.Mesh(name, scene);
  64593. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64594. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  64595. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  64596. vertexData.applyToMesh(torusKnot, options.updatable);
  64597. return torusKnot;
  64598. };
  64599. /**
  64600. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  64601. * * 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
  64602. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  64603. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  64604. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  64605. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  64606. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  64607. * * 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
  64608. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  64609. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64610. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  64611. * @param name defines the name of the new line system
  64612. * @param options defines the options used to create the line system
  64613. * @param scene defines the hosting scene
  64614. * @returns a new line system mesh
  64615. */
  64616. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  64617. var instance = options.instance;
  64618. var lines = options.lines;
  64619. var colors = options.colors;
  64620. if (instance) { // lines update
  64621. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64622. var vertexColor;
  64623. var lineColors;
  64624. if (colors) {
  64625. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64626. }
  64627. var i = 0;
  64628. var c = 0;
  64629. for (var l = 0; l < lines.length; l++) {
  64630. var points = lines[l];
  64631. for (var p = 0; p < points.length; p++) {
  64632. positions[i] = points[p].x;
  64633. positions[i + 1] = points[p].y;
  64634. positions[i + 2] = points[p].z;
  64635. if (colors && vertexColor) {
  64636. lineColors = colors[l];
  64637. vertexColor[c] = lineColors[p].r;
  64638. vertexColor[c + 1] = lineColors[p].g;
  64639. vertexColor[c + 2] = lineColors[p].b;
  64640. vertexColor[c + 3] = lineColors[p].a;
  64641. c += 4;
  64642. }
  64643. i += 3;
  64644. }
  64645. }
  64646. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64647. if (colors && vertexColor) {
  64648. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  64649. }
  64650. return instance;
  64651. }
  64652. // line system creation
  64653. var useVertexColor = (colors) ? true : false;
  64654. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  64655. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  64656. vertexData.applyToMesh(lineSystem, options.updatable);
  64657. return lineSystem;
  64658. };
  64659. /**
  64660. * Creates a line mesh
  64661. * 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
  64662. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64663. * * The parameter `points` is an array successive Vector3
  64664. * * 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
  64665. * * The optional parameter `colors` is an array of successive Color4, one per line point
  64666. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  64667. * * When updating an instance, remember that only point positions can change, not the number of points
  64668. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64669. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  64670. * @param name defines the name of the new line system
  64671. * @param options defines the options used to create the line system
  64672. * @param scene defines the hosting scene
  64673. * @returns a new line mesh
  64674. */
  64675. MeshBuilder.CreateLines = function (name, options, scene) {
  64676. if (scene === void 0) { scene = null; }
  64677. var colors = (options.colors) ? [options.colors] : null;
  64678. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  64679. return lines;
  64680. };
  64681. /**
  64682. * Creates a dashed line mesh
  64683. * * 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
  64684. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64685. * * The parameter `points` is an array successive Vector3
  64686. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  64687. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  64688. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  64689. * * 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
  64690. * * When updating an instance, remember that only point positions can change, not the number of points
  64691. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64692. * @param name defines the name of the mesh
  64693. * @param options defines the options used to create the mesh
  64694. * @param scene defines the hosting scene
  64695. * @returns the dashed line mesh
  64696. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  64697. */
  64698. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  64699. if (scene === void 0) { scene = null; }
  64700. var points = options.points;
  64701. var instance = options.instance;
  64702. var gapSize = options.gapSize || 1;
  64703. var dashSize = options.dashSize || 3;
  64704. if (instance) { // dashed lines update
  64705. var positionFunction = function (positions) {
  64706. var curvect = BABYLON.Vector3.Zero();
  64707. var nbSeg = positions.length / 6;
  64708. var lg = 0;
  64709. var nb = 0;
  64710. var shft = 0;
  64711. var dashshft = 0;
  64712. var curshft = 0;
  64713. var p = 0;
  64714. var i = 0;
  64715. var j = 0;
  64716. for (i = 0; i < points.length - 1; i++) {
  64717. points[i + 1].subtractToRef(points[i], curvect);
  64718. lg += curvect.length();
  64719. }
  64720. shft = lg / nbSeg;
  64721. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  64722. for (i = 0; i < points.length - 1; i++) {
  64723. points[i + 1].subtractToRef(points[i], curvect);
  64724. nb = Math.floor(curvect.length() / shft);
  64725. curvect.normalize();
  64726. j = 0;
  64727. while (j < nb && p < positions.length) {
  64728. curshft = shft * j;
  64729. positions[p] = points[i].x + curshft * curvect.x;
  64730. positions[p + 1] = points[i].y + curshft * curvect.y;
  64731. positions[p + 2] = points[i].z + curshft * curvect.z;
  64732. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  64733. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  64734. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  64735. p += 6;
  64736. j++;
  64737. }
  64738. }
  64739. while (p < positions.length) {
  64740. positions[p] = points[i].x;
  64741. positions[p + 1] = points[i].y;
  64742. positions[p + 2] = points[i].z;
  64743. p += 3;
  64744. }
  64745. };
  64746. instance.updateMeshPositions(positionFunction, false);
  64747. return instance;
  64748. }
  64749. // dashed lines creation
  64750. var dashedLines = new BABYLON.LinesMesh(name, scene);
  64751. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  64752. vertexData.applyToMesh(dashedLines, options.updatable);
  64753. dashedLines.dashSize = dashSize;
  64754. dashedLines.gapSize = gapSize;
  64755. return dashedLines;
  64756. };
  64757. /**
  64758. * 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.
  64759. * * 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.
  64760. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64761. * * 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.
  64762. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  64763. * * 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
  64764. * * 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
  64765. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  64766. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64767. * * 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
  64768. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  64769. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64770. * @param name defines the name of the mesh
  64771. * @param options defines the options used to create the mesh
  64772. * @param scene defines the hosting scene
  64773. * @returns the extruded shape mesh
  64774. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64775. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64776. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64777. */
  64778. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  64779. if (scene === void 0) { scene = null; }
  64780. var path = options.path;
  64781. var shape = options.shape;
  64782. var scale = options.scale || 1;
  64783. var rotation = options.rotation || 0;
  64784. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64785. var updatable = options.updatable;
  64786. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64787. var instance = options.instance || null;
  64788. var invertUV = options.invertUV || false;
  64789. 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);
  64790. };
  64791. /**
  64792. * Creates an custom extruded shape mesh.
  64793. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  64794. * * 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.
  64795. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64796. * * 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
  64797. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  64798. * * 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
  64799. * * It must returns a float value that will be the scale value applied to the shape on each path point
  64800. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  64801. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  64802. * * 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
  64803. * * 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
  64804. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  64805. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64806. * * 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
  64807. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64808. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64809. * @param name defines the name of the mesh
  64810. * @param options defines the options used to create the mesh
  64811. * @param scene defines the hosting scene
  64812. * @returns the custom extruded shape mesh
  64813. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  64814. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64815. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64816. */
  64817. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  64818. var path = options.path;
  64819. var shape = options.shape;
  64820. var scaleFunction = options.scaleFunction || (function () { return 1; });
  64821. var rotationFunction = options.rotationFunction || (function () { return 0; });
  64822. var ribbonCloseArray = options.ribbonCloseArray || false;
  64823. var ribbonClosePath = options.ribbonClosePath || false;
  64824. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64825. var updatable = options.updatable;
  64826. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64827. var instance = options.instance;
  64828. var invertUV = options.invertUV || false;
  64829. 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);
  64830. };
  64831. /**
  64832. * Creates lathe mesh.
  64833. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  64834. * * 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
  64835. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  64836. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  64837. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  64838. * * 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
  64839. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  64840. * * 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
  64841. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64842. * * 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
  64843. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64844. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64845. * @param name defines the name of the mesh
  64846. * @param options defines the options used to create the mesh
  64847. * @param scene defines the hosting scene
  64848. * @returns the lathe mesh
  64849. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  64850. */
  64851. MeshBuilder.CreateLathe = function (name, options, scene) {
  64852. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  64853. var closed = (options.closed === undefined) ? true : options.closed;
  64854. var shape = options.shape;
  64855. var radius = options.radius || 1;
  64856. var tessellation = options.tessellation || 64;
  64857. var clip = options.clip || 0;
  64858. var updatable = options.updatable;
  64859. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64860. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64861. var pi2 = Math.PI * 2;
  64862. var paths = new Array();
  64863. var invertUV = options.invertUV || false;
  64864. var i = 0;
  64865. var p = 0;
  64866. var step = pi2 / tessellation * arc;
  64867. var rotated;
  64868. var path = new Array();
  64869. for (i = 0; i <= tessellation - clip; i++) {
  64870. var path = [];
  64871. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  64872. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  64873. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  64874. }
  64875. for (p = 0; p < shape.length; p++) {
  64876. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  64877. path.push(rotated);
  64878. }
  64879. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  64880. 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));
  64881. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  64882. }
  64883. paths.push(path);
  64884. }
  64885. // lathe ribbon
  64886. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64887. return lathe;
  64888. };
  64889. /**
  64890. * Creates a plane mesh
  64891. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  64892. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  64893. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  64894. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64895. * * 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
  64896. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64897. * @param name defines the name of the mesh
  64898. * @param options defines the options used to create the mesh
  64899. * @param scene defines the hosting scene
  64900. * @returns the plane mesh
  64901. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64902. */
  64903. MeshBuilder.CreatePlane = function (name, options, scene) {
  64904. var plane = new BABYLON.Mesh(name, scene);
  64905. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64906. plane._originalBuilderSideOrientation = options.sideOrientation;
  64907. var vertexData = BABYLON.VertexData.CreatePlane(options);
  64908. vertexData.applyToMesh(plane, options.updatable);
  64909. if (options.sourcePlane) {
  64910. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  64911. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  64912. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  64913. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  64914. plane.rotate(vectorProduct, product);
  64915. }
  64916. }
  64917. return plane;
  64918. };
  64919. /**
  64920. * Creates a ground mesh
  64921. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  64922. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  64923. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64924. * @param name defines the name of the mesh
  64925. * @param options defines the options used to create the mesh
  64926. * @param scene defines the hosting scene
  64927. * @returns the ground mesh
  64928. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64929. */
  64930. MeshBuilder.CreateGround = function (name, options, scene) {
  64931. var ground = new BABYLON.GroundMesh(name, scene);
  64932. ground._setReady(false);
  64933. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  64934. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  64935. ground._width = options.width || 1;
  64936. ground._height = options.height || 1;
  64937. ground._maxX = ground._width / 2;
  64938. ground._maxZ = ground._height / 2;
  64939. ground._minX = -ground._maxX;
  64940. ground._minZ = -ground._maxZ;
  64941. var vertexData = BABYLON.VertexData.CreateGround(options);
  64942. vertexData.applyToMesh(ground, options.updatable);
  64943. ground._setReady(true);
  64944. return ground;
  64945. };
  64946. /**
  64947. * Creates a tiled ground mesh
  64948. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  64949. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  64950. * * 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
  64951. * * 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
  64952. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64953. * @param name defines the name of the mesh
  64954. * @param options defines the options used to create the mesh
  64955. * @param scene defines the hosting scene
  64956. * @returns the tiled ground mesh
  64957. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  64958. */
  64959. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  64960. var tiledGround = new BABYLON.Mesh(name, scene);
  64961. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  64962. vertexData.applyToMesh(tiledGround, options.updatable);
  64963. return tiledGround;
  64964. };
  64965. /**
  64966. * Creates a ground mesh from a height map
  64967. * * The parameter `url` sets the URL of the height map image resource.
  64968. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  64969. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  64970. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  64971. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  64972. * * 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.
  64973. * * 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).
  64974. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  64975. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64976. * @param name defines the name of the mesh
  64977. * @param url defines the url to the height map
  64978. * @param options defines the options used to create the mesh
  64979. * @param scene defines the hosting scene
  64980. * @returns the ground mesh
  64981. * @see http://doc.babylonjs.com/babylon101/height_map
  64982. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  64983. */
  64984. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  64985. var width = options.width || 10.0;
  64986. var height = options.height || 10.0;
  64987. var subdivisions = options.subdivisions || 1 | 0;
  64988. var minHeight = options.minHeight || 0.0;
  64989. var maxHeight = options.maxHeight || 1.0;
  64990. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  64991. var alphaFilter = options.alphaFilter || 0.0;
  64992. var updatable = options.updatable;
  64993. var onReady = options.onReady;
  64994. var ground = new BABYLON.GroundMesh(name, scene);
  64995. ground._subdivisionsX = subdivisions;
  64996. ground._subdivisionsY = subdivisions;
  64997. ground._width = width;
  64998. ground._height = height;
  64999. ground._maxX = ground._width / 2.0;
  65000. ground._maxZ = ground._height / 2.0;
  65001. ground._minX = -ground._maxX;
  65002. ground._minZ = -ground._maxZ;
  65003. ground._setReady(false);
  65004. var onload = function (img) {
  65005. // Getting height map data
  65006. var canvas = document.createElement("canvas");
  65007. var context = canvas.getContext("2d");
  65008. if (!context) {
  65009. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  65010. }
  65011. if (scene.isDisposed) {
  65012. return;
  65013. }
  65014. var bufferWidth = img.width;
  65015. var bufferHeight = img.height;
  65016. canvas.width = bufferWidth;
  65017. canvas.height = bufferHeight;
  65018. context.drawImage(img, 0, 0);
  65019. // Create VertexData from map data
  65020. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  65021. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  65022. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  65023. width: width, height: height,
  65024. subdivisions: subdivisions,
  65025. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  65026. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  65027. alphaFilter: alphaFilter
  65028. });
  65029. vertexData.applyToMesh(ground, updatable);
  65030. //execute ready callback, if set
  65031. if (onReady) {
  65032. onReady(ground);
  65033. }
  65034. ground._setReady(true);
  65035. };
  65036. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  65037. return ground;
  65038. };
  65039. /**
  65040. * Creates a polygon mesh
  65041. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  65042. * * 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
  65043. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65044. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65045. * * 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)
  65046. * * Remember you can only change the shape positions, not their number when updating a polygon
  65047. * @param name defines the name of the mesh
  65048. * @param options defines the options used to create the mesh
  65049. * @param scene defines the hosting scene
  65050. * @returns the polygon mesh
  65051. */
  65052. MeshBuilder.CreatePolygon = function (name, options, scene) {
  65053. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65054. var shape = options.shape;
  65055. var holes = options.holes || [];
  65056. var depth = options.depth || 0;
  65057. var contours = [];
  65058. var hole = [];
  65059. for (var i = 0; i < shape.length; i++) {
  65060. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  65061. }
  65062. var epsilon = 0.00000001;
  65063. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  65064. contours.pop();
  65065. }
  65066. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  65067. for (var hNb = 0; hNb < holes.length; hNb++) {
  65068. hole = [];
  65069. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  65070. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  65071. }
  65072. polygonTriangulation.addHole(hole);
  65073. }
  65074. var polygon = polygonTriangulation.build(options.updatable, depth);
  65075. polygon._originalBuilderSideOrientation = options.sideOrientation;
  65076. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  65077. vertexData.applyToMesh(polygon, options.updatable);
  65078. return polygon;
  65079. };
  65080. ;
  65081. /**
  65082. * Creates an extruded polygon mesh, with depth in the Y direction.
  65083. * * 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)
  65084. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  65085. * @param name defines the name of the mesh
  65086. * @param options defines the options used to create the mesh
  65087. * @param scene defines the hosting scene
  65088. * @returns the polygon mesh
  65089. */
  65090. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  65091. return MeshBuilder.CreatePolygon(name, options, scene);
  65092. };
  65093. ;
  65094. /**
  65095. * Creates a tube mesh.
  65096. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  65097. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  65098. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  65099. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  65100. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  65101. * * 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)
  65102. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  65103. * * 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
  65104. * * 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
  65105. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65106. * * 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
  65107. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65108. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65109. * @param name defines the name of the mesh
  65110. * @param options defines the options used to create the mesh
  65111. * @param scene defines the hosting scene
  65112. * @returns the tube mesh
  65113. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65114. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  65115. */
  65116. MeshBuilder.CreateTube = function (name, options, scene) {
  65117. var path = options.path;
  65118. var instance = options.instance;
  65119. var radius = 1.0;
  65120. if (instance) {
  65121. radius = instance.radius;
  65122. }
  65123. if (options.radius !== undefined) {
  65124. radius = options.radius;
  65125. }
  65126. ;
  65127. var tessellation = options.tessellation || 64 | 0;
  65128. var radiusFunction = options.radiusFunction || null;
  65129. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  65130. var invertUV = options.invertUV || false;
  65131. var updatable = options.updatable;
  65132. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65133. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  65134. // tube geometry
  65135. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  65136. var tangents = path3D.getTangents();
  65137. var normals = path3D.getNormals();
  65138. var distances = path3D.getDistances();
  65139. var pi2 = Math.PI * 2;
  65140. var step = pi2 / tessellation * arc;
  65141. var returnRadius = function () { return radius; };
  65142. var radiusFunctionFinal = radiusFunction || returnRadius;
  65143. var circlePath;
  65144. var rad;
  65145. var normal;
  65146. var rotated;
  65147. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  65148. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  65149. for (var i = 0; i < path.length; i++) {
  65150. rad = radiusFunctionFinal(i, distances[i]); // current radius
  65151. circlePath = Array(); // current circle array
  65152. normal = normals[i]; // current normal
  65153. for (var t = 0; t < tessellation; t++) {
  65154. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  65155. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  65156. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  65157. rotated.scaleInPlace(rad).addInPlace(path[i]);
  65158. circlePath[t] = rotated;
  65159. }
  65160. circlePaths[index] = circlePath;
  65161. index++;
  65162. }
  65163. // cap
  65164. var capPath = function (nbPoints, pathIndex) {
  65165. var pointCap = Array();
  65166. for (var i = 0; i < nbPoints; i++) {
  65167. pointCap.push(path[pathIndex]);
  65168. }
  65169. return pointCap;
  65170. };
  65171. switch (cap) {
  65172. case BABYLON.Mesh.NO_CAP:
  65173. break;
  65174. case BABYLON.Mesh.CAP_START:
  65175. circlePaths[0] = capPath(tessellation, 0);
  65176. circlePaths[1] = circlePaths[2].slice(0);
  65177. break;
  65178. case BABYLON.Mesh.CAP_END:
  65179. circlePaths[index] = circlePaths[index - 1].slice(0);
  65180. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  65181. break;
  65182. case BABYLON.Mesh.CAP_ALL:
  65183. circlePaths[0] = capPath(tessellation, 0);
  65184. circlePaths[1] = circlePaths[2].slice(0);
  65185. circlePaths[index] = circlePaths[index - 1].slice(0);
  65186. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  65187. break;
  65188. default:
  65189. break;
  65190. }
  65191. return circlePaths;
  65192. };
  65193. var path3D;
  65194. var pathArray;
  65195. if (instance) { // tube update
  65196. var arc = options.arc || instance.arc;
  65197. path3D = (instance.path3D).update(path);
  65198. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  65199. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  65200. instance.path3D = path3D;
  65201. instance.pathArray = pathArray;
  65202. instance.arc = arc;
  65203. instance.radius = radius;
  65204. return instance;
  65205. }
  65206. // tube creation
  65207. path3D = new BABYLON.Path3D(path);
  65208. var newPathArray = new Array();
  65209. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65210. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  65211. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  65212. tube.pathArray = pathArray;
  65213. tube.path3D = path3D;
  65214. tube.tessellation = tessellation;
  65215. tube.cap = cap;
  65216. tube.arc = options.arc;
  65217. tube.radius = radius;
  65218. return tube;
  65219. };
  65220. /**
  65221. * Creates a polyhedron mesh
  65222. * * 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
  65223. * * The parameter `size` (positive float, default 1) sets the polygon size
  65224. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  65225. * * 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`
  65226. * * 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
  65227. * * 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)`)
  65228. * * 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
  65229. * * 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
  65230. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65231. * * 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
  65232. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65233. * @param name defines the name of the mesh
  65234. * @param options defines the options used to create the mesh
  65235. * @param scene defines the hosting scene
  65236. * @returns the polyhedron mesh
  65237. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  65238. */
  65239. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  65240. var polyhedron = new BABYLON.Mesh(name, scene);
  65241. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65242. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  65243. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  65244. vertexData.applyToMesh(polyhedron, options.updatable);
  65245. return polyhedron;
  65246. };
  65247. /**
  65248. * Creates a decal mesh.
  65249. * 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
  65250. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  65251. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  65252. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  65253. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  65254. * @param name defines the name of the mesh
  65255. * @param sourceMesh defines the mesh where the decal must be applied
  65256. * @param options defines the options used to create the mesh
  65257. * @param scene defines the hosting scene
  65258. * @returns the decal mesh
  65259. * @see http://doc.babylonjs.com/how_to/decals
  65260. */
  65261. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  65262. var indices = sourceMesh.getIndices();
  65263. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65264. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65265. var position = options.position || BABYLON.Vector3.Zero();
  65266. var normal = options.normal || BABYLON.Vector3.Up();
  65267. var size = options.size || BABYLON.Vector3.One();
  65268. var angle = options.angle || 0;
  65269. // Getting correct rotation
  65270. if (!normal) {
  65271. var target = new BABYLON.Vector3(0, 0, 1);
  65272. var camera = sourceMesh.getScene().activeCamera;
  65273. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  65274. normal = camera.globalPosition.subtract(cameraWorldTarget);
  65275. }
  65276. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  65277. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  65278. var pitch = Math.atan2(normal.y, len);
  65279. // Matrix
  65280. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  65281. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  65282. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  65283. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  65284. var vertexData = new BABYLON.VertexData();
  65285. vertexData.indices = [];
  65286. vertexData.positions = [];
  65287. vertexData.normals = [];
  65288. vertexData.uvs = [];
  65289. var currentVertexDataIndex = 0;
  65290. var extractDecalVector3 = function (indexId) {
  65291. var result = new BABYLON.PositionNormalVertex();
  65292. if (!indices || !positions || !normals) {
  65293. return result;
  65294. }
  65295. var vertexId = indices[indexId];
  65296. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  65297. // Send vector to decal local world
  65298. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  65299. // Get normal
  65300. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  65301. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  65302. return result;
  65303. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  65304. var clip = function (vertices, axis) {
  65305. if (vertices.length === 0) {
  65306. return vertices;
  65307. }
  65308. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  65309. var clipVertices = function (v0, v1) {
  65310. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  65311. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  65312. };
  65313. var result = new Array();
  65314. for (var index = 0; index < vertices.length; index += 3) {
  65315. var v1Out;
  65316. var v2Out;
  65317. var v3Out;
  65318. var total = 0;
  65319. var nV1 = null;
  65320. var nV2 = null;
  65321. var nV3 = null;
  65322. var nV4 = null;
  65323. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  65324. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  65325. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  65326. v1Out = d1 > 0;
  65327. v2Out = d2 > 0;
  65328. v3Out = d3 > 0;
  65329. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  65330. switch (total) {
  65331. case 0:
  65332. result.push(vertices[index]);
  65333. result.push(vertices[index + 1]);
  65334. result.push(vertices[index + 2]);
  65335. break;
  65336. case 1:
  65337. if (v1Out) {
  65338. nV1 = vertices[index + 1];
  65339. nV2 = vertices[index + 2];
  65340. nV3 = clipVertices(vertices[index], nV1);
  65341. nV4 = clipVertices(vertices[index], nV2);
  65342. }
  65343. if (v2Out) {
  65344. nV1 = vertices[index];
  65345. nV2 = vertices[index + 2];
  65346. nV3 = clipVertices(vertices[index + 1], nV1);
  65347. nV4 = clipVertices(vertices[index + 1], nV2);
  65348. result.push(nV3);
  65349. result.push(nV2.clone());
  65350. result.push(nV1.clone());
  65351. result.push(nV2.clone());
  65352. result.push(nV3.clone());
  65353. result.push(nV4);
  65354. break;
  65355. }
  65356. if (v3Out) {
  65357. nV1 = vertices[index];
  65358. nV2 = vertices[index + 1];
  65359. nV3 = clipVertices(vertices[index + 2], nV1);
  65360. nV4 = clipVertices(vertices[index + 2], nV2);
  65361. }
  65362. if (nV1 && nV2 && nV3 && nV4) {
  65363. result.push(nV1.clone());
  65364. result.push(nV2.clone());
  65365. result.push(nV3);
  65366. result.push(nV4);
  65367. result.push(nV3.clone());
  65368. result.push(nV2.clone());
  65369. }
  65370. break;
  65371. case 2:
  65372. if (!v1Out) {
  65373. nV1 = vertices[index].clone();
  65374. nV2 = clipVertices(nV1, vertices[index + 1]);
  65375. nV3 = clipVertices(nV1, vertices[index + 2]);
  65376. result.push(nV1);
  65377. result.push(nV2);
  65378. result.push(nV3);
  65379. }
  65380. if (!v2Out) {
  65381. nV1 = vertices[index + 1].clone();
  65382. nV2 = clipVertices(nV1, vertices[index + 2]);
  65383. nV3 = clipVertices(nV1, vertices[index]);
  65384. result.push(nV1);
  65385. result.push(nV2);
  65386. result.push(nV3);
  65387. }
  65388. if (!v3Out) {
  65389. nV1 = vertices[index + 2].clone();
  65390. nV2 = clipVertices(nV1, vertices[index]);
  65391. nV3 = clipVertices(nV1, vertices[index + 1]);
  65392. result.push(nV1);
  65393. result.push(nV2);
  65394. result.push(nV3);
  65395. }
  65396. break;
  65397. case 3:
  65398. break;
  65399. }
  65400. }
  65401. return result;
  65402. };
  65403. for (var index = 0; index < indices.length; index += 3) {
  65404. var faceVertices = new Array();
  65405. faceVertices.push(extractDecalVector3(index));
  65406. faceVertices.push(extractDecalVector3(index + 1));
  65407. faceVertices.push(extractDecalVector3(index + 2));
  65408. // Clip
  65409. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  65410. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  65411. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  65412. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  65413. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  65414. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  65415. if (faceVertices.length === 0) {
  65416. continue;
  65417. }
  65418. // Add UVs and get back to world
  65419. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  65420. var vertex = faceVertices[vIndex];
  65421. //TODO check for Int32Array | Uint32Array | Uint16Array
  65422. vertexData.indices.push(currentVertexDataIndex);
  65423. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  65424. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  65425. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  65426. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  65427. currentVertexDataIndex++;
  65428. }
  65429. }
  65430. // Return mesh
  65431. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  65432. vertexData.applyToMesh(decal);
  65433. decal.position = position.clone();
  65434. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  65435. return decal;
  65436. };
  65437. // Privates
  65438. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  65439. // extrusion geometry
  65440. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  65441. var tangents = path3D.getTangents();
  65442. var normals = path3D.getNormals();
  65443. var binormals = path3D.getBinormals();
  65444. var distances = path3D.getDistances();
  65445. var angle = 0;
  65446. var returnScale = function () { return scale !== null ? scale : 1; };
  65447. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  65448. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  65449. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  65450. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  65451. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  65452. for (var i = 0; i < curve.length; i++) {
  65453. var shapePath = new Array();
  65454. var angleStep = rotate(i, distances[i]);
  65455. var scaleRatio = scl(i, distances[i]);
  65456. for (var p = 0; p < shape.length; p++) {
  65457. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  65458. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  65459. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  65460. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  65461. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  65462. shapePath[p] = rotated;
  65463. }
  65464. shapePaths[index] = shapePath;
  65465. angle += angleStep;
  65466. index++;
  65467. }
  65468. // cap
  65469. var capPath = function (shapePath) {
  65470. var pointCap = Array();
  65471. var barycenter = BABYLON.Vector3.Zero();
  65472. var i;
  65473. for (i = 0; i < shapePath.length; i++) {
  65474. barycenter.addInPlace(shapePath[i]);
  65475. }
  65476. barycenter.scaleInPlace(1.0 / shapePath.length);
  65477. for (i = 0; i < shapePath.length; i++) {
  65478. pointCap.push(barycenter);
  65479. }
  65480. return pointCap;
  65481. };
  65482. switch (cap) {
  65483. case BABYLON.Mesh.NO_CAP:
  65484. break;
  65485. case BABYLON.Mesh.CAP_START:
  65486. shapePaths[0] = capPath(shapePaths[2]);
  65487. shapePaths[1] = shapePaths[2];
  65488. break;
  65489. case BABYLON.Mesh.CAP_END:
  65490. shapePaths[index] = shapePaths[index - 1];
  65491. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65492. break;
  65493. case BABYLON.Mesh.CAP_ALL:
  65494. shapePaths[0] = capPath(shapePaths[2]);
  65495. shapePaths[1] = shapePaths[2];
  65496. shapePaths[index] = shapePaths[index - 1];
  65497. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65498. break;
  65499. default:
  65500. break;
  65501. }
  65502. return shapePaths;
  65503. };
  65504. var path3D;
  65505. var pathArray;
  65506. if (instance) { // instance update
  65507. path3D = (instance.path3D).update(curve);
  65508. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  65509. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  65510. return instance;
  65511. }
  65512. // extruded shape creation
  65513. path3D = new BABYLON.Path3D(curve);
  65514. var newShapePaths = new Array();
  65515. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65516. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  65517. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  65518. extrudedGeneric.pathArray = pathArray;
  65519. extrudedGeneric.path3D = path3D;
  65520. extrudedGeneric.cap = cap;
  65521. return extrudedGeneric;
  65522. };
  65523. return MeshBuilder;
  65524. }());
  65525. BABYLON.MeshBuilder = MeshBuilder;
  65526. })(BABYLON || (BABYLON = {}));
  65527. //# sourceMappingURL=babylon.meshBuilder.js.map
  65528. var BABYLON;
  65529. (function (BABYLON) {
  65530. /**
  65531. * Draco compression (https://google.github.io/draco/)
  65532. *
  65533. * This class wraps the Draco module.
  65534. *
  65535. * **Encoder**
  65536. *
  65537. * The encoder is not currently implemented.
  65538. *
  65539. * **Decoder**
  65540. *
  65541. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  65542. *
  65543. * To update the configuration, use the following code:
  65544. * ```javascript
  65545. * BABYLON.DracoCompression.Configuration = {
  65546. * decoder: {
  65547. * wasmUrl: "<url to the WebAssembly library>",
  65548. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  65549. * fallbackUrl: "<url to the fallback JavaScript library>",
  65550. * }
  65551. * };
  65552. * ```
  65553. *
  65554. * 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.
  65555. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  65556. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  65557. *
  65558. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  65559. * ```javascript
  65560. * var dracoCompression = new BABYLON.DracoCompression();
  65561. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  65562. * [BABYLON.VertexBuffer.PositionKind]: 0
  65563. * });
  65564. * ```
  65565. *
  65566. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  65567. */
  65568. var DracoCompression = /** @class */ (function () {
  65569. /**
  65570. * Constructor
  65571. */
  65572. function DracoCompression() {
  65573. }
  65574. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  65575. /**
  65576. * Returns true if the decoder is available.
  65577. */
  65578. get: function () {
  65579. if (typeof DracoDecoderModule !== "undefined") {
  65580. return true;
  65581. }
  65582. var decoder = DracoCompression.Configuration.decoder;
  65583. if (decoder) {
  65584. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65585. return true;
  65586. }
  65587. if (decoder.fallbackUrl) {
  65588. return true;
  65589. }
  65590. }
  65591. return false;
  65592. },
  65593. enumerable: true,
  65594. configurable: true
  65595. });
  65596. /**
  65597. * Stop all async operations and release resources.
  65598. */
  65599. DracoCompression.prototype.dispose = function () {
  65600. };
  65601. /**
  65602. * Decode Draco compressed mesh data to vertex data.
  65603. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  65604. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  65605. * @returns A promise that resolves with the decoded vertex data
  65606. */
  65607. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  65608. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  65609. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  65610. var module = wrappedModule.module;
  65611. var vertexData = new BABYLON.VertexData();
  65612. var buffer = new module.DecoderBuffer();
  65613. buffer.Init(dataView, dataView.byteLength);
  65614. var decoder = new module.Decoder();
  65615. var geometry;
  65616. var status;
  65617. try {
  65618. var type = decoder.GetEncodedGeometryType(buffer);
  65619. switch (type) {
  65620. case module.TRIANGULAR_MESH:
  65621. geometry = new module.Mesh();
  65622. status = decoder.DecodeBufferToMesh(buffer, geometry);
  65623. break;
  65624. case module.POINT_CLOUD:
  65625. geometry = new module.PointCloud();
  65626. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  65627. break;
  65628. default:
  65629. throw new Error("Invalid geometry type " + type);
  65630. }
  65631. if (!status.ok() || !geometry.ptr) {
  65632. throw new Error(status.error_msg());
  65633. }
  65634. var numPoints = geometry.num_points();
  65635. if (type === module.TRIANGULAR_MESH) {
  65636. var numFaces = geometry.num_faces();
  65637. var faceIndices = new module.DracoInt32Array();
  65638. try {
  65639. var indices = new Uint32Array(numFaces * 3);
  65640. for (var i = 0; i < numFaces; i++) {
  65641. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  65642. var offset = i * 3;
  65643. indices[offset + 0] = faceIndices.GetValue(0);
  65644. indices[offset + 1] = faceIndices.GetValue(1);
  65645. indices[offset + 2] = faceIndices.GetValue(2);
  65646. }
  65647. vertexData.indices = indices;
  65648. }
  65649. finally {
  65650. module.destroy(faceIndices);
  65651. }
  65652. }
  65653. for (var kind in attributes) {
  65654. var uniqueId = attributes[kind];
  65655. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  65656. var dracoData = new module.DracoFloat32Array();
  65657. try {
  65658. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  65659. var babylonData = new Float32Array(numPoints * attribute.num_components());
  65660. for (var i = 0; i < babylonData.length; i++) {
  65661. babylonData[i] = dracoData.GetValue(i);
  65662. }
  65663. vertexData.set(babylonData, kind);
  65664. }
  65665. finally {
  65666. module.destroy(dracoData);
  65667. }
  65668. }
  65669. }
  65670. finally {
  65671. if (geometry) {
  65672. module.destroy(geometry);
  65673. }
  65674. module.destroy(decoder);
  65675. module.destroy(buffer);
  65676. }
  65677. return vertexData;
  65678. });
  65679. };
  65680. DracoCompression._GetDecoderModule = function () {
  65681. if (!DracoCompression._DecoderModulePromise) {
  65682. var promise = null;
  65683. var config_1 = {};
  65684. if (typeof DracoDecoderModule !== "undefined") {
  65685. promise = Promise.resolve();
  65686. }
  65687. else {
  65688. var decoder = DracoCompression.Configuration.decoder;
  65689. if (decoder) {
  65690. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65691. promise = Promise.all([
  65692. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  65693. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  65694. config_1.wasmBinary = data;
  65695. })
  65696. ]);
  65697. }
  65698. else if (decoder.fallbackUrl) {
  65699. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  65700. }
  65701. }
  65702. }
  65703. if (!promise) {
  65704. throw new Error("Draco decoder module is not available");
  65705. }
  65706. DracoCompression._DecoderModulePromise = promise.then(function () {
  65707. return new Promise(function (resolve) {
  65708. config_1.onModuleLoaded = function (decoderModule) {
  65709. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  65710. resolve({ module: decoderModule });
  65711. };
  65712. DracoDecoderModule(config_1);
  65713. });
  65714. });
  65715. }
  65716. return DracoCompression._DecoderModulePromise;
  65717. };
  65718. DracoCompression._LoadScriptAsync = function (url) {
  65719. return new Promise(function (resolve, reject) {
  65720. BABYLON.Tools.LoadScript(url, function () {
  65721. resolve();
  65722. }, function (message) {
  65723. reject(new Error(message));
  65724. });
  65725. });
  65726. };
  65727. DracoCompression._LoadFileAsync = function (url) {
  65728. return new Promise(function (resolve, reject) {
  65729. BABYLON.Tools.LoadFile(url, function (data) {
  65730. resolve(data);
  65731. }, undefined, undefined, true, function (request, exception) {
  65732. reject(exception);
  65733. });
  65734. });
  65735. };
  65736. /**
  65737. * The configuration. Defaults to the following urls:
  65738. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  65739. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  65740. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65741. */
  65742. DracoCompression.Configuration = {
  65743. decoder: {
  65744. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  65745. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  65746. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65747. }
  65748. };
  65749. return DracoCompression;
  65750. }());
  65751. BABYLON.DracoCompression = DracoCompression;
  65752. })(BABYLON || (BABYLON = {}));
  65753. //# sourceMappingURL=babylon.dracoCompression.js.map
  65754. var BABYLON;
  65755. (function (BABYLON) {
  65756. // Sets the default audio engine to Babylon JS.
  65757. BABYLON.Engine.AudioEngineFactory = function () { return new AudioEngine(); };
  65758. var AudioEngine = /** @class */ (function () {
  65759. function AudioEngine() {
  65760. this._audioContext = null;
  65761. this._audioContextInitialized = false;
  65762. this.canUseWebAudio = false;
  65763. this.WarnedWebAudioUnsupported = false;
  65764. this.unlocked = false;
  65765. this.isMP3supported = false;
  65766. this.isOGGsupported = false;
  65767. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  65768. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  65769. this.canUseWebAudio = true;
  65770. }
  65771. var audioElem = document.createElement('audio');
  65772. try {
  65773. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  65774. this.isMP3supported = true;
  65775. }
  65776. }
  65777. catch (e) {
  65778. // protect error during capability check.
  65779. }
  65780. try {
  65781. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  65782. this.isOGGsupported = true;
  65783. }
  65784. }
  65785. catch (e) {
  65786. // protect error during capability check.
  65787. }
  65788. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  65789. this._unlockiOSaudio();
  65790. }
  65791. else {
  65792. this.unlocked = true;
  65793. }
  65794. }
  65795. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  65796. get: function () {
  65797. if (!this._audioContextInitialized) {
  65798. this._initializeAudioContext();
  65799. }
  65800. return this._audioContext;
  65801. },
  65802. enumerable: true,
  65803. configurable: true
  65804. });
  65805. AudioEngine.prototype._unlockiOSaudio = function () {
  65806. var _this = this;
  65807. var unlockaudio = function () {
  65808. if (!_this.audioContext) {
  65809. return;
  65810. }
  65811. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  65812. var source = _this.audioContext.createBufferSource();
  65813. source.buffer = buffer;
  65814. source.connect(_this.audioContext.destination);
  65815. source.start(0);
  65816. setTimeout(function () {
  65817. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  65818. _this.unlocked = true;
  65819. window.removeEventListener('touchend', unlockaudio, false);
  65820. if (_this.onAudioUnlocked) {
  65821. _this.onAudioUnlocked();
  65822. }
  65823. }
  65824. }, 0);
  65825. };
  65826. window.addEventListener('touchend', unlockaudio, false);
  65827. };
  65828. AudioEngine.prototype._initializeAudioContext = function () {
  65829. try {
  65830. if (this.canUseWebAudio) {
  65831. this._audioContext = new AudioContext();
  65832. // create a global volume gain node
  65833. this.masterGain = this._audioContext.createGain();
  65834. this.masterGain.gain.value = 1;
  65835. this.masterGain.connect(this._audioContext.destination);
  65836. this._audioContextInitialized = true;
  65837. }
  65838. }
  65839. catch (e) {
  65840. this.canUseWebAudio = false;
  65841. BABYLON.Tools.Error("Web Audio: " + e.message);
  65842. }
  65843. };
  65844. AudioEngine.prototype.dispose = function () {
  65845. if (this.canUseWebAudio && this._audioContextInitialized) {
  65846. if (this._connectedAnalyser && this._audioContext) {
  65847. this._connectedAnalyser.stopDebugCanvas();
  65848. this._connectedAnalyser.dispose();
  65849. this.masterGain.disconnect();
  65850. this.masterGain.connect(this._audioContext.destination);
  65851. this._connectedAnalyser = null;
  65852. }
  65853. this.masterGain.gain.value = 1;
  65854. }
  65855. this.WarnedWebAudioUnsupported = false;
  65856. };
  65857. AudioEngine.prototype.getGlobalVolume = function () {
  65858. if (this.canUseWebAudio && this._audioContextInitialized) {
  65859. return this.masterGain.gain.value;
  65860. }
  65861. else {
  65862. return -1;
  65863. }
  65864. };
  65865. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  65866. if (this.canUseWebAudio && this._audioContextInitialized) {
  65867. this.masterGain.gain.value = newVolume;
  65868. }
  65869. };
  65870. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  65871. if (this._connectedAnalyser) {
  65872. this._connectedAnalyser.stopDebugCanvas();
  65873. }
  65874. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  65875. this._connectedAnalyser = analyser;
  65876. this.masterGain.disconnect();
  65877. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  65878. }
  65879. };
  65880. return AudioEngine;
  65881. }());
  65882. BABYLON.AudioEngine = AudioEngine;
  65883. })(BABYLON || (BABYLON = {}));
  65884. //# sourceMappingURL=babylon.audioEngine.js.map
  65885. var BABYLON;
  65886. (function (BABYLON) {
  65887. var Sound = /** @class */ (function () {
  65888. /**
  65889. * Create a sound and attach it to a scene
  65890. * @param name Name of your sound
  65891. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  65892. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  65893. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  65894. */
  65895. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  65896. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  65897. var _this = this;
  65898. this.autoplay = false;
  65899. this.loop = false;
  65900. this.useCustomAttenuation = false;
  65901. this.spatialSound = false;
  65902. this.refDistance = 1;
  65903. this.rolloffFactor = 1;
  65904. this.maxDistance = 100;
  65905. this.distanceModel = "linear";
  65906. this._panningModel = "equalpower";
  65907. /**
  65908. * Observable event when the current playing sound finishes.
  65909. */
  65910. this.onEndedObservable = new BABYLON.Observable();
  65911. this._playbackRate = 1;
  65912. this._streaming = false;
  65913. this._startTime = 0;
  65914. this._startOffset = 0;
  65915. this._position = BABYLON.Vector3.Zero();
  65916. /** @hidden */
  65917. this._positionInEmitterSpace = false;
  65918. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  65919. this._volume = 1;
  65920. this._isReadyToPlay = false;
  65921. this.isPlaying = false;
  65922. this.isPaused = false;
  65923. this._isDirectional = false;
  65924. // Used if you'd like to create a directional sound.
  65925. // If not set, the sound will be omnidirectional
  65926. this._coneInnerAngle = 360;
  65927. this._coneOuterAngle = 360;
  65928. this._coneOuterGain = 0;
  65929. this._isOutputConnected = false;
  65930. this._urlType = "Unknown";
  65931. this.name = name;
  65932. this._scene = scene;
  65933. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  65934. if (!compo) {
  65935. compo = new BABYLON.AudioSceneComponent(scene);
  65936. scene._addComponent(compo);
  65937. }
  65938. this._readyToPlayCallback = readyToPlayCallback;
  65939. // Default custom attenuation function is a linear attenuation
  65940. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  65941. if (currentDistance < maxDistance) {
  65942. return currentVolume * (1 - currentDistance / maxDistance);
  65943. }
  65944. else {
  65945. return 0;
  65946. }
  65947. };
  65948. if (options) {
  65949. this.autoplay = options.autoplay || false;
  65950. this.loop = options.loop || false;
  65951. // if volume === 0, we need another way to check this option
  65952. if (options.volume !== undefined) {
  65953. this._volume = options.volume;
  65954. }
  65955. this.spatialSound = options.spatialSound || false;
  65956. this.maxDistance = options.maxDistance || 100;
  65957. this.useCustomAttenuation = options.useCustomAttenuation || false;
  65958. this.rolloffFactor = options.rolloffFactor || 1;
  65959. this.refDistance = options.refDistance || 1;
  65960. this.distanceModel = options.distanceModel || "linear";
  65961. this._playbackRate = options.playbackRate || 1;
  65962. this._streaming = options.streaming || false;
  65963. }
  65964. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65965. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  65966. this._soundGain.gain.value = this._volume;
  65967. this._inputAudioNode = this._soundGain;
  65968. this._outputAudioNode = this._soundGain;
  65969. if (this.spatialSound) {
  65970. this._createSpatialParameters();
  65971. }
  65972. this._scene.mainSoundTrack.AddSound(this);
  65973. var validParameter = true;
  65974. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  65975. if (urlOrArrayBuffer) {
  65976. try {
  65977. if (typeof (urlOrArrayBuffer) === "string") {
  65978. this._urlType = "String";
  65979. }
  65980. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  65981. this._urlType = "ArrayBuffer";
  65982. }
  65983. else if (urlOrArrayBuffer instanceof MediaStream) {
  65984. this._urlType = "MediaStream";
  65985. }
  65986. else if (Array.isArray(urlOrArrayBuffer)) {
  65987. this._urlType = "Array";
  65988. }
  65989. var urls = [];
  65990. var codecSupportedFound = false;
  65991. switch (this._urlType) {
  65992. case "MediaStream":
  65993. this._streaming = true;
  65994. this._isReadyToPlay = true;
  65995. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  65996. if (this.autoplay) {
  65997. this.play();
  65998. }
  65999. if (this._readyToPlayCallback) {
  66000. this._readyToPlayCallback();
  66001. }
  66002. break;
  66003. case "ArrayBuffer":
  66004. if (urlOrArrayBuffer.byteLength > 0) {
  66005. codecSupportedFound = true;
  66006. this._soundLoaded(urlOrArrayBuffer);
  66007. }
  66008. break;
  66009. case "String":
  66010. urls.push(urlOrArrayBuffer);
  66011. case "Array":
  66012. if (urls.length === 0)
  66013. urls = urlOrArrayBuffer;
  66014. // If we found a supported format, we load it immediately and stop the loop
  66015. for (var i = 0; i < urls.length; i++) {
  66016. var url = urls[i];
  66017. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  66018. codecSupportedFound = true;
  66019. }
  66020. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  66021. codecSupportedFound = true;
  66022. }
  66023. if (url.indexOf(".wav", url.length - 4) !== -1) {
  66024. codecSupportedFound = true;
  66025. }
  66026. if (url.indexOf("blob:") !== -1) {
  66027. codecSupportedFound = true;
  66028. }
  66029. if (codecSupportedFound) {
  66030. // Loading sound using XHR2
  66031. if (!this._streaming) {
  66032. this._scene._loadFile(url, function (data) {
  66033. _this._soundLoaded(data);
  66034. }, undefined, true, true, function (exception) {
  66035. if (exception) {
  66036. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  66037. }
  66038. BABYLON.Tools.Error("Sound creation aborted.");
  66039. _this._scene.mainSoundTrack.RemoveSound(_this);
  66040. });
  66041. }
  66042. // Streaming sound using HTML5 Audio tag
  66043. else {
  66044. this._htmlAudioElement = new Audio(url);
  66045. this._htmlAudioElement.controls = false;
  66046. this._htmlAudioElement.loop = this.loop;
  66047. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  66048. this._htmlAudioElement.preload = "auto";
  66049. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  66050. _this._isReadyToPlay = true;
  66051. if (_this.autoplay) {
  66052. _this.play();
  66053. }
  66054. if (_this._readyToPlayCallback) {
  66055. _this._readyToPlayCallback();
  66056. }
  66057. });
  66058. document.body.appendChild(this._htmlAudioElement);
  66059. }
  66060. break;
  66061. }
  66062. }
  66063. break;
  66064. default:
  66065. validParameter = false;
  66066. break;
  66067. }
  66068. if (!validParameter) {
  66069. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  66070. }
  66071. else {
  66072. if (!codecSupportedFound) {
  66073. this._isReadyToPlay = true;
  66074. // Simulating a ready to play event to avoid breaking code path
  66075. if (this._readyToPlayCallback) {
  66076. window.setTimeout(function () {
  66077. if (_this._readyToPlayCallback) {
  66078. _this._readyToPlayCallback();
  66079. }
  66080. }, 1000);
  66081. }
  66082. }
  66083. }
  66084. }
  66085. catch (ex) {
  66086. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  66087. this._scene.mainSoundTrack.RemoveSound(this);
  66088. }
  66089. }
  66090. }
  66091. else {
  66092. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  66093. this._scene.mainSoundTrack.AddSound(this);
  66094. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  66095. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  66096. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  66097. }
  66098. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  66099. if (this._readyToPlayCallback) {
  66100. window.setTimeout(function () {
  66101. if (_this._readyToPlayCallback) {
  66102. _this._readyToPlayCallback();
  66103. }
  66104. }, 1000);
  66105. }
  66106. }
  66107. }
  66108. Sound.prototype.dispose = function () {
  66109. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66110. if (this.isPlaying) {
  66111. this.stop();
  66112. }
  66113. this._isReadyToPlay = false;
  66114. if (this.soundTrackId === -1) {
  66115. this._scene.mainSoundTrack.RemoveSound(this);
  66116. }
  66117. else if (this._scene.soundTracks) {
  66118. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  66119. }
  66120. if (this._soundGain) {
  66121. this._soundGain.disconnect();
  66122. this._soundGain = null;
  66123. }
  66124. if (this._soundPanner) {
  66125. this._soundPanner.disconnect();
  66126. this._soundPanner = null;
  66127. }
  66128. if (this._soundSource) {
  66129. this._soundSource.disconnect();
  66130. this._soundSource = null;
  66131. }
  66132. this._audioBuffer = null;
  66133. if (this._htmlAudioElement) {
  66134. this._htmlAudioElement.pause();
  66135. this._htmlAudioElement.src = "";
  66136. document.body.removeChild(this._htmlAudioElement);
  66137. }
  66138. if (this._streamingSource) {
  66139. this._streamingSource.disconnect();
  66140. }
  66141. if (this._connectedMesh && this._registerFunc) {
  66142. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66143. this._connectedMesh = null;
  66144. }
  66145. }
  66146. };
  66147. Sound.prototype.isReady = function () {
  66148. return this._isReadyToPlay;
  66149. };
  66150. Sound.prototype._soundLoaded = function (audioData) {
  66151. var _this = this;
  66152. if (!BABYLON.Engine.audioEngine.audioContext) {
  66153. return;
  66154. }
  66155. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  66156. _this._audioBuffer = buffer;
  66157. _this._isReadyToPlay = true;
  66158. if (_this.autoplay) {
  66159. _this.play();
  66160. }
  66161. if (_this._readyToPlayCallback) {
  66162. _this._readyToPlayCallback();
  66163. }
  66164. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  66165. };
  66166. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  66167. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66168. this._audioBuffer = audioBuffer;
  66169. this._isReadyToPlay = true;
  66170. }
  66171. };
  66172. Sound.prototype.updateOptions = function (options) {
  66173. if (options) {
  66174. this.loop = options.loop || this.loop;
  66175. this.maxDistance = options.maxDistance || this.maxDistance;
  66176. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  66177. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  66178. this.refDistance = options.refDistance || this.refDistance;
  66179. this.distanceModel = options.distanceModel || this.distanceModel;
  66180. this._playbackRate = options.playbackRate || this._playbackRate;
  66181. this._updateSpatialParameters();
  66182. if (this.isPlaying) {
  66183. if (this._streaming && this._htmlAudioElement) {
  66184. this._htmlAudioElement.playbackRate = this._playbackRate;
  66185. }
  66186. else {
  66187. if (this._soundSource) {
  66188. this._soundSource.playbackRate.value = this._playbackRate;
  66189. }
  66190. }
  66191. }
  66192. }
  66193. };
  66194. Sound.prototype._createSpatialParameters = function () {
  66195. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66196. if (this._scene.headphone) {
  66197. this._panningModel = "HRTF";
  66198. }
  66199. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  66200. this._updateSpatialParameters();
  66201. this._soundPanner.connect(this._outputAudioNode);
  66202. this._inputAudioNode = this._soundPanner;
  66203. }
  66204. };
  66205. Sound.prototype._updateSpatialParameters = function () {
  66206. if (this.spatialSound && this._soundPanner) {
  66207. if (this.useCustomAttenuation) {
  66208. // Tricks to disable in a way embedded Web Audio attenuation
  66209. this._soundPanner.distanceModel = "linear";
  66210. this._soundPanner.maxDistance = Number.MAX_VALUE;
  66211. this._soundPanner.refDistance = 1;
  66212. this._soundPanner.rolloffFactor = 1;
  66213. this._soundPanner.panningModel = this._panningModel;
  66214. }
  66215. else {
  66216. this._soundPanner.distanceModel = this.distanceModel;
  66217. this._soundPanner.maxDistance = this.maxDistance;
  66218. this._soundPanner.refDistance = this.refDistance;
  66219. this._soundPanner.rolloffFactor = this.rolloffFactor;
  66220. this._soundPanner.panningModel = this._panningModel;
  66221. }
  66222. }
  66223. };
  66224. Sound.prototype.switchPanningModelToHRTF = function () {
  66225. this._panningModel = "HRTF";
  66226. this._switchPanningModel();
  66227. };
  66228. Sound.prototype.switchPanningModelToEqualPower = function () {
  66229. this._panningModel = "equalpower";
  66230. this._switchPanningModel();
  66231. };
  66232. Sound.prototype._switchPanningModel = function () {
  66233. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66234. this._soundPanner.panningModel = this._panningModel;
  66235. }
  66236. };
  66237. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  66238. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66239. if (this._isOutputConnected) {
  66240. this._outputAudioNode.disconnect();
  66241. }
  66242. this._outputAudioNode.connect(soundTrackAudioNode);
  66243. this._isOutputConnected = true;
  66244. }
  66245. };
  66246. /**
  66247. * Transform this sound into a directional source
  66248. * @param coneInnerAngle Size of the inner cone in degree
  66249. * @param coneOuterAngle Size of the outer cone in degree
  66250. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  66251. */
  66252. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  66253. if (coneOuterAngle < coneInnerAngle) {
  66254. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  66255. return;
  66256. }
  66257. this._coneInnerAngle = coneInnerAngle;
  66258. this._coneOuterAngle = coneOuterAngle;
  66259. this._coneOuterGain = coneOuterGain;
  66260. this._isDirectional = true;
  66261. if (this.isPlaying && this.loop) {
  66262. this.stop();
  66263. this.play();
  66264. }
  66265. };
  66266. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  66267. /**
  66268. * Gets or sets the inner angle for the directional cone.
  66269. */
  66270. get: function () {
  66271. return this._coneInnerAngle;
  66272. },
  66273. /**
  66274. * Gets or sets the inner angle for the directional cone.
  66275. */
  66276. set: function (value) {
  66277. if (value != this._coneInnerAngle) {
  66278. if (this._coneOuterAngle < value) {
  66279. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66280. return;
  66281. }
  66282. this._coneInnerAngle = value;
  66283. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66284. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66285. }
  66286. }
  66287. },
  66288. enumerable: true,
  66289. configurable: true
  66290. });
  66291. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  66292. /**
  66293. * Gets or sets the outer angle for the directional cone.
  66294. */
  66295. get: function () {
  66296. return this._coneOuterAngle;
  66297. },
  66298. /**
  66299. * Gets or sets the outer angle for the directional cone.
  66300. */
  66301. set: function (value) {
  66302. if (value != this._coneOuterAngle) {
  66303. if (value < this._coneInnerAngle) {
  66304. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66305. return;
  66306. }
  66307. this._coneOuterAngle = value;
  66308. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66309. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66310. }
  66311. }
  66312. },
  66313. enumerable: true,
  66314. configurable: true
  66315. });
  66316. Sound.prototype.setPosition = function (newPosition) {
  66317. this._position = newPosition;
  66318. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66319. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66320. }
  66321. };
  66322. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  66323. this._localDirection = newLocalDirection;
  66324. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  66325. this._updateDirection();
  66326. }
  66327. };
  66328. Sound.prototype._updateDirection = function () {
  66329. if (!this._connectedMesh || !this._soundPanner) {
  66330. return;
  66331. }
  66332. var mat = this._connectedMesh.getWorldMatrix();
  66333. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  66334. direction.normalize();
  66335. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  66336. };
  66337. Sound.prototype.updateDistanceFromListener = function () {
  66338. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  66339. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  66340. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  66341. }
  66342. };
  66343. Sound.prototype.setAttenuationFunction = function (callback) {
  66344. this._customAttenuationFunction = callback;
  66345. };
  66346. /**
  66347. * Play the sound
  66348. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  66349. * @param offset (optional) Start the sound setting it at a specific time
  66350. */
  66351. Sound.prototype.play = function (time, offset) {
  66352. var _this = this;
  66353. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  66354. try {
  66355. if (this._startOffset < 0) {
  66356. time = -this._startOffset;
  66357. this._startOffset = 0;
  66358. }
  66359. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66360. if (!this._soundSource || !this._streamingSource) {
  66361. if (this.spatialSound && this._soundPanner) {
  66362. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66363. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66364. }
  66365. if (this._isDirectional) {
  66366. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66367. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66368. this._soundPanner.coneOuterGain = this._coneOuterGain;
  66369. if (this._connectedMesh) {
  66370. this._updateDirection();
  66371. }
  66372. else {
  66373. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  66374. }
  66375. }
  66376. }
  66377. }
  66378. if (this._streaming) {
  66379. if (!this._streamingSource) {
  66380. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  66381. this._htmlAudioElement.onended = function () { _this._onended(); };
  66382. this._htmlAudioElement.playbackRate = this._playbackRate;
  66383. }
  66384. this._streamingSource.disconnect();
  66385. this._streamingSource.connect(this._inputAudioNode);
  66386. if (this._htmlAudioElement) {
  66387. this._htmlAudioElement.play();
  66388. }
  66389. }
  66390. else {
  66391. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  66392. this._soundSource.buffer = this._audioBuffer;
  66393. this._soundSource.connect(this._inputAudioNode);
  66394. this._soundSource.loop = this.loop;
  66395. this._soundSource.playbackRate.value = this._playbackRate;
  66396. this._soundSource.onended = function () { _this._onended(); };
  66397. if (this._soundSource.buffer) {
  66398. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  66399. }
  66400. }
  66401. this._startTime = startTime;
  66402. this.isPlaying = true;
  66403. this.isPaused = false;
  66404. }
  66405. catch (ex) {
  66406. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  66407. }
  66408. }
  66409. };
  66410. Sound.prototype._onended = function () {
  66411. this.isPlaying = false;
  66412. if (this.onended) {
  66413. this.onended();
  66414. }
  66415. this.onEndedObservable.notifyObservers(this);
  66416. };
  66417. /**
  66418. * Stop the sound
  66419. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  66420. */
  66421. Sound.prototype.stop = function (time) {
  66422. if (this.isPlaying) {
  66423. if (this._streaming) {
  66424. if (this._htmlAudioElement) {
  66425. this._htmlAudioElement.pause();
  66426. // Test needed for Firefox or it will generate an Invalid State Error
  66427. if (this._htmlAudioElement.currentTime > 0) {
  66428. this._htmlAudioElement.currentTime = 0;
  66429. }
  66430. }
  66431. else {
  66432. this._streamingSource.disconnect();
  66433. }
  66434. }
  66435. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  66436. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66437. this._soundSource.stop(stopTime);
  66438. this._soundSource.onended = function () { };
  66439. if (!this.isPaused) {
  66440. this._startOffset = 0;
  66441. }
  66442. }
  66443. this.isPlaying = false;
  66444. }
  66445. };
  66446. Sound.prototype.pause = function () {
  66447. if (this.isPlaying) {
  66448. this.isPaused = true;
  66449. if (this._streaming) {
  66450. if (this._htmlAudioElement) {
  66451. this._htmlAudioElement.pause();
  66452. }
  66453. else {
  66454. this._streamingSource.disconnect();
  66455. }
  66456. }
  66457. else if (BABYLON.Engine.audioEngine.audioContext) {
  66458. this.stop(0);
  66459. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  66460. }
  66461. }
  66462. };
  66463. Sound.prototype.setVolume = function (newVolume, time) {
  66464. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  66465. if (time && BABYLON.Engine.audioEngine.audioContext) {
  66466. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  66467. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  66468. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  66469. }
  66470. else {
  66471. this._soundGain.gain.value = newVolume;
  66472. }
  66473. }
  66474. this._volume = newVolume;
  66475. };
  66476. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  66477. this._playbackRate = newPlaybackRate;
  66478. if (this.isPlaying) {
  66479. if (this._streaming && this._htmlAudioElement) {
  66480. this._htmlAudioElement.playbackRate = this._playbackRate;
  66481. }
  66482. else if (this._soundSource) {
  66483. this._soundSource.playbackRate.value = this._playbackRate;
  66484. }
  66485. }
  66486. };
  66487. Sound.prototype.getVolume = function () {
  66488. return this._volume;
  66489. };
  66490. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  66491. var _this = this;
  66492. if (this._connectedMesh && this._registerFunc) {
  66493. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66494. this._registerFunc = null;
  66495. }
  66496. this._connectedMesh = meshToConnectTo;
  66497. if (!this.spatialSound) {
  66498. this.spatialSound = true;
  66499. this._createSpatialParameters();
  66500. if (this.isPlaying && this.loop) {
  66501. this.stop();
  66502. this.play();
  66503. }
  66504. }
  66505. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  66506. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  66507. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  66508. };
  66509. Sound.prototype.detachFromMesh = function () {
  66510. if (this._connectedMesh && this._registerFunc) {
  66511. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66512. this._registerFunc = null;
  66513. this._connectedMesh = null;
  66514. }
  66515. };
  66516. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  66517. if (!node.getBoundingInfo) {
  66518. return;
  66519. }
  66520. var mesh = node;
  66521. if (this._positionInEmitterSpace) {
  66522. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  66523. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  66524. }
  66525. else {
  66526. var boundingInfo = mesh.getBoundingInfo();
  66527. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  66528. }
  66529. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  66530. this._updateDirection();
  66531. }
  66532. };
  66533. Sound.prototype.clone = function () {
  66534. var _this = this;
  66535. if (!this._streaming) {
  66536. var setBufferAndRun = function () {
  66537. if (_this._isReadyToPlay) {
  66538. clonedSound._audioBuffer = _this.getAudioBuffer();
  66539. clonedSound._isReadyToPlay = true;
  66540. if (clonedSound.autoplay) {
  66541. clonedSound.play();
  66542. }
  66543. }
  66544. else {
  66545. window.setTimeout(setBufferAndRun, 300);
  66546. }
  66547. };
  66548. var currentOptions = {
  66549. autoplay: this.autoplay, loop: this.loop,
  66550. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  66551. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  66552. refDistance: this.refDistance, distanceModel: this.distanceModel
  66553. };
  66554. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  66555. if (this.useCustomAttenuation) {
  66556. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  66557. }
  66558. clonedSound.setPosition(this._position);
  66559. clonedSound.setPlaybackRate(this._playbackRate);
  66560. setBufferAndRun();
  66561. return clonedSound;
  66562. }
  66563. // Can't clone a streaming sound
  66564. else {
  66565. return null;
  66566. }
  66567. };
  66568. Sound.prototype.getAudioBuffer = function () {
  66569. return this._audioBuffer;
  66570. };
  66571. Sound.prototype.serialize = function () {
  66572. var serializationObject = {
  66573. name: this.name,
  66574. url: this.name,
  66575. autoplay: this.autoplay,
  66576. loop: this.loop,
  66577. volume: this._volume,
  66578. spatialSound: this.spatialSound,
  66579. maxDistance: this.maxDistance,
  66580. rolloffFactor: this.rolloffFactor,
  66581. refDistance: this.refDistance,
  66582. distanceModel: this.distanceModel,
  66583. playbackRate: this._playbackRate,
  66584. panningModel: this._panningModel,
  66585. soundTrackId: this.soundTrackId
  66586. };
  66587. if (this.spatialSound) {
  66588. if (this._connectedMesh)
  66589. serializationObject.connectedMeshId = this._connectedMesh.id;
  66590. serializationObject.position = this._position.asArray();
  66591. serializationObject.refDistance = this.refDistance;
  66592. serializationObject.distanceModel = this.distanceModel;
  66593. serializationObject.isDirectional = this._isDirectional;
  66594. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  66595. serializationObject.coneInnerAngle = this._coneInnerAngle;
  66596. serializationObject.coneOuterAngle = this._coneOuterAngle;
  66597. serializationObject.coneOuterGain = this._coneOuterGain;
  66598. }
  66599. return serializationObject;
  66600. };
  66601. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  66602. var soundName = parsedSound.name;
  66603. var soundUrl;
  66604. if (parsedSound.url) {
  66605. soundUrl = rootUrl + parsedSound.url;
  66606. }
  66607. else {
  66608. soundUrl = rootUrl + soundName;
  66609. }
  66610. var options = {
  66611. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  66612. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  66613. rolloffFactor: parsedSound.rolloffFactor,
  66614. refDistance: parsedSound.refDistance,
  66615. distanceModel: parsedSound.distanceModel,
  66616. playbackRate: parsedSound.playbackRate
  66617. };
  66618. var newSound;
  66619. if (!sourceSound) {
  66620. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  66621. scene._addPendingData(newSound);
  66622. }
  66623. else {
  66624. var setBufferAndRun = function () {
  66625. if (sourceSound._isReadyToPlay) {
  66626. newSound._audioBuffer = sourceSound.getAudioBuffer();
  66627. newSound._isReadyToPlay = true;
  66628. if (newSound.autoplay) {
  66629. newSound.play();
  66630. }
  66631. }
  66632. else {
  66633. window.setTimeout(setBufferAndRun, 300);
  66634. }
  66635. };
  66636. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  66637. setBufferAndRun();
  66638. }
  66639. if (parsedSound.position) {
  66640. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  66641. newSound.setPosition(soundPosition);
  66642. }
  66643. if (parsedSound.isDirectional) {
  66644. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  66645. if (parsedSound.localDirectionToMesh) {
  66646. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  66647. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  66648. }
  66649. }
  66650. if (parsedSound.connectedMeshId) {
  66651. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  66652. if (connectedMesh) {
  66653. newSound.attachToMesh(connectedMesh);
  66654. }
  66655. }
  66656. return newSound;
  66657. };
  66658. return Sound;
  66659. }());
  66660. BABYLON.Sound = Sound;
  66661. })(BABYLON || (BABYLON = {}));
  66662. //# sourceMappingURL=babylon.sound.js.map
  66663. var BABYLON;
  66664. (function (BABYLON) {
  66665. var SoundTrack = /** @class */ (function () {
  66666. function SoundTrack(scene, options) {
  66667. this.id = -1;
  66668. this._isMainTrack = false;
  66669. this._isInitialized = false;
  66670. this._scene = scene;
  66671. this.soundCollection = new Array();
  66672. this._options = options;
  66673. if (!this._isMainTrack && this._scene.soundTracks) {
  66674. this._scene.soundTracks.push(this);
  66675. this.id = this._scene.soundTracks.length - 1;
  66676. }
  66677. }
  66678. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  66679. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66680. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  66681. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  66682. if (this._options) {
  66683. if (this._options.volume) {
  66684. this._outputAudioNode.gain.value = this._options.volume;
  66685. }
  66686. if (this._options.mainTrack) {
  66687. this._isMainTrack = this._options.mainTrack;
  66688. }
  66689. }
  66690. this._isInitialized = true;
  66691. }
  66692. };
  66693. SoundTrack.prototype.dispose = function () {
  66694. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  66695. if (this._connectedAnalyser) {
  66696. this._connectedAnalyser.stopDebugCanvas();
  66697. }
  66698. while (this.soundCollection.length) {
  66699. this.soundCollection[0].dispose();
  66700. }
  66701. if (this._outputAudioNode) {
  66702. this._outputAudioNode.disconnect();
  66703. }
  66704. this._outputAudioNode = null;
  66705. }
  66706. };
  66707. SoundTrack.prototype.AddSound = function (sound) {
  66708. if (!this._isInitialized) {
  66709. this._initializeSoundTrackAudioGraph();
  66710. }
  66711. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66712. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  66713. }
  66714. if (sound.soundTrackId) {
  66715. if (sound.soundTrackId === -1) {
  66716. this._scene.mainSoundTrack.RemoveSound(sound);
  66717. }
  66718. else if (this._scene.soundTracks) {
  66719. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  66720. }
  66721. }
  66722. this.soundCollection.push(sound);
  66723. sound.soundTrackId = this.id;
  66724. };
  66725. SoundTrack.prototype.RemoveSound = function (sound) {
  66726. var index = this.soundCollection.indexOf(sound);
  66727. if (index !== -1) {
  66728. this.soundCollection.splice(index, 1);
  66729. }
  66730. };
  66731. SoundTrack.prototype.setVolume = function (newVolume) {
  66732. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66733. this._outputAudioNode.gain.value = newVolume;
  66734. }
  66735. };
  66736. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  66737. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66738. for (var i = 0; i < this.soundCollection.length; i++) {
  66739. this.soundCollection[i].switchPanningModelToHRTF();
  66740. }
  66741. }
  66742. };
  66743. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  66744. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66745. for (var i = 0; i < this.soundCollection.length; i++) {
  66746. this.soundCollection[i].switchPanningModelToEqualPower();
  66747. }
  66748. }
  66749. };
  66750. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  66751. if (this._connectedAnalyser) {
  66752. this._connectedAnalyser.stopDebugCanvas();
  66753. }
  66754. this._connectedAnalyser = analyser;
  66755. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66756. this._outputAudioNode.disconnect();
  66757. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  66758. }
  66759. };
  66760. return SoundTrack;
  66761. }());
  66762. BABYLON.SoundTrack = SoundTrack;
  66763. })(BABYLON || (BABYLON = {}));
  66764. //# sourceMappingURL=babylon.soundtrack.js.map
  66765. var BABYLON;
  66766. (function (BABYLON) {
  66767. /**
  66768. * Class used to work with sound analyzer using fast fourier transform (FFT)
  66769. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66770. */
  66771. var Analyser = /** @class */ (function () {
  66772. /**
  66773. * Creates a new analyser
  66774. * @param scene defines hosting scene
  66775. */
  66776. function Analyser(scene) {
  66777. /**
  66778. * Gets or sets the smoothing
  66779. * @ignorenaming
  66780. */
  66781. this.SMOOTHING = 0.75;
  66782. /**
  66783. * Gets or sets the FFT table size
  66784. * @ignorenaming
  66785. */
  66786. this.FFT_SIZE = 512;
  66787. /**
  66788. * Gets or sets the bar graph amplitude
  66789. * @ignorenaming
  66790. */
  66791. this.BARGRAPHAMPLITUDE = 256;
  66792. /**
  66793. * Gets or sets the position of the debug canvas
  66794. * @ignorenaming
  66795. */
  66796. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  66797. /**
  66798. * Gets or sets the debug canvas size
  66799. * @ignorenaming
  66800. */
  66801. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  66802. this._scene = scene;
  66803. this._audioEngine = BABYLON.Engine.audioEngine;
  66804. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  66805. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  66806. this._webAudioAnalyser.minDecibels = -140;
  66807. this._webAudioAnalyser.maxDecibels = 0;
  66808. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66809. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66810. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  66811. }
  66812. }
  66813. /**
  66814. * Get the number of data values you will have to play with for the visualization
  66815. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  66816. * @returns a number
  66817. */
  66818. Analyser.prototype.getFrequencyBinCount = function () {
  66819. if (this._audioEngine.canUseWebAudio) {
  66820. return this._webAudioAnalyser.frequencyBinCount;
  66821. }
  66822. else {
  66823. return 0;
  66824. }
  66825. };
  66826. /**
  66827. * Gets the current frequency data as a byte array
  66828. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66829. * @returns a Uint8Array
  66830. */
  66831. Analyser.prototype.getByteFrequencyData = function () {
  66832. if (this._audioEngine.canUseWebAudio) {
  66833. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66834. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66835. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  66836. }
  66837. return this._byteFreqs;
  66838. };
  66839. /**
  66840. * Gets the current waveform as a byte array
  66841. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  66842. * @returns a Uint8Array
  66843. */
  66844. Analyser.prototype.getByteTimeDomainData = function () {
  66845. if (this._audioEngine.canUseWebAudio) {
  66846. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66847. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66848. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  66849. }
  66850. return this._byteTime;
  66851. };
  66852. /**
  66853. * Gets the current frequency data as a float array
  66854. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66855. * @returns a Float32Array
  66856. */
  66857. Analyser.prototype.getFloatFrequencyData = function () {
  66858. if (this._audioEngine.canUseWebAudio) {
  66859. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66860. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66861. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  66862. }
  66863. return this._floatFreqs;
  66864. };
  66865. /**
  66866. * Renders the debug canvas
  66867. */
  66868. Analyser.prototype.drawDebugCanvas = function () {
  66869. var _this = this;
  66870. if (this._audioEngine.canUseWebAudio) {
  66871. if (!this._debugCanvas) {
  66872. this._debugCanvas = document.createElement("canvas");
  66873. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  66874. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  66875. this._debugCanvas.style.position = "absolute";
  66876. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  66877. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  66878. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  66879. document.body.appendChild(this._debugCanvas);
  66880. this._registerFunc = function () {
  66881. _this.drawDebugCanvas();
  66882. };
  66883. this._scene.registerBeforeRender(this._registerFunc);
  66884. }
  66885. if (this._registerFunc && this._debugCanvasContext) {
  66886. var workingArray = this.getByteFrequencyData();
  66887. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  66888. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  66889. // Draw the frequency domain chart.
  66890. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  66891. var value = workingArray[i];
  66892. var percent = value / this.BARGRAPHAMPLITUDE;
  66893. var height = this.DEBUGCANVASSIZE.height * percent;
  66894. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  66895. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  66896. var hue = i / this.getFrequencyBinCount() * 360;
  66897. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  66898. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  66899. }
  66900. }
  66901. }
  66902. };
  66903. /**
  66904. * Stops rendering the debug canvas and removes it
  66905. */
  66906. Analyser.prototype.stopDebugCanvas = function () {
  66907. if (this._debugCanvas) {
  66908. if (this._registerFunc) {
  66909. this._scene.unregisterBeforeRender(this._registerFunc);
  66910. this._registerFunc = null;
  66911. }
  66912. document.body.removeChild(this._debugCanvas);
  66913. this._debugCanvas = null;
  66914. this._debugCanvasContext = null;
  66915. }
  66916. };
  66917. /**
  66918. * Connects two audio nodes
  66919. * @param inputAudioNode defines first node to connect
  66920. * @param outputAudioNode defines second node to connect
  66921. */
  66922. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  66923. if (this._audioEngine.canUseWebAudio) {
  66924. inputAudioNode.connect(this._webAudioAnalyser);
  66925. this._webAudioAnalyser.connect(outputAudioNode);
  66926. }
  66927. };
  66928. /**
  66929. * Releases all associated resources
  66930. */
  66931. Analyser.prototype.dispose = function () {
  66932. if (this._audioEngine.canUseWebAudio) {
  66933. this._webAudioAnalyser.disconnect();
  66934. }
  66935. };
  66936. return Analyser;
  66937. }());
  66938. BABYLON.Analyser = Analyser;
  66939. })(BABYLON || (BABYLON = {}));
  66940. //# sourceMappingURL=babylon.analyser.js.map
  66941. var BABYLON;
  66942. (function (BABYLON) {
  66943. /**
  66944. * Wraps one or more Sound objects and selects one with random weight for playback.
  66945. */
  66946. var WeightedSound = /** @class */ (function () {
  66947. /**
  66948. * Creates a new WeightedSound from the list of sounds given.
  66949. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  66950. * @param sounds Array of Sounds that will be selected from.
  66951. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  66952. */
  66953. function WeightedSound(loop, sounds, weights) {
  66954. var _this = this;
  66955. /** When true a Sound will be selected and played when the current playing Sound completes. */
  66956. this.loop = false;
  66957. this._coneInnerAngle = 360;
  66958. this._coneOuterAngle = 360;
  66959. this._volume = 1;
  66960. /** A Sound is currently playing. */
  66961. this.isPlaying = false;
  66962. /** A Sound is currently paused. */
  66963. this.isPaused = false;
  66964. this._sounds = [];
  66965. this._weights = [];
  66966. if (sounds.length !== weights.length) {
  66967. throw new Error('Sounds length does not equal weights length');
  66968. }
  66969. this.loop = loop;
  66970. this._weights = weights;
  66971. // Normalize the weights
  66972. var weightSum = 0;
  66973. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  66974. var weight = weights_1[_i];
  66975. weightSum += weight;
  66976. }
  66977. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  66978. for (var i = 0; i < this._weights.length; i++) {
  66979. this._weights[i] *= invWeightSum;
  66980. }
  66981. this._sounds = sounds;
  66982. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  66983. var sound = _b[_a];
  66984. sound.onEndedObservable.add(function () { _this._onended(); });
  66985. }
  66986. }
  66987. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  66988. /**
  66989. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  66990. */
  66991. get: function () {
  66992. return this._coneInnerAngle;
  66993. },
  66994. /**
  66995. * The size of cone in degress for a directional sound in which there will be no attenuation.
  66996. */
  66997. set: function (value) {
  66998. if (value !== this._coneInnerAngle) {
  66999. if (this._coneOuterAngle < value) {
  67000. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67001. return;
  67002. }
  67003. this._coneInnerAngle = value;
  67004. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  67005. var sound = _a[_i];
  67006. sound.directionalConeInnerAngle = value;
  67007. }
  67008. }
  67009. },
  67010. enumerable: true,
  67011. configurable: true
  67012. });
  67013. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  67014. /**
  67015. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  67016. * Listener angles between innerAngle and outerAngle will falloff linearly.
  67017. */
  67018. get: function () {
  67019. return this._coneOuterAngle;
  67020. },
  67021. /**
  67022. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  67023. * Listener angles between innerAngle and outerAngle will falloff linearly.
  67024. */
  67025. set: function (value) {
  67026. if (value !== this._coneOuterAngle) {
  67027. if (value < this._coneInnerAngle) {
  67028. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67029. return;
  67030. }
  67031. this._coneOuterAngle = value;
  67032. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  67033. var sound = _a[_i];
  67034. sound.directionalConeOuterAngle = value;
  67035. }
  67036. }
  67037. },
  67038. enumerable: true,
  67039. configurable: true
  67040. });
  67041. Object.defineProperty(WeightedSound.prototype, "volume", {
  67042. /**
  67043. * Playback volume.
  67044. */
  67045. get: function () {
  67046. return this._volume;
  67047. },
  67048. /**
  67049. * Playback volume.
  67050. */
  67051. set: function (value) {
  67052. if (value !== this._volume) {
  67053. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  67054. var sound = _a[_i];
  67055. sound.setVolume(value);
  67056. }
  67057. }
  67058. },
  67059. enumerable: true,
  67060. configurable: true
  67061. });
  67062. WeightedSound.prototype._onended = function () {
  67063. if (this._currentIndex !== undefined) {
  67064. this._sounds[this._currentIndex].autoplay = false;
  67065. }
  67066. if (this.loop && this.isPlaying) {
  67067. this.play();
  67068. }
  67069. else {
  67070. this.isPlaying = false;
  67071. }
  67072. };
  67073. /**
  67074. * Suspend playback
  67075. */
  67076. WeightedSound.prototype.pause = function () {
  67077. this.isPaused = true;
  67078. if (this._currentIndex !== undefined) {
  67079. this._sounds[this._currentIndex].pause();
  67080. }
  67081. };
  67082. /**
  67083. * Stop playback
  67084. */
  67085. WeightedSound.prototype.stop = function () {
  67086. this.isPlaying = false;
  67087. if (this._currentIndex !== undefined) {
  67088. this._sounds[this._currentIndex].stop();
  67089. }
  67090. };
  67091. /**
  67092. * Start playback.
  67093. * @param startOffset Position the clip head at a specific time in seconds.
  67094. */
  67095. WeightedSound.prototype.play = function (startOffset) {
  67096. if (!this.isPaused) {
  67097. this.stop();
  67098. var randomValue = Math.random();
  67099. var total = 0;
  67100. for (var i = 0; i < this._weights.length; i++) {
  67101. total += this._weights[i];
  67102. if (randomValue <= total) {
  67103. this._currentIndex = i;
  67104. break;
  67105. }
  67106. }
  67107. }
  67108. var sound = this._sounds[this._currentIndex];
  67109. if (sound.isReady()) {
  67110. sound.play(0, this.isPaused ? undefined : startOffset);
  67111. }
  67112. else {
  67113. sound.autoplay = true;
  67114. }
  67115. this.isPlaying = true;
  67116. this.isPaused = false;
  67117. };
  67118. return WeightedSound;
  67119. }());
  67120. BABYLON.WeightedSound = WeightedSound;
  67121. })(BABYLON || (BABYLON = {}));
  67122. //# sourceMappingURL=babylon.weightedsound.js.map
  67123. var BABYLON;
  67124. (function (BABYLON) {
  67125. // Adds the parser to the scene parsers.
  67126. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  67127. // TODO: add sound
  67128. var loadedSounds = [];
  67129. var loadedSound;
  67130. container.sounds = container.sounds || [];
  67131. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67132. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67133. var parsedSound = parsedData.sounds[index];
  67134. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67135. if (!parsedSound.url)
  67136. parsedSound.url = parsedSound.name;
  67137. if (!loadedSounds[parsedSound.url]) {
  67138. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67139. loadedSounds[parsedSound.url] = loadedSound;
  67140. container.sounds.push(loadedSound);
  67141. }
  67142. else {
  67143. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67144. }
  67145. }
  67146. else {
  67147. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67148. }
  67149. }
  67150. }
  67151. loadedSounds = [];
  67152. });
  67153. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  67154. get: function () {
  67155. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67156. if (!compo) {
  67157. compo = new AudioSceneComponent(this);
  67158. this._addComponent(compo);
  67159. }
  67160. if (!this._mainSoundTrack) {
  67161. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  67162. }
  67163. return this._mainSoundTrack;
  67164. },
  67165. enumerable: true,
  67166. configurable: true
  67167. });
  67168. BABYLON.Scene.prototype.getSoundByName = function (name) {
  67169. var index;
  67170. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  67171. if (this.mainSoundTrack.soundCollection[index].name === name) {
  67172. return this.mainSoundTrack.soundCollection[index];
  67173. }
  67174. }
  67175. if (this.soundTracks) {
  67176. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  67177. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  67178. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  67179. return this.soundTracks[sdIndex].soundCollection[index];
  67180. }
  67181. }
  67182. }
  67183. }
  67184. return null;
  67185. };
  67186. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  67187. get: function () {
  67188. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67189. if (!compo) {
  67190. compo = new AudioSceneComponent(this);
  67191. this._addComponent(compo);
  67192. }
  67193. return compo.audioEnabled;
  67194. },
  67195. set: function (value) {
  67196. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67197. if (!compo) {
  67198. compo = new AudioSceneComponent(this);
  67199. this._addComponent(compo);
  67200. }
  67201. if (value) {
  67202. compo.enableAudio();
  67203. }
  67204. else {
  67205. compo.disableAudio();
  67206. }
  67207. },
  67208. enumerable: true,
  67209. configurable: true
  67210. });
  67211. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  67212. get: function () {
  67213. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67214. if (!compo) {
  67215. compo = new AudioSceneComponent(this);
  67216. this._addComponent(compo);
  67217. }
  67218. return compo.headphone;
  67219. },
  67220. set: function (value) {
  67221. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67222. if (!compo) {
  67223. compo = new AudioSceneComponent(this);
  67224. this._addComponent(compo);
  67225. }
  67226. if (value) {
  67227. compo.switchAudioModeForHeadphones();
  67228. }
  67229. else {
  67230. compo.switchAudioModeForNormalSpeakers();
  67231. }
  67232. },
  67233. enumerable: true,
  67234. configurable: true
  67235. });
  67236. /**
  67237. * Defines the sound scene component responsible to manage any sounds
  67238. * in a given scene.
  67239. */
  67240. var AudioSceneComponent = /** @class */ (function () {
  67241. /**
  67242. * Creates a new instance of the component for the given scene
  67243. * @param scene Defines the scene to register the component in
  67244. */
  67245. function AudioSceneComponent(scene) {
  67246. /**
  67247. * The component name helpfull to identify the component in the list of scene components.
  67248. */
  67249. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  67250. this._audioEnabled = true;
  67251. this._headphone = false;
  67252. this.scene = scene;
  67253. scene.soundTracks = new Array();
  67254. scene.sounds = new Array();
  67255. }
  67256. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  67257. /**
  67258. * Gets whether audio is enabled or not.
  67259. * Please use related enable/disable method to switch state.
  67260. */
  67261. get: function () {
  67262. return this._audioEnabled;
  67263. },
  67264. enumerable: true,
  67265. configurable: true
  67266. });
  67267. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  67268. /**
  67269. * Gets whether audio is outputing to headphone or not.
  67270. * Please use the according Switch methods to change output.
  67271. */
  67272. get: function () {
  67273. return this._headphone;
  67274. },
  67275. enumerable: true,
  67276. configurable: true
  67277. });
  67278. /**
  67279. * Registers the component in a given scene
  67280. */
  67281. AudioSceneComponent.prototype.register = function () {
  67282. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  67283. };
  67284. /**
  67285. * Rebuilds the elements related to this component in case of
  67286. * context lost for instance.
  67287. */
  67288. AudioSceneComponent.prototype.rebuild = function () {
  67289. // Nothing to do here. (Not rendering related)
  67290. };
  67291. /**
  67292. * Serializes the component data to the specified json object
  67293. * @param serializationObject The object to serialize to
  67294. */
  67295. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  67296. serializationObject.sounds = [];
  67297. if (this.scene.soundTracks) {
  67298. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  67299. var soundtrack = this.scene.soundTracks[index];
  67300. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  67301. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  67302. }
  67303. }
  67304. }
  67305. };
  67306. /**
  67307. * Adds all the element from the container to the scene
  67308. * @param container the container holding the elements
  67309. */
  67310. AudioSceneComponent.prototype.addFromContainer = function (container) {
  67311. var _this = this;
  67312. if (!container.sounds) {
  67313. return;
  67314. }
  67315. container.sounds.forEach(function (sound) {
  67316. sound.play();
  67317. sound.autoplay = true;
  67318. _this.scene.mainSoundTrack.AddSound(sound);
  67319. });
  67320. };
  67321. /**
  67322. * Removes all the elements in the container from the scene
  67323. * @param container contains the elements to remove
  67324. */
  67325. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  67326. var _this = this;
  67327. if (!container.sounds) {
  67328. return;
  67329. }
  67330. container.sounds.forEach(function (sound) {
  67331. sound.stop();
  67332. sound.autoplay = false;
  67333. _this.scene.mainSoundTrack.RemoveSound(sound);
  67334. });
  67335. };
  67336. /**
  67337. * Disposes the component and the associated ressources.
  67338. */
  67339. AudioSceneComponent.prototype.dispose = function () {
  67340. var scene = this.scene;
  67341. if (scene._mainSoundTrack) {
  67342. scene.mainSoundTrack.dispose();
  67343. }
  67344. if (scene.soundTracks) {
  67345. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  67346. scene.soundTracks[scIndex].dispose();
  67347. }
  67348. }
  67349. };
  67350. /**
  67351. * Disables audio in the associated scene.
  67352. */
  67353. AudioSceneComponent.prototype.disableAudio = function () {
  67354. var scene = this.scene;
  67355. this._audioEnabled = false;
  67356. var i;
  67357. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67358. scene.mainSoundTrack.soundCollection[i].pause();
  67359. }
  67360. if (scene.soundTracks) {
  67361. for (i = 0; i < scene.soundTracks.length; i++) {
  67362. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67363. scene.soundTracks[i].soundCollection[j].pause();
  67364. }
  67365. }
  67366. }
  67367. };
  67368. /**
  67369. * Enables audio in the associated scene.
  67370. */
  67371. AudioSceneComponent.prototype.enableAudio = function () {
  67372. var scene = this.scene;
  67373. this._audioEnabled = true;
  67374. var i;
  67375. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67376. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  67377. scene.mainSoundTrack.soundCollection[i].play();
  67378. }
  67379. }
  67380. if (scene.soundTracks) {
  67381. for (i = 0; i < scene.soundTracks.length; i++) {
  67382. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67383. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  67384. scene.soundTracks[i].soundCollection[j].play();
  67385. }
  67386. }
  67387. }
  67388. }
  67389. };
  67390. /**
  67391. * Switch audio to headphone output.
  67392. */
  67393. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  67394. var scene = this.scene;
  67395. this._headphone = true;
  67396. scene.mainSoundTrack.switchPanningModelToHRTF();
  67397. if (scene.soundTracks) {
  67398. for (var i = 0; i < scene.soundTracks.length; i++) {
  67399. scene.soundTracks[i].switchPanningModelToHRTF();
  67400. }
  67401. }
  67402. };
  67403. /**
  67404. * Switch audio to normal speakers.
  67405. */
  67406. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  67407. var scene = this.scene;
  67408. this._headphone = false;
  67409. scene.mainSoundTrack.switchPanningModelToEqualPower();
  67410. if (scene.soundTracks) {
  67411. for (var i = 0; i < scene.soundTracks.length; i++) {
  67412. scene.soundTracks[i].switchPanningModelToEqualPower();
  67413. }
  67414. }
  67415. };
  67416. AudioSceneComponent.prototype._afterRender = function () {
  67417. var scene = this.scene;
  67418. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  67419. return;
  67420. }
  67421. var listeningCamera;
  67422. var audioEngine = BABYLON.Engine.audioEngine;
  67423. if (scene.activeCameras.length > 0) {
  67424. listeningCamera = scene.activeCameras[0];
  67425. }
  67426. else {
  67427. listeningCamera = scene.activeCamera;
  67428. }
  67429. if (listeningCamera && audioEngine.audioContext) {
  67430. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  67431. // for VR cameras
  67432. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  67433. listeningCamera = listeningCamera.rigCameras[0];
  67434. }
  67435. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  67436. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  67437. cameraDirection.normalize();
  67438. // To avoid some errors on GearVR
  67439. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  67440. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  67441. }
  67442. var i;
  67443. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67444. var sound = scene.mainSoundTrack.soundCollection[i];
  67445. if (sound.useCustomAttenuation) {
  67446. sound.updateDistanceFromListener();
  67447. }
  67448. }
  67449. if (scene.soundTracks) {
  67450. for (i = 0; i < scene.soundTracks.length; i++) {
  67451. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67452. sound = scene.soundTracks[i].soundCollection[j];
  67453. if (sound.useCustomAttenuation) {
  67454. sound.updateDistanceFromListener();
  67455. }
  67456. }
  67457. }
  67458. }
  67459. }
  67460. };
  67461. return AudioSceneComponent;
  67462. }());
  67463. BABYLON.AudioSceneComponent = AudioSceneComponent;
  67464. })(BABYLON || (BABYLON = {}));
  67465. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  67466. var BABYLON;
  67467. (function (BABYLON) {
  67468. /**
  67469. * This defines an action helpful to play a defined sound on a triggered action.
  67470. */
  67471. var PlaySoundAction = /** @class */ (function (_super) {
  67472. __extends(PlaySoundAction, _super);
  67473. /**
  67474. * Instantiate the action
  67475. * @param triggerOptions defines the trigger options
  67476. * @param sound defines the sound to play
  67477. * @param condition defines the trigger related conditions
  67478. */
  67479. function PlaySoundAction(triggerOptions, sound, condition) {
  67480. var _this = _super.call(this, triggerOptions, condition) || this;
  67481. _this._sound = sound;
  67482. return _this;
  67483. }
  67484. /** @hidden */
  67485. PlaySoundAction.prototype._prepare = function () {
  67486. };
  67487. /**
  67488. * Execute the action and play the sound.
  67489. */
  67490. PlaySoundAction.prototype.execute = function () {
  67491. if (this._sound !== undefined)
  67492. this._sound.play();
  67493. };
  67494. /**
  67495. * Serializes the actions and its related information.
  67496. * @param parent defines the object to serialize in
  67497. * @returns the serialized object
  67498. */
  67499. PlaySoundAction.prototype.serialize = function (parent) {
  67500. return _super.prototype._serialize.call(this, {
  67501. name: "PlaySoundAction",
  67502. properties: [{ name: "sound", value: this._sound.name }]
  67503. }, parent);
  67504. };
  67505. return PlaySoundAction;
  67506. }(BABYLON.Action));
  67507. BABYLON.PlaySoundAction = PlaySoundAction;
  67508. /**
  67509. * This defines an action helpful to stop a defined sound on a triggered action.
  67510. */
  67511. var StopSoundAction = /** @class */ (function (_super) {
  67512. __extends(StopSoundAction, _super);
  67513. /**
  67514. * Instantiate the action
  67515. * @param triggerOptions defines the trigger options
  67516. * @param sound defines the sound to stop
  67517. * @param condition defines the trigger related conditions
  67518. */
  67519. function StopSoundAction(triggerOptions, sound, condition) {
  67520. var _this = _super.call(this, triggerOptions, condition) || this;
  67521. _this._sound = sound;
  67522. return _this;
  67523. }
  67524. /** @hidden */
  67525. StopSoundAction.prototype._prepare = function () {
  67526. };
  67527. /**
  67528. * Execute the action and stop the sound.
  67529. */
  67530. StopSoundAction.prototype.execute = function () {
  67531. if (this._sound !== undefined)
  67532. this._sound.stop();
  67533. };
  67534. /**
  67535. * Serializes the actions and its related information.
  67536. * @param parent defines the object to serialize in
  67537. * @returns the serialized object
  67538. */
  67539. StopSoundAction.prototype.serialize = function (parent) {
  67540. return _super.prototype._serialize.call(this, {
  67541. name: "StopSoundAction",
  67542. properties: [{ name: "sound", value: this._sound.name }]
  67543. }, parent);
  67544. };
  67545. return StopSoundAction;
  67546. }(BABYLON.Action));
  67547. BABYLON.StopSoundAction = StopSoundAction;
  67548. })(BABYLON || (BABYLON = {}));
  67549. //# sourceMappingURL=babylon.directAudioActions.js.map
  67550. var BABYLON;
  67551. (function (BABYLON) {
  67552. var CubeTexture = /** @class */ (function (_super) {
  67553. __extends(CubeTexture, _super);
  67554. /**
  67555. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  67556. * as prefiltered data.
  67557. * @param rootUrl defines the url of the texture or the root name of the six images
  67558. * @param scene defines the scene the texture is attached to
  67559. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  67560. * @param noMipmap defines if mipmaps should be created or not
  67561. * @param files defines the six files to load for the different faces
  67562. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  67563. * @param onError defines a callback triggered in case of error during load
  67564. * @param format defines the internal format to use for the texture once loaded
  67565. * @param prefiltered defines whether or not the texture is created from prefiltered data
  67566. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  67567. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67568. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67569. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67570. * @return the cube texture
  67571. */
  67572. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  67573. if (extensions === void 0) { extensions = null; }
  67574. if (noMipmap === void 0) { noMipmap = false; }
  67575. if (files === void 0) { files = null; }
  67576. if (onLoad === void 0) { onLoad = null; }
  67577. if (onError === void 0) { onError = null; }
  67578. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67579. if (prefiltered === void 0) { prefiltered = false; }
  67580. if (forcedExtension === void 0) { forcedExtension = null; }
  67581. if (createPolynomials === void 0) { createPolynomials = false; }
  67582. if (lodScale === void 0) { lodScale = 0.8; }
  67583. if (lodOffset === void 0) { lodOffset = 0; }
  67584. var _this = _super.call(this, scene) || this;
  67585. /**
  67586. * Gets or sets the center of the bounding box associated with the cube texture
  67587. * It must define where the camera used to render the texture was set
  67588. */
  67589. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67590. _this._rotationY = 0;
  67591. /** @hidden */
  67592. _this._prefiltered = false;
  67593. _this.name = rootUrl;
  67594. _this.url = rootUrl;
  67595. _this._noMipmap = noMipmap;
  67596. _this.hasAlpha = false;
  67597. _this._format = format;
  67598. _this.isCube = true;
  67599. _this._textureMatrix = BABYLON.Matrix.Identity();
  67600. _this._createPolynomials = createPolynomials;
  67601. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67602. if (!rootUrl && !files) {
  67603. return _this;
  67604. }
  67605. var lastDot = rootUrl.lastIndexOf(".");
  67606. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  67607. var isDDS = (extension === ".dds");
  67608. var isEnv = (extension === ".env");
  67609. if (isEnv) {
  67610. _this.gammaSpace = false;
  67611. _this._prefiltered = false;
  67612. }
  67613. else {
  67614. _this._prefiltered = prefiltered;
  67615. if (prefiltered) {
  67616. _this.gammaSpace = false;
  67617. }
  67618. }
  67619. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  67620. if (!files) {
  67621. if (!isEnv && !isDDS && !extensions) {
  67622. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  67623. }
  67624. files = [];
  67625. if (extensions) {
  67626. for (var index = 0; index < extensions.length; index++) {
  67627. files.push(rootUrl + extensions[index]);
  67628. }
  67629. }
  67630. }
  67631. _this._files = files;
  67632. if (!_this._texture) {
  67633. if (!scene.useDelayedTextureLoading) {
  67634. if (prefiltered) {
  67635. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  67636. }
  67637. else {
  67638. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  67639. }
  67640. }
  67641. else {
  67642. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67643. }
  67644. }
  67645. else if (onLoad) {
  67646. if (_this._texture.isReady) {
  67647. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  67648. }
  67649. else {
  67650. _this._texture.onLoadedObservable.add(onLoad);
  67651. }
  67652. }
  67653. return _this;
  67654. }
  67655. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  67656. get: function () {
  67657. return this._boundingBoxSize;
  67658. },
  67659. /**
  67660. * Gets or sets the size of the bounding box associated with the cube texture
  67661. * When defined, the cubemap will switch to local mode
  67662. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67663. * @example https://www.babylonjs-playground.com/#RNASML
  67664. */
  67665. set: function (value) {
  67666. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67667. return;
  67668. }
  67669. this._boundingBoxSize = value;
  67670. var scene = this.getScene();
  67671. if (scene) {
  67672. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67673. }
  67674. },
  67675. enumerable: true,
  67676. configurable: true
  67677. });
  67678. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  67679. /**
  67680. * Gets texture matrix rotation angle around Y axis radians.
  67681. */
  67682. get: function () {
  67683. return this._rotationY;
  67684. },
  67685. /**
  67686. * Sets texture matrix rotation angle around Y axis in radians.
  67687. */
  67688. set: function (value) {
  67689. this._rotationY = value;
  67690. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  67691. },
  67692. enumerable: true,
  67693. configurable: true
  67694. });
  67695. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  67696. var rootUrlKey = "";
  67697. files.forEach(function (url) { return rootUrlKey += url; });
  67698. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  67699. };
  67700. /**
  67701. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  67702. * @param url defines the url of the prefiltered texture
  67703. * @param scene defines the scene the texture is attached to
  67704. * @param forcedExtension defines the extension of the file if different from the url
  67705. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67706. * @return the prefiltered texture
  67707. */
  67708. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  67709. if (forcedExtension === void 0) { forcedExtension = null; }
  67710. if (createPolynomials === void 0) { createPolynomials = true; }
  67711. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  67712. };
  67713. // Methods
  67714. CubeTexture.prototype.delayLoad = function () {
  67715. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  67716. return;
  67717. }
  67718. var scene = this.getScene();
  67719. if (!scene) {
  67720. return;
  67721. }
  67722. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  67723. this._texture = this._getFromCache(this.url, this._noMipmap);
  67724. if (!this._texture) {
  67725. if (this._prefiltered) {
  67726. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  67727. }
  67728. else {
  67729. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  67730. }
  67731. }
  67732. };
  67733. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  67734. return this._textureMatrix;
  67735. };
  67736. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  67737. this._textureMatrix = value;
  67738. };
  67739. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  67740. var texture = BABYLON.SerializationHelper.Parse(function () {
  67741. var prefiltered = false;
  67742. if (parsedTexture.prefiltered) {
  67743. prefiltered = parsedTexture.prefiltered;
  67744. }
  67745. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  67746. }, parsedTexture, scene);
  67747. // Local Cubemaps
  67748. if (parsedTexture.boundingBoxPosition) {
  67749. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  67750. }
  67751. if (parsedTexture.boundingBoxSize) {
  67752. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  67753. }
  67754. // Animations
  67755. if (parsedTexture.animations) {
  67756. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  67757. var parsedAnimation = parsedTexture.animations[animationIndex];
  67758. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  67759. }
  67760. }
  67761. return texture;
  67762. };
  67763. CubeTexture.prototype.clone = function () {
  67764. var _this = this;
  67765. return BABYLON.SerializationHelper.Clone(function () {
  67766. var scene = _this.getScene();
  67767. if (!scene) {
  67768. return _this;
  67769. }
  67770. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  67771. }, this);
  67772. };
  67773. __decorate([
  67774. BABYLON.serialize("rotationY")
  67775. ], CubeTexture.prototype, "rotationY", null);
  67776. return CubeTexture;
  67777. }(BABYLON.BaseTexture));
  67778. BABYLON.CubeTexture = CubeTexture;
  67779. })(BABYLON || (BABYLON = {}));
  67780. //# sourceMappingURL=babylon.cubeTexture.js.map
  67781. var BABYLON;
  67782. (function (BABYLON) {
  67783. /**
  67784. * Raw cube texture where the raw buffers are passed in
  67785. */
  67786. var RawCubeTexture = /** @class */ (function (_super) {
  67787. __extends(RawCubeTexture, _super);
  67788. /**
  67789. * Creates a cube texture where the raw buffers are passed in.
  67790. * @param scene defines the scene the texture is attached to
  67791. * @param data defines the array of data to use to create each face
  67792. * @param size defines the size of the textures
  67793. * @param format defines the format of the data
  67794. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  67795. * @param generateMipMaps defines if the engine should generate the mip levels
  67796. * @param invertY defines if data must be stored with Y axis inverted
  67797. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  67798. * @param compression defines the compression used (null by default)
  67799. */
  67800. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  67801. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67802. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67803. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67804. if (invertY === void 0) { invertY = false; }
  67805. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67806. if (compression === void 0) { compression = null; }
  67807. var _this = _super.call(this, "", scene) || this;
  67808. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  67809. return _this;
  67810. }
  67811. /**
  67812. * Updates the raw cube texture.
  67813. * @param data defines the data to store
  67814. * @param format defines the data format
  67815. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  67816. * @param invertY defines if data must be stored with Y axis inverted
  67817. * @param compression defines the compression used (null by default)
  67818. * @param level defines which level of the texture to update
  67819. */
  67820. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  67821. if (compression === void 0) { compression = null; }
  67822. if (level === void 0) { level = 0; }
  67823. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  67824. };
  67825. /**
  67826. * Updates a raw cube texture with RGBD encoded data.
  67827. * @param data defines the array of data [mipmap][face] to use to create each face
  67828. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  67829. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67830. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67831. * @returns a promsie that resolves when the operation is complete
  67832. */
  67833. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  67834. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  67835. if (lodScale === void 0) { lodScale = 0.8; }
  67836. if (lodOffset === void 0) { lodOffset = 0; }
  67837. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  67838. };
  67839. /**
  67840. * Clones the raw cube texture.
  67841. * @return a new cube texture
  67842. */
  67843. RawCubeTexture.prototype.clone = function () {
  67844. var _this = this;
  67845. return BABYLON.SerializationHelper.Clone(function () {
  67846. var scene = _this.getScene();
  67847. var internalTexture = _this._texture;
  67848. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  67849. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  67850. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  67851. }
  67852. return texture;
  67853. }, this);
  67854. };
  67855. /** @hidden */
  67856. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  67857. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  67858. internalTexture._bufferViewArrayArray = data;
  67859. internalTexture._lodGenerationScale = lodScale;
  67860. internalTexture._lodGenerationOffset = lodOffset;
  67861. internalTexture._sphericalPolynomial = sphericalPolynomial;
  67862. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  67863. internalTexture.isReady = true;
  67864. });
  67865. };
  67866. return RawCubeTexture;
  67867. }(BABYLON.CubeTexture));
  67868. BABYLON.RawCubeTexture = RawCubeTexture;
  67869. })(BABYLON || (BABYLON = {}));
  67870. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  67871. var BABYLON;
  67872. (function (BABYLON) {
  67873. var RenderTargetTexture = /** @class */ (function (_super) {
  67874. __extends(RenderTargetTexture, _super);
  67875. /**
  67876. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  67877. * or used a shadow, depth texture...
  67878. * @param name The friendly name of the texture
  67879. * @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)
  67880. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  67881. * @param generateMipMaps True if mip maps need to be generated after render.
  67882. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  67883. * @param type The type of the buffer in the RTT (int, half float, float...)
  67884. * @param isCube True if a cube texture needs to be created
  67885. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  67886. * @param generateDepthBuffer True to generate a depth buffer
  67887. * @param generateStencilBuffer True to generate a stencil buffer
  67888. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  67889. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  67890. */
  67891. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  67892. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  67893. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67894. if (isCube === void 0) { isCube = false; }
  67895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67896. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67897. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  67898. if (isMulti === void 0) { isMulti = false; }
  67899. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67900. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  67901. _this.isCube = isCube;
  67902. _this.renderParticles = true;
  67903. _this.renderSprites = false;
  67904. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  67905. _this.ignoreCameraViewport = false;
  67906. // Events
  67907. /**
  67908. * An event triggered when the texture is unbind.
  67909. */
  67910. _this.onBeforeBindObservable = new BABYLON.Observable();
  67911. /**
  67912. * An event triggered when the texture is unbind.
  67913. */
  67914. _this.onAfterUnbindObservable = new BABYLON.Observable();
  67915. /**
  67916. * An event triggered before rendering the texture
  67917. */
  67918. _this.onBeforeRenderObservable = new BABYLON.Observable();
  67919. /**
  67920. * An event triggered after rendering the texture
  67921. */
  67922. _this.onAfterRenderObservable = new BABYLON.Observable();
  67923. /**
  67924. * An event triggered after the texture clear
  67925. */
  67926. _this.onClearObservable = new BABYLON.Observable();
  67927. _this._currentRefreshId = -1;
  67928. _this._refreshRate = 1;
  67929. _this._samples = 1;
  67930. /**
  67931. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  67932. * It must define where the camera used to render the texture is set
  67933. */
  67934. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67935. scene = _this.getScene();
  67936. if (!scene) {
  67937. return _this;
  67938. }
  67939. _this.renderList = new Array();
  67940. _this._engine = scene.getEngine();
  67941. _this.name = name;
  67942. _this.isRenderTarget = true;
  67943. _this._initialSizeParameter = size;
  67944. _this._processSizeParameter(size);
  67945. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  67946. });
  67947. _this._generateMipMaps = generateMipMaps ? true : false;
  67948. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  67949. // Rendering groups
  67950. _this._renderingManager = new BABYLON.RenderingManager(scene);
  67951. _this._renderingManager._useSceneAutoClearSetup = true;
  67952. if (isMulti) {
  67953. return _this;
  67954. }
  67955. _this._renderTargetOptions = {
  67956. generateMipMaps: generateMipMaps,
  67957. type: type,
  67958. format: format,
  67959. samplingMode: samplingMode,
  67960. generateDepthBuffer: generateDepthBuffer,
  67961. generateStencilBuffer: generateStencilBuffer
  67962. };
  67963. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  67964. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67965. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67966. }
  67967. if (isCube) {
  67968. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  67969. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  67970. _this._textureMatrix = BABYLON.Matrix.Identity();
  67971. }
  67972. else {
  67973. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  67974. }
  67975. return _this;
  67976. }
  67977. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  67978. get: function () {
  67979. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  67980. },
  67981. enumerable: true,
  67982. configurable: true
  67983. });
  67984. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  67985. get: function () {
  67986. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  67987. },
  67988. enumerable: true,
  67989. configurable: true
  67990. });
  67991. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  67992. get: function () {
  67993. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  67994. },
  67995. enumerable: true,
  67996. configurable: true
  67997. });
  67998. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  67999. /**
  68000. * Use this list to define the list of mesh you want to render.
  68001. */
  68002. get: function () {
  68003. return this._renderList;
  68004. },
  68005. set: function (value) {
  68006. this._renderList = value;
  68007. if (this._renderList) {
  68008. this._hookArray(this._renderList);
  68009. }
  68010. },
  68011. enumerable: true,
  68012. configurable: true
  68013. });
  68014. RenderTargetTexture.prototype._hookArray = function (array) {
  68015. var _this = this;
  68016. var oldPush = array.push;
  68017. array.push = function () {
  68018. var items = [];
  68019. for (var _i = 0; _i < arguments.length; _i++) {
  68020. items[_i] = arguments[_i];
  68021. }
  68022. var result = oldPush.apply(array, items);
  68023. _this.getScene().meshes.forEach(function (mesh) {
  68024. mesh._markSubMeshesAsLightDirty();
  68025. });
  68026. return result;
  68027. };
  68028. var oldSplice = array.splice;
  68029. array.splice = function (index, deleteCount) {
  68030. var deleted = oldSplice.apply(array, [index, deleteCount]);
  68031. _this.getScene().meshes.forEach(function (mesh) {
  68032. mesh._markSubMeshesAsLightDirty();
  68033. });
  68034. return deleted;
  68035. };
  68036. };
  68037. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  68038. set: function (callback) {
  68039. if (this._onAfterUnbindObserver) {
  68040. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  68041. }
  68042. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  68043. },
  68044. enumerable: true,
  68045. configurable: true
  68046. });
  68047. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  68048. set: function (callback) {
  68049. if (this._onBeforeRenderObserver) {
  68050. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  68051. }
  68052. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  68053. },
  68054. enumerable: true,
  68055. configurable: true
  68056. });
  68057. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  68058. set: function (callback) {
  68059. if (this._onAfterRenderObserver) {
  68060. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  68061. }
  68062. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  68063. },
  68064. enumerable: true,
  68065. configurable: true
  68066. });
  68067. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  68068. set: function (callback) {
  68069. if (this._onClearObserver) {
  68070. this.onClearObservable.remove(this._onClearObserver);
  68071. }
  68072. this._onClearObserver = this.onClearObservable.add(callback);
  68073. },
  68074. enumerable: true,
  68075. configurable: true
  68076. });
  68077. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  68078. get: function () {
  68079. return this._renderTargetOptions;
  68080. },
  68081. enumerable: true,
  68082. configurable: true
  68083. });
  68084. RenderTargetTexture.prototype._onRatioRescale = function () {
  68085. if (this._sizeRatio) {
  68086. this.resize(this._initialSizeParameter);
  68087. }
  68088. };
  68089. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  68090. get: function () {
  68091. return this._boundingBoxSize;
  68092. },
  68093. /**
  68094. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  68095. * When defined, the cubemap will switch to local mode
  68096. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  68097. * @example https://www.babylonjs-playground.com/#RNASML
  68098. */
  68099. set: function (value) {
  68100. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  68101. return;
  68102. }
  68103. this._boundingBoxSize = value;
  68104. var scene = this.getScene();
  68105. if (scene) {
  68106. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  68107. }
  68108. },
  68109. enumerable: true,
  68110. configurable: true
  68111. });
  68112. /**
  68113. * Creates a depth stencil texture.
  68114. * This is only available in WebGL 2 or with the depth texture extension available.
  68115. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  68116. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  68117. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  68118. */
  68119. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  68120. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  68121. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  68122. if (generateStencil === void 0) { generateStencil = false; }
  68123. if (!this.getScene()) {
  68124. return;
  68125. }
  68126. var engine = this.getScene().getEngine();
  68127. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  68128. bilinearFiltering: bilinearFiltering,
  68129. comparisonFunction: comparisonFunction,
  68130. generateStencil: generateStencil,
  68131. isCube: this.isCube
  68132. });
  68133. engine.setFrameBufferDepthStencilTexture(this);
  68134. };
  68135. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  68136. if (size.ratio) {
  68137. this._sizeRatio = size.ratio;
  68138. this._size = {
  68139. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  68140. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  68141. };
  68142. }
  68143. else {
  68144. this._size = size;
  68145. }
  68146. };
  68147. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  68148. get: function () {
  68149. return this._samples;
  68150. },
  68151. set: function (value) {
  68152. if (this._samples === value) {
  68153. return;
  68154. }
  68155. var scene = this.getScene();
  68156. if (!scene) {
  68157. return;
  68158. }
  68159. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  68160. },
  68161. enumerable: true,
  68162. configurable: true
  68163. });
  68164. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  68165. this._currentRefreshId = -1;
  68166. };
  68167. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  68168. get: function () {
  68169. return this._refreshRate;
  68170. },
  68171. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  68172. set: function (value) {
  68173. this._refreshRate = value;
  68174. this.resetRefreshCounter();
  68175. },
  68176. enumerable: true,
  68177. configurable: true
  68178. });
  68179. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  68180. if (!this._postProcessManager) {
  68181. var scene = this.getScene();
  68182. if (!scene) {
  68183. return;
  68184. }
  68185. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  68186. this._postProcesses = new Array();
  68187. }
  68188. this._postProcesses.push(postProcess);
  68189. this._postProcesses[0].autoClear = false;
  68190. };
  68191. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  68192. if (!this._postProcesses) {
  68193. return;
  68194. }
  68195. if (dispose) {
  68196. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  68197. var postProcess = _a[_i];
  68198. postProcess.dispose();
  68199. }
  68200. }
  68201. this._postProcesses = [];
  68202. };
  68203. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  68204. if (!this._postProcesses) {
  68205. return;
  68206. }
  68207. var index = this._postProcesses.indexOf(postProcess);
  68208. if (index === -1) {
  68209. return;
  68210. }
  68211. this._postProcesses.splice(index, 1);
  68212. if (this._postProcesses.length > 0) {
  68213. this._postProcesses[0].autoClear = false;
  68214. }
  68215. };
  68216. /** @hidden */
  68217. RenderTargetTexture.prototype._shouldRender = function () {
  68218. if (this._currentRefreshId === -1) { // At least render once
  68219. this._currentRefreshId = 1;
  68220. return true;
  68221. }
  68222. if (this.refreshRate === this._currentRefreshId) {
  68223. this._currentRefreshId = 1;
  68224. return true;
  68225. }
  68226. this._currentRefreshId++;
  68227. return false;
  68228. };
  68229. RenderTargetTexture.prototype.getRenderSize = function () {
  68230. if (this._size.width) {
  68231. return this._size.width;
  68232. }
  68233. return this._size;
  68234. };
  68235. RenderTargetTexture.prototype.getRenderWidth = function () {
  68236. if (this._size.width) {
  68237. return this._size.width;
  68238. }
  68239. return this._size;
  68240. };
  68241. RenderTargetTexture.prototype.getRenderHeight = function () {
  68242. if (this._size.width) {
  68243. return this._size.height;
  68244. }
  68245. return this._size;
  68246. };
  68247. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  68248. get: function () {
  68249. return true;
  68250. },
  68251. enumerable: true,
  68252. configurable: true
  68253. });
  68254. RenderTargetTexture.prototype.scale = function (ratio) {
  68255. var newSize = this.getRenderSize() * ratio;
  68256. this.resize(newSize);
  68257. };
  68258. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  68259. if (this.isCube) {
  68260. return this._textureMatrix;
  68261. }
  68262. return _super.prototype.getReflectionTextureMatrix.call(this);
  68263. };
  68264. RenderTargetTexture.prototype.resize = function (size) {
  68265. this.releaseInternalTexture();
  68266. var scene = this.getScene();
  68267. if (!scene) {
  68268. return;
  68269. }
  68270. this._processSizeParameter(size);
  68271. if (this.isCube) {
  68272. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  68273. }
  68274. else {
  68275. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  68276. }
  68277. };
  68278. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  68279. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  68280. if (dumpForDebug === void 0) { dumpForDebug = false; }
  68281. var scene = this.getScene();
  68282. if (!scene) {
  68283. return;
  68284. }
  68285. var engine = scene.getEngine();
  68286. if (this.useCameraPostProcesses !== undefined) {
  68287. useCameraPostProcess = this.useCameraPostProcesses;
  68288. }
  68289. if (this._waitingRenderList) {
  68290. this.renderList = [];
  68291. for (var index = 0; index < this._waitingRenderList.length; index++) {
  68292. var id = this._waitingRenderList[index];
  68293. var mesh_1 = scene.getMeshByID(id);
  68294. if (mesh_1) {
  68295. this.renderList.push(mesh_1);
  68296. }
  68297. }
  68298. delete this._waitingRenderList;
  68299. }
  68300. // Is predicate defined?
  68301. if (this.renderListPredicate) {
  68302. if (this.renderList) {
  68303. this.renderList.splice(0); // Clear previous renderList
  68304. }
  68305. else {
  68306. this.renderList = [];
  68307. }
  68308. var scene = this.getScene();
  68309. if (!scene) {
  68310. return;
  68311. }
  68312. var sceneMeshes = scene.meshes;
  68313. for (var index = 0; index < sceneMeshes.length; index++) {
  68314. var mesh = sceneMeshes[index];
  68315. if (this.renderListPredicate(mesh)) {
  68316. this.renderList.push(mesh);
  68317. }
  68318. }
  68319. }
  68320. this.onBeforeBindObservable.notifyObservers(this);
  68321. // Set custom projection.
  68322. // Needs to be before binding to prevent changing the aspect ratio.
  68323. var camera;
  68324. if (this.activeCamera) {
  68325. camera = this.activeCamera;
  68326. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  68327. if (this.activeCamera !== scene.activeCamera) {
  68328. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  68329. }
  68330. }
  68331. else {
  68332. camera = scene.activeCamera;
  68333. if (camera) {
  68334. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  68335. }
  68336. }
  68337. // Prepare renderingManager
  68338. this._renderingManager.reset();
  68339. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  68340. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  68341. var sceneRenderId = scene.getRenderId();
  68342. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  68343. var mesh = currentRenderList[meshIndex];
  68344. if (mesh) {
  68345. if (!mesh.isReady(this.refreshRate === 0)) {
  68346. this.resetRefreshCounter();
  68347. continue;
  68348. }
  68349. mesh._preActivateForIntermediateRendering(sceneRenderId);
  68350. var isMasked = void 0;
  68351. if (!this.renderList && camera) {
  68352. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  68353. }
  68354. else {
  68355. isMasked = false;
  68356. }
  68357. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  68358. mesh._activate(sceneRenderId);
  68359. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  68360. var subMesh = mesh.subMeshes[subIndex];
  68361. scene._activeIndices.addCount(subMesh.indexCount, false);
  68362. this._renderingManager.dispatch(subMesh, mesh);
  68363. }
  68364. }
  68365. }
  68366. }
  68367. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  68368. var particleSystem = scene.particleSystems[particleIndex];
  68369. var emitter = particleSystem.emitter;
  68370. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  68371. continue;
  68372. }
  68373. if (currentRenderList.indexOf(emitter) >= 0) {
  68374. this._renderingManager.dispatchParticles(particleSystem);
  68375. }
  68376. }
  68377. if (this.isCube) {
  68378. for (var face = 0; face < 6; face++) {
  68379. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  68380. scene.incrementRenderId();
  68381. scene.resetCachedMaterial();
  68382. }
  68383. }
  68384. else {
  68385. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  68386. }
  68387. this.onAfterUnbindObservable.notifyObservers(this);
  68388. if (scene.activeCamera) {
  68389. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  68390. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  68391. }
  68392. engine.setViewport(scene.activeCamera.viewport);
  68393. }
  68394. scene.resetCachedMaterial();
  68395. };
  68396. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  68397. var minimum = 128;
  68398. var x = renderDimension * scale;
  68399. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  68400. // Ensure we don't exceed the render dimension (while staying POT)
  68401. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  68402. };
  68403. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  68404. var _this = this;
  68405. if (!this._texture) {
  68406. return;
  68407. }
  68408. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  68409. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  68410. });
  68411. };
  68412. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  68413. var scene = this.getScene();
  68414. if (!scene) {
  68415. return;
  68416. }
  68417. var engine = scene.getEngine();
  68418. if (!this._texture) {
  68419. return;
  68420. }
  68421. // Bind
  68422. if (this._postProcessManager) {
  68423. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  68424. }
  68425. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  68426. if (this._texture) {
  68427. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  68428. }
  68429. }
  68430. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  68431. // Clear
  68432. if (this.onClearObservable.hasObservers()) {
  68433. this.onClearObservable.notifyObservers(engine);
  68434. }
  68435. else {
  68436. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  68437. }
  68438. if (!this._doNotChangeAspectRatio) {
  68439. scene.updateTransformMatrix(true);
  68440. }
  68441. // Render
  68442. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  68443. if (this._postProcessManager) {
  68444. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  68445. }
  68446. else if (useCameraPostProcess) {
  68447. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  68448. }
  68449. if (!this._doNotChangeAspectRatio) {
  68450. scene.updateTransformMatrix(true);
  68451. }
  68452. // Dump ?
  68453. if (dumpForDebug) {
  68454. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  68455. }
  68456. // Unbind
  68457. if (!this.isCube || faceIndex === 5) {
  68458. if (this.isCube) {
  68459. if (faceIndex === 5) {
  68460. engine.generateMipMapsForCubemap(this._texture);
  68461. }
  68462. }
  68463. this.unbindFrameBuffer(engine, faceIndex);
  68464. }
  68465. else {
  68466. this.onAfterRenderObservable.notifyObservers(faceIndex);
  68467. }
  68468. };
  68469. /**
  68470. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  68471. * This allowed control for front to back rendering or reversly depending of the special needs.
  68472. *
  68473. * @param renderingGroupId The rendering group id corresponding to its index
  68474. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  68475. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  68476. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  68477. */
  68478. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  68479. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  68480. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  68481. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  68482. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  68483. };
  68484. /**
  68485. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  68486. *
  68487. * @param renderingGroupId The rendering group id corresponding to its index
  68488. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  68489. */
  68490. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  68491. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  68492. this._renderingManager._useSceneAutoClearSetup = false;
  68493. };
  68494. RenderTargetTexture.prototype.clone = function () {
  68495. var textureSize = this.getSize();
  68496. 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);
  68497. // Base texture
  68498. newTexture.hasAlpha = this.hasAlpha;
  68499. newTexture.level = this.level;
  68500. // RenderTarget Texture
  68501. newTexture.coordinatesMode = this.coordinatesMode;
  68502. if (this.renderList) {
  68503. newTexture.renderList = this.renderList.slice(0);
  68504. }
  68505. return newTexture;
  68506. };
  68507. RenderTargetTexture.prototype.serialize = function () {
  68508. if (!this.name) {
  68509. return null;
  68510. }
  68511. var serializationObject = _super.prototype.serialize.call(this);
  68512. serializationObject.renderTargetSize = this.getRenderSize();
  68513. serializationObject.renderList = [];
  68514. if (this.renderList) {
  68515. for (var index = 0; index < this.renderList.length; index++) {
  68516. serializationObject.renderList.push(this.renderList[index].id);
  68517. }
  68518. }
  68519. return serializationObject;
  68520. };
  68521. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  68522. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  68523. var objBuffer = this.getInternalTexture();
  68524. var scene = this.getScene();
  68525. if (objBuffer && scene) {
  68526. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  68527. }
  68528. };
  68529. RenderTargetTexture.prototype.dispose = function () {
  68530. if (this._postProcessManager) {
  68531. this._postProcessManager.dispose();
  68532. this._postProcessManager = null;
  68533. }
  68534. this.clearPostProcesses(true);
  68535. if (this._resizeObserver) {
  68536. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  68537. this._resizeObserver = null;
  68538. }
  68539. this.renderList = null;
  68540. // Remove from custom render targets
  68541. var scene = this.getScene();
  68542. if (!scene) {
  68543. return;
  68544. }
  68545. var index = scene.customRenderTargets.indexOf(this);
  68546. if (index >= 0) {
  68547. scene.customRenderTargets.splice(index, 1);
  68548. }
  68549. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  68550. var camera = _a[_i];
  68551. index = camera.customRenderTargets.indexOf(this);
  68552. if (index >= 0) {
  68553. camera.customRenderTargets.splice(index, 1);
  68554. }
  68555. }
  68556. _super.prototype.dispose.call(this);
  68557. };
  68558. /** @hidden */
  68559. RenderTargetTexture.prototype._rebuild = function () {
  68560. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68561. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68562. }
  68563. if (this._postProcessManager) {
  68564. this._postProcessManager._rebuild();
  68565. }
  68566. };
  68567. /**
  68568. * Clear the info related to rendering groups preventing retention point in material dispose.
  68569. */
  68570. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  68571. if (this._renderingManager) {
  68572. this._renderingManager.freeRenderingGroups();
  68573. }
  68574. };
  68575. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  68576. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  68577. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  68578. return RenderTargetTexture;
  68579. }(BABYLON.Texture));
  68580. BABYLON.RenderTargetTexture = RenderTargetTexture;
  68581. })(BABYLON || (BABYLON = {}));
  68582. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  68583. var BABYLON;
  68584. (function (BABYLON) {
  68585. ;
  68586. var MultiRenderTarget = /** @class */ (function (_super) {
  68587. __extends(MultiRenderTarget, _super);
  68588. function MultiRenderTarget(name, size, count, scene, options) {
  68589. var _this = this;
  68590. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  68591. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  68592. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  68593. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  68594. _this._engine = scene.getEngine();
  68595. if (!_this.isSupported) {
  68596. _this.dispose();
  68597. return;
  68598. }
  68599. var types = [];
  68600. var samplingModes = [];
  68601. for (var i = 0; i < count; i++) {
  68602. if (options && options.types && options.types[i] !== undefined) {
  68603. types.push(options.types[i]);
  68604. }
  68605. else {
  68606. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68607. }
  68608. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  68609. samplingModes.push(options.samplingModes[i]);
  68610. }
  68611. else {
  68612. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68613. }
  68614. }
  68615. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  68616. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  68617. _this._size = size;
  68618. _this._multiRenderTargetOptions = {
  68619. samplingModes: samplingModes,
  68620. generateMipMaps: generateMipMaps,
  68621. generateDepthBuffer: generateDepthBuffer,
  68622. generateStencilBuffer: generateStencilBuffer,
  68623. generateDepthTexture: generateDepthTexture,
  68624. types: types,
  68625. textureCount: count
  68626. };
  68627. _this._createInternalTextures();
  68628. _this._createTextures();
  68629. return _this;
  68630. }
  68631. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  68632. get: function () {
  68633. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  68634. },
  68635. enumerable: true,
  68636. configurable: true
  68637. });
  68638. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  68639. get: function () {
  68640. return this._textures;
  68641. },
  68642. enumerable: true,
  68643. configurable: true
  68644. });
  68645. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  68646. get: function () {
  68647. return this._textures[this._textures.length - 1];
  68648. },
  68649. enumerable: true,
  68650. configurable: true
  68651. });
  68652. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  68653. set: function (wrap) {
  68654. if (this._textures) {
  68655. for (var i = 0; i < this._textures.length; i++) {
  68656. this._textures[i].wrapU = wrap;
  68657. }
  68658. }
  68659. },
  68660. enumerable: true,
  68661. configurable: true
  68662. });
  68663. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  68664. set: function (wrap) {
  68665. if (this._textures) {
  68666. for (var i = 0; i < this._textures.length; i++) {
  68667. this._textures[i].wrapV = wrap;
  68668. }
  68669. }
  68670. },
  68671. enumerable: true,
  68672. configurable: true
  68673. });
  68674. /** @hidden */
  68675. MultiRenderTarget.prototype._rebuild = function () {
  68676. this.releaseInternalTextures();
  68677. this._createInternalTextures();
  68678. for (var i = 0; i < this._internalTextures.length; i++) {
  68679. var texture = this._textures[i];
  68680. texture._texture = this._internalTextures[i];
  68681. }
  68682. // Keeps references to frame buffer and stencil/depth buffer
  68683. this._texture = this._internalTextures[0];
  68684. };
  68685. MultiRenderTarget.prototype._createInternalTextures = function () {
  68686. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  68687. };
  68688. MultiRenderTarget.prototype._createTextures = function () {
  68689. this._textures = [];
  68690. for (var i = 0; i < this._internalTextures.length; i++) {
  68691. var texture = new BABYLON.Texture(null, this.getScene());
  68692. texture._texture = this._internalTextures[i];
  68693. this._textures.push(texture);
  68694. }
  68695. // Keeps references to frame buffer and stencil/depth buffer
  68696. this._texture = this._internalTextures[0];
  68697. };
  68698. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  68699. get: function () {
  68700. return this._samples;
  68701. },
  68702. set: function (value) {
  68703. if (this._samples === value) {
  68704. return;
  68705. }
  68706. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  68707. },
  68708. enumerable: true,
  68709. configurable: true
  68710. });
  68711. MultiRenderTarget.prototype.resize = function (size) {
  68712. this.releaseInternalTextures();
  68713. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  68714. this._createInternalTextures();
  68715. };
  68716. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  68717. var _this = this;
  68718. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  68719. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  68720. });
  68721. };
  68722. MultiRenderTarget.prototype.dispose = function () {
  68723. this.releaseInternalTextures();
  68724. _super.prototype.dispose.call(this);
  68725. };
  68726. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  68727. if (!this._internalTextures) {
  68728. return;
  68729. }
  68730. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  68731. if (this._internalTextures[i] !== undefined) {
  68732. this._internalTextures[i].dispose();
  68733. this._internalTextures.splice(i, 1);
  68734. }
  68735. }
  68736. };
  68737. return MultiRenderTarget;
  68738. }(BABYLON.RenderTargetTexture));
  68739. BABYLON.MultiRenderTarget = MultiRenderTarget;
  68740. })(BABYLON || (BABYLON = {}));
  68741. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  68742. var BABYLON;
  68743. (function (BABYLON) {
  68744. var MirrorTexture = /** @class */ (function (_super) {
  68745. __extends(MirrorTexture, _super);
  68746. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  68747. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68748. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68749. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  68750. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  68751. _this.scene = scene;
  68752. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  68753. _this._transformMatrix = BABYLON.Matrix.Zero();
  68754. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  68755. _this._adaptiveBlurKernel = 0;
  68756. _this._blurKernelX = 0;
  68757. _this._blurKernelY = 0;
  68758. _this._blurRatio = 1.0;
  68759. _this.ignoreCameraViewport = true;
  68760. _this._updateGammaSpace();
  68761. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  68762. _this._updateGammaSpace;
  68763. });
  68764. _this.onBeforeRenderObservable.add(function () {
  68765. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  68766. _this._savedViewMatrix = scene.getViewMatrix();
  68767. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  68768. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  68769. scene.clipPlane = _this.mirrorPlane;
  68770. scene.getEngine().cullBackFaces = false;
  68771. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  68772. });
  68773. _this.onAfterRenderObservable.add(function () {
  68774. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  68775. scene.getEngine().cullBackFaces = true;
  68776. scene._mirroredCameraPosition = null;
  68777. delete scene.clipPlane;
  68778. });
  68779. return _this;
  68780. }
  68781. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  68782. get: function () {
  68783. return this._blurRatio;
  68784. },
  68785. set: function (value) {
  68786. if (this._blurRatio === value) {
  68787. return;
  68788. }
  68789. this._blurRatio = value;
  68790. this._preparePostProcesses();
  68791. },
  68792. enumerable: true,
  68793. configurable: true
  68794. });
  68795. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  68796. set: function (value) {
  68797. this._adaptiveBlurKernel = value;
  68798. this._autoComputeBlurKernel();
  68799. },
  68800. enumerable: true,
  68801. configurable: true
  68802. });
  68803. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  68804. set: function (value) {
  68805. this.blurKernelX = value;
  68806. this.blurKernelY = value;
  68807. },
  68808. enumerable: true,
  68809. configurable: true
  68810. });
  68811. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  68812. get: function () {
  68813. return this._blurKernelX;
  68814. },
  68815. set: function (value) {
  68816. if (this._blurKernelX === value) {
  68817. return;
  68818. }
  68819. this._blurKernelX = value;
  68820. this._preparePostProcesses();
  68821. },
  68822. enumerable: true,
  68823. configurable: true
  68824. });
  68825. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  68826. get: function () {
  68827. return this._blurKernelY;
  68828. },
  68829. set: function (value) {
  68830. if (this._blurKernelY === value) {
  68831. return;
  68832. }
  68833. this._blurKernelY = value;
  68834. this._preparePostProcesses();
  68835. },
  68836. enumerable: true,
  68837. configurable: true
  68838. });
  68839. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  68840. var engine = this.getScene().getEngine();
  68841. var dw = this.getRenderWidth() / engine.getRenderWidth();
  68842. var dh = this.getRenderHeight() / engine.getRenderHeight();
  68843. this.blurKernelX = this._adaptiveBlurKernel * dw;
  68844. this.blurKernelY = this._adaptiveBlurKernel * dh;
  68845. };
  68846. MirrorTexture.prototype._onRatioRescale = function () {
  68847. if (this._sizeRatio) {
  68848. this.resize(this._initialSizeParameter);
  68849. if (!this._adaptiveBlurKernel) {
  68850. this._preparePostProcesses();
  68851. }
  68852. }
  68853. if (this._adaptiveBlurKernel) {
  68854. this._autoComputeBlurKernel();
  68855. }
  68856. };
  68857. MirrorTexture.prototype._updateGammaSpace = function () {
  68858. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  68859. };
  68860. MirrorTexture.prototype._preparePostProcesses = function () {
  68861. this.clearPostProcesses(true);
  68862. if (this._blurKernelX && this._blurKernelY) {
  68863. var engine = this.getScene().getEngine();
  68864. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68865. 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);
  68866. this._blurX.autoClear = false;
  68867. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  68868. this._blurX.inputTexture = this._texture;
  68869. }
  68870. else {
  68871. this._blurX.alwaysForcePOT = true;
  68872. }
  68873. 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);
  68874. this._blurY.autoClear = false;
  68875. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  68876. this.addPostProcess(this._blurX);
  68877. this.addPostProcess(this._blurY);
  68878. }
  68879. else {
  68880. if (this._blurY) {
  68881. this.removePostProcess(this._blurY);
  68882. this._blurY.dispose();
  68883. this._blurY = null;
  68884. }
  68885. if (this._blurX) {
  68886. this.removePostProcess(this._blurX);
  68887. this._blurX.dispose();
  68888. this._blurX = null;
  68889. }
  68890. }
  68891. };
  68892. MirrorTexture.prototype.clone = function () {
  68893. var scene = this.getScene();
  68894. if (!scene) {
  68895. return this;
  68896. }
  68897. var textureSize = this.getSize();
  68898. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  68899. // Base texture
  68900. newTexture.hasAlpha = this.hasAlpha;
  68901. newTexture.level = this.level;
  68902. // Mirror Texture
  68903. newTexture.mirrorPlane = this.mirrorPlane.clone();
  68904. if (this.renderList) {
  68905. newTexture.renderList = this.renderList.slice(0);
  68906. }
  68907. return newTexture;
  68908. };
  68909. MirrorTexture.prototype.serialize = function () {
  68910. if (!this.name) {
  68911. return null;
  68912. }
  68913. var serializationObject = _super.prototype.serialize.call(this);
  68914. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  68915. return serializationObject;
  68916. };
  68917. MirrorTexture.prototype.dispose = function () {
  68918. _super.prototype.dispose.call(this);
  68919. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  68920. };
  68921. return MirrorTexture;
  68922. }(BABYLON.RenderTargetTexture));
  68923. BABYLON.MirrorTexture = MirrorTexture;
  68924. })(BABYLON || (BABYLON = {}));
  68925. //# sourceMappingURL=babylon.mirrorTexture.js.map
  68926. var BABYLON;
  68927. (function (BABYLON) {
  68928. /**
  68929. * Creates a refraction texture used by refraction channel of the standard material.
  68930. * @param name the texture name
  68931. * @param size size of the underlying texture
  68932. * @param scene root scene
  68933. */
  68934. var RefractionTexture = /** @class */ (function (_super) {
  68935. __extends(RefractionTexture, _super);
  68936. function RefractionTexture(name, size, scene, generateMipMaps) {
  68937. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  68938. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  68939. _this.depth = 2.0;
  68940. _this.onBeforeRenderObservable.add(function () {
  68941. scene.clipPlane = _this.refractionPlane;
  68942. });
  68943. _this.onAfterRenderObservable.add(function () {
  68944. delete scene.clipPlane;
  68945. });
  68946. return _this;
  68947. }
  68948. RefractionTexture.prototype.clone = function () {
  68949. var scene = this.getScene();
  68950. if (!scene) {
  68951. return this;
  68952. }
  68953. var textureSize = this.getSize();
  68954. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  68955. // Base texture
  68956. newTexture.hasAlpha = this.hasAlpha;
  68957. newTexture.level = this.level;
  68958. // Refraction Texture
  68959. newTexture.refractionPlane = this.refractionPlane.clone();
  68960. if (this.renderList) {
  68961. newTexture.renderList = this.renderList.slice(0);
  68962. }
  68963. newTexture.depth = this.depth;
  68964. return newTexture;
  68965. };
  68966. RefractionTexture.prototype.serialize = function () {
  68967. if (!this.name) {
  68968. return null;
  68969. }
  68970. var serializationObject = _super.prototype.serialize.call(this);
  68971. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  68972. serializationObject.depth = this.depth;
  68973. return serializationObject;
  68974. };
  68975. return RefractionTexture;
  68976. }(BABYLON.RenderTargetTexture));
  68977. BABYLON.RefractionTexture = RefractionTexture;
  68978. })(BABYLON || (BABYLON = {}));
  68979. //# sourceMappingURL=babylon.refractionTexture.js.map
  68980. var BABYLON;
  68981. (function (BABYLON) {
  68982. /**
  68983. * A class extending {BABYLON.Texture} allowing drawing on a texture
  68984. * @see http://doc.babylonjs.com/how_to/dynamictexture
  68985. */
  68986. var DynamicTexture = /** @class */ (function (_super) {
  68987. __extends(DynamicTexture, _super);
  68988. /**
  68989. * Creates a {BABYLON.DynamicTexture}
  68990. * @param name defines the name of the texture
  68991. * @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
  68992. * @param scene defines the scene where you want the texture
  68993. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  68994. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  68995. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  68996. */
  68997. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  68998. if (scene === void 0) { scene = null; }
  68999. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69000. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69001. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  69002. _this.name = name;
  69003. _this._engine = _this.getScene().getEngine();
  69004. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69005. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69006. _this._generateMipMaps = generateMipMaps;
  69007. if (options.getContext) {
  69008. _this._canvas = options;
  69009. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  69010. }
  69011. else {
  69012. _this._canvas = document.createElement("canvas");
  69013. if (options.width || options.width === 0) {
  69014. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  69015. }
  69016. else {
  69017. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  69018. }
  69019. }
  69020. var textureSize = _this.getSize();
  69021. _this._canvas.width = textureSize.width;
  69022. _this._canvas.height = textureSize.height;
  69023. _this._context = _this._canvas.getContext("2d");
  69024. return _this;
  69025. }
  69026. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  69027. /**
  69028. * Gets the current state of canRescale
  69029. */
  69030. get: function () {
  69031. return true;
  69032. },
  69033. enumerable: true,
  69034. configurable: true
  69035. });
  69036. DynamicTexture.prototype._recreate = function (textureSize) {
  69037. this._canvas.width = textureSize.width;
  69038. this._canvas.height = textureSize.height;
  69039. this.releaseInternalTexture();
  69040. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  69041. };
  69042. /**
  69043. * Scales the texture
  69044. * @param ratio the scale factor to apply to both width and height
  69045. */
  69046. DynamicTexture.prototype.scale = function (ratio) {
  69047. var textureSize = this.getSize();
  69048. textureSize.width *= ratio;
  69049. textureSize.height *= ratio;
  69050. this._recreate(textureSize);
  69051. };
  69052. /**
  69053. * Resizes the texture
  69054. * @param width the new width
  69055. * @param height the new height
  69056. */
  69057. DynamicTexture.prototype.scaleTo = function (width, height) {
  69058. var textureSize = this.getSize();
  69059. textureSize.width = width;
  69060. textureSize.height = height;
  69061. this._recreate(textureSize);
  69062. };
  69063. /**
  69064. * Gets the context of the canvas used by the texture
  69065. * @returns the canvas context of the dynamic texture
  69066. */
  69067. DynamicTexture.prototype.getContext = function () {
  69068. return this._context;
  69069. };
  69070. /**
  69071. * Clears the texture
  69072. */
  69073. DynamicTexture.prototype.clear = function () {
  69074. var size = this.getSize();
  69075. this._context.fillRect(0, 0, size.width, size.height);
  69076. };
  69077. /**
  69078. * Updates the texture
  69079. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  69080. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  69081. */
  69082. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  69083. if (premulAlpha === void 0) { premulAlpha = false; }
  69084. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  69085. };
  69086. /**
  69087. * Draws text onto the texture
  69088. * @param text defines the text to be drawn
  69089. * @param x defines the placement of the text from the left
  69090. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  69091. * @param font defines the font to be used with font-style, font-size, font-name
  69092. * @param color defines the color used for the text
  69093. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  69094. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  69095. * @param update defines whether texture is immediately update (default is true)
  69096. */
  69097. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  69098. if (update === void 0) { update = true; }
  69099. var size = this.getSize();
  69100. if (clearColor) {
  69101. this._context.fillStyle = clearColor;
  69102. this._context.fillRect(0, 0, size.width, size.height);
  69103. }
  69104. this._context.font = font;
  69105. if (x === null || x === undefined) {
  69106. var textSize = this._context.measureText(text);
  69107. x = (size.width - textSize.width) / 2;
  69108. }
  69109. if (y === null || y === undefined) {
  69110. var fontSize = parseInt((font.replace(/\D/g, '')));
  69111. y = (size.height / 2) + (fontSize / 3.65);
  69112. }
  69113. this._context.fillStyle = color;
  69114. this._context.fillText(text, x, y);
  69115. if (update) {
  69116. this.update(invertY);
  69117. }
  69118. };
  69119. /**
  69120. * Clones the texture
  69121. * @returns the clone of the texture.
  69122. */
  69123. DynamicTexture.prototype.clone = function () {
  69124. var scene = this.getScene();
  69125. if (!scene) {
  69126. return this;
  69127. }
  69128. var textureSize = this.getSize();
  69129. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  69130. // Base texture
  69131. newTexture.hasAlpha = this.hasAlpha;
  69132. newTexture.level = this.level;
  69133. // Dynamic Texture
  69134. newTexture.wrapU = this.wrapU;
  69135. newTexture.wrapV = this.wrapV;
  69136. return newTexture;
  69137. };
  69138. /**
  69139. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  69140. * @returns a serialized dynamic texture object
  69141. */
  69142. DynamicTexture.prototype.serialize = function () {
  69143. var scene = this.getScene();
  69144. if (scene && !scene.isReady()) {
  69145. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  69146. }
  69147. var serializationObject = _super.prototype.serialize.call(this);
  69148. serializationObject.base64String = this._canvas.toDataURL();
  69149. serializationObject.invertY = this._invertY;
  69150. serializationObject.samplingMode = this.samplingMode;
  69151. return serializationObject;
  69152. };
  69153. /** @hidden */
  69154. DynamicTexture.prototype._rebuild = function () {
  69155. this.update();
  69156. };
  69157. return DynamicTexture;
  69158. }(BABYLON.Texture));
  69159. BABYLON.DynamicTexture = DynamicTexture;
  69160. })(BABYLON || (BABYLON = {}));
  69161. //# sourceMappingURL=babylon.dynamicTexture.js.map
  69162. var BABYLON;
  69163. (function (BABYLON) {
  69164. var VideoTexture = /** @class */ (function (_super) {
  69165. __extends(VideoTexture, _super);
  69166. /**
  69167. * Creates a video texture.
  69168. * Sample : https://doc.babylonjs.com/how_to/video_texture
  69169. * @param {string | null} name optional name, will detect from video source, if not defined
  69170. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  69171. * @param {BABYLON.Scene} scene is obviously the current scene.
  69172. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  69173. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  69174. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  69175. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  69176. */
  69177. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  69178. if (generateMipMaps === void 0) { generateMipMaps = false; }
  69179. if (invertY === void 0) { invertY = false; }
  69180. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69181. if (settings === void 0) { settings = {
  69182. autoPlay: true,
  69183. loop: true,
  69184. autoUpdateTexture: true,
  69185. }; }
  69186. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  69187. _this._onUserActionRequestedObservable = null;
  69188. _this._stillImageCaptured = false;
  69189. _this._poster = false;
  69190. _this._createInternalTexture = function () {
  69191. if (_this._texture != null) {
  69192. if (_this._poster) {
  69193. _this._texture.dispose();
  69194. _this._poster = false;
  69195. }
  69196. else {
  69197. return;
  69198. }
  69199. }
  69200. if (!_this._engine.needPOTTextures ||
  69201. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  69202. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  69203. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  69204. }
  69205. else {
  69206. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69207. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69208. _this._generateMipMaps = false;
  69209. }
  69210. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  69211. if (!_this.video.autoplay) {
  69212. var oldHandler_1 = _this.video.onplaying;
  69213. var error_1 = false;
  69214. _this.video.onplaying = function () {
  69215. _this.video.onplaying = oldHandler_1;
  69216. _this._texture.isReady = true;
  69217. _this._updateInternalTexture();
  69218. if (!error_1) {
  69219. _this.video.pause();
  69220. }
  69221. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  69222. _this.onLoadObservable.notifyObservers(_this);
  69223. }
  69224. };
  69225. var playing = _this.video.play();
  69226. if (playing) {
  69227. playing.then(function () {
  69228. // Everything is good.
  69229. })
  69230. .catch(function () {
  69231. error_1 = true;
  69232. // On Chrome for instance, new policies might prevent playing without user interaction.
  69233. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  69234. _this._onUserActionRequestedObservable.notifyObservers(_this);
  69235. }
  69236. });
  69237. }
  69238. else {
  69239. _this.video.onplaying = oldHandler_1;
  69240. _this._texture.isReady = true;
  69241. _this._updateInternalTexture();
  69242. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  69243. _this.onLoadObservable.notifyObservers(_this);
  69244. }
  69245. }
  69246. }
  69247. else {
  69248. _this._texture.isReady = true;
  69249. _this._updateInternalTexture();
  69250. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  69251. _this.onLoadObservable.notifyObservers(_this);
  69252. }
  69253. }
  69254. };
  69255. _this.reset = function () {
  69256. if (_this._texture == null) {
  69257. return;
  69258. }
  69259. if (!_this._poster) {
  69260. _this._texture.dispose();
  69261. _this._texture = null;
  69262. }
  69263. };
  69264. _this._updateInternalTexture = function (e) {
  69265. if (_this._texture == null || !_this._texture.isReady) {
  69266. return;
  69267. }
  69268. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  69269. return;
  69270. }
  69271. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  69272. };
  69273. _this._engine = _this.getScene().getEngine();
  69274. _this._generateMipMaps = generateMipMaps;
  69275. _this._samplingMode = samplingMode;
  69276. _this.autoUpdateTexture = settings.autoUpdateTexture;
  69277. _this.name = name || _this._getName(src);
  69278. _this.video = _this._getVideo(src);
  69279. if (settings.poster) {
  69280. _this.video.poster = settings.poster;
  69281. }
  69282. if (settings.autoPlay !== undefined) {
  69283. _this.video.autoplay = settings.autoPlay;
  69284. }
  69285. if (settings.loop !== undefined) {
  69286. _this.video.loop = settings.loop;
  69287. }
  69288. _this.video.setAttribute("playsinline", "");
  69289. _this.video.addEventListener("canplay", _this._createInternalTexture);
  69290. _this.video.addEventListener("paused", _this._updateInternalTexture);
  69291. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  69292. _this.video.addEventListener("emptied", _this.reset);
  69293. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  69294. _this._createInternalTexture();
  69295. }
  69296. if (settings.poster) {
  69297. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  69298. _this._poster = true;
  69299. }
  69300. return _this;
  69301. }
  69302. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  69303. get: function () {
  69304. if (!this._onUserActionRequestedObservable) {
  69305. this._onUserActionRequestedObservable = new BABYLON.Observable();
  69306. }
  69307. return this._onUserActionRequestedObservable;
  69308. },
  69309. enumerable: true,
  69310. configurable: true
  69311. });
  69312. VideoTexture.prototype._getName = function (src) {
  69313. if (src instanceof HTMLVideoElement) {
  69314. return src.currentSrc;
  69315. }
  69316. if (typeof src === "object") {
  69317. return src.toString();
  69318. }
  69319. return src;
  69320. };
  69321. ;
  69322. VideoTexture.prototype._getVideo = function (src) {
  69323. if (src instanceof HTMLVideoElement) {
  69324. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  69325. return src;
  69326. }
  69327. var video = document.createElement("video");
  69328. if (typeof src === "string") {
  69329. BABYLON.Tools.SetCorsBehavior(src, video);
  69330. video.src = src;
  69331. }
  69332. else {
  69333. BABYLON.Tools.SetCorsBehavior(src[0], video);
  69334. src.forEach(function (url) {
  69335. var source = document.createElement("source");
  69336. source.src = url;
  69337. video.appendChild(source);
  69338. });
  69339. }
  69340. return video;
  69341. };
  69342. ;
  69343. /**
  69344. * @hidden Internal method to initiate `update`.
  69345. */
  69346. VideoTexture.prototype._rebuild = function () {
  69347. this.update();
  69348. };
  69349. /**
  69350. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  69351. */
  69352. VideoTexture.prototype.update = function () {
  69353. if (!this.autoUpdateTexture) {
  69354. // Expecting user to call `updateTexture` manually
  69355. return;
  69356. }
  69357. this.updateTexture(true);
  69358. };
  69359. /**
  69360. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  69361. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  69362. */
  69363. VideoTexture.prototype.updateTexture = function (isVisible) {
  69364. if (!isVisible) {
  69365. return;
  69366. }
  69367. if (this.video.paused && this._stillImageCaptured) {
  69368. return;
  69369. }
  69370. this._stillImageCaptured = true;
  69371. this._updateInternalTexture();
  69372. };
  69373. /**
  69374. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  69375. * @param url New url.
  69376. */
  69377. VideoTexture.prototype.updateURL = function (url) {
  69378. this.video.src = url;
  69379. };
  69380. VideoTexture.prototype.dispose = function () {
  69381. _super.prototype.dispose.call(this);
  69382. if (this._onUserActionRequestedObservable) {
  69383. this._onUserActionRequestedObservable.clear();
  69384. this._onUserActionRequestedObservable = null;
  69385. }
  69386. this.video.removeEventListener("canplay", this._createInternalTexture);
  69387. this.video.removeEventListener("paused", this._updateInternalTexture);
  69388. this.video.removeEventListener("seeked", this._updateInternalTexture);
  69389. this.video.removeEventListener("emptied", this.reset);
  69390. this.video.pause();
  69391. };
  69392. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  69393. var video = document.createElement("video");
  69394. video.setAttribute('autoplay', '');
  69395. video.setAttribute('muted', '');
  69396. video.setAttribute('playsinline', '');
  69397. var constraintsDeviceId;
  69398. if (constraints && constraints.deviceId) {
  69399. constraintsDeviceId = {
  69400. exact: constraints.deviceId,
  69401. };
  69402. }
  69403. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  69404. if (navigator.mediaDevices) {
  69405. navigator.mediaDevices.getUserMedia({ video: constraints })
  69406. .then(function (stream) {
  69407. if (video.mozSrcObject !== undefined) {
  69408. // hack for Firefox < 19
  69409. video.mozSrcObject = stream;
  69410. }
  69411. else {
  69412. video.srcObject = stream;
  69413. }
  69414. var onPlaying = function () {
  69415. if (onReady) {
  69416. onReady(new VideoTexture("video", video, scene, true, true));
  69417. }
  69418. video.removeEventListener("playing", onPlaying);
  69419. };
  69420. video.addEventListener("playing", onPlaying);
  69421. video.play();
  69422. })
  69423. .catch(function (err) {
  69424. BABYLON.Tools.Error(err.name);
  69425. });
  69426. }
  69427. else {
  69428. navigator.getUserMedia =
  69429. navigator.getUserMedia ||
  69430. navigator.webkitGetUserMedia ||
  69431. navigator.mozGetUserMedia ||
  69432. navigator.msGetUserMedia;
  69433. if (navigator.getUserMedia) {
  69434. navigator.getUserMedia({
  69435. video: {
  69436. deviceId: constraintsDeviceId,
  69437. width: {
  69438. min: (constraints && constraints.minWidth) || 256,
  69439. max: (constraints && constraints.maxWidth) || 640,
  69440. },
  69441. height: {
  69442. min: (constraints && constraints.minHeight) || 256,
  69443. max: (constraints && constraints.maxHeight) || 480,
  69444. },
  69445. },
  69446. }, function (stream) {
  69447. if (video.mozSrcObject !== undefined) {
  69448. // hack for Firefox < 19
  69449. video.mozSrcObject = stream;
  69450. }
  69451. else {
  69452. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  69453. }
  69454. video.play();
  69455. if (onReady) {
  69456. onReady(new VideoTexture("video", video, scene, true, true));
  69457. }
  69458. }, function (e) {
  69459. BABYLON.Tools.Error(e.name);
  69460. });
  69461. }
  69462. }
  69463. };
  69464. return VideoTexture;
  69465. }(BABYLON.Texture));
  69466. BABYLON.VideoTexture = VideoTexture;
  69467. })(BABYLON || (BABYLON = {}));
  69468. //# sourceMappingURL=babylon.videoTexture.js.map
  69469. var BABYLON;
  69470. (function (BABYLON) {
  69471. var RawTexture = /** @class */ (function (_super) {
  69472. __extends(RawTexture, _super);
  69473. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  69474. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69475. if (invertY === void 0) { invertY = false; }
  69476. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69477. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69478. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  69479. _this.format = format;
  69480. _this._engine = scene.getEngine();
  69481. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  69482. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69483. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69484. return _this;
  69485. }
  69486. RawTexture.prototype.update = function (data) {
  69487. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  69488. };
  69489. // Statics
  69490. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69491. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69492. if (invertY === void 0) { invertY = false; }
  69493. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69494. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  69495. };
  69496. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69497. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69498. if (invertY === void 0) { invertY = false; }
  69499. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69500. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  69501. };
  69502. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69503. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69504. if (invertY === void 0) { invertY = false; }
  69505. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69506. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  69507. };
  69508. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69509. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69510. if (invertY === void 0) { invertY = false; }
  69511. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69512. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69513. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  69514. };
  69515. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69516. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69517. if (invertY === void 0) { invertY = false; }
  69518. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69519. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69520. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  69521. };
  69522. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69523. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69524. if (invertY === void 0) { invertY = false; }
  69525. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69526. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  69527. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  69528. };
  69529. return RawTexture;
  69530. }(BABYLON.Texture));
  69531. BABYLON.RawTexture = RawTexture;
  69532. })(BABYLON || (BABYLON = {}));
  69533. //# sourceMappingURL=babylon.rawTexture.js.map
  69534. var BABYLON;
  69535. (function (BABYLON) {
  69536. /**
  69537. * Class used to store 3D textures containing user data
  69538. */
  69539. var RawTexture3D = /** @class */ (function (_super) {
  69540. __extends(RawTexture3D, _super);
  69541. /**
  69542. * Create a new RawTexture3D
  69543. * @param data defines the data of the texture
  69544. * @param width defines the width of the texture
  69545. * @param height defines the height of the texture
  69546. * @param depth defines the depth of the texture
  69547. * @param format defines the texture format to use
  69548. * @param scene defines the hosting scene
  69549. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  69550. * @param invertY defines if texture must be stored with Y axis inverted
  69551. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  69552. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  69553. */
  69554. function RawTexture3D(data, width, height, depth,
  69555. /** Gets or sets the texture format to use */
  69556. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  69557. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69558. if (invertY === void 0) { invertY = false; }
  69559. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69560. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69561. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  69562. _this.format = format;
  69563. _this._engine = scene.getEngine();
  69564. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  69565. _this.is3D = true;
  69566. return _this;
  69567. }
  69568. /**
  69569. * Update the texture with new data
  69570. * @param data defines the data to store in the texture
  69571. */
  69572. RawTexture3D.prototype.update = function (data) {
  69573. if (!this._texture) {
  69574. return;
  69575. }
  69576. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  69577. };
  69578. return RawTexture3D;
  69579. }(BABYLON.Texture));
  69580. BABYLON.RawTexture3D = RawTexture3D;
  69581. })(BABYLON || (BABYLON = {}));
  69582. //# sourceMappingURL=babylon.rawTexture3D.js.map
  69583. var BABYLON;
  69584. (function (BABYLON) {
  69585. /**
  69586. * PostProcessManager is used to manage one or more post processes or post process pipelines
  69587. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69588. */
  69589. var PostProcessManager = /** @class */ (function () {
  69590. /**
  69591. * Creates a new instance PostProcess
  69592. * @param scene The scene that the post process is associated with.
  69593. */
  69594. function PostProcessManager(scene) {
  69595. this._vertexBuffers = {};
  69596. this._scene = scene;
  69597. }
  69598. PostProcessManager.prototype._prepareBuffers = function () {
  69599. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  69600. return;
  69601. }
  69602. // VBO
  69603. var vertices = [];
  69604. vertices.push(1, 1);
  69605. vertices.push(-1, 1);
  69606. vertices.push(-1, -1);
  69607. vertices.push(1, -1);
  69608. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69609. this._buildIndexBuffer();
  69610. };
  69611. PostProcessManager.prototype._buildIndexBuffer = function () {
  69612. // Indices
  69613. var indices = [];
  69614. indices.push(0);
  69615. indices.push(1);
  69616. indices.push(2);
  69617. indices.push(0);
  69618. indices.push(2);
  69619. indices.push(3);
  69620. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  69621. };
  69622. /**
  69623. * Rebuilds the vertex buffers of the manager.
  69624. * @hidden
  69625. */
  69626. PostProcessManager.prototype._rebuild = function () {
  69627. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69628. if (!vb) {
  69629. return;
  69630. }
  69631. vb._rebuild();
  69632. this._buildIndexBuffer();
  69633. };
  69634. // Methods
  69635. /**
  69636. * Prepares a frame to be run through a post process.
  69637. * @param sourceTexture The input texture to the post procesess. (default: null)
  69638. * @param postProcesses An array of post processes to be run. (default: null)
  69639. * @returns True if the post processes were able to be run.
  69640. * @hidden
  69641. */
  69642. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  69643. if (sourceTexture === void 0) { sourceTexture = null; }
  69644. if (postProcesses === void 0) { postProcesses = null; }
  69645. var camera = this._scene.activeCamera;
  69646. if (!camera) {
  69647. return false;
  69648. }
  69649. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69650. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69651. return false;
  69652. }
  69653. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  69654. return true;
  69655. };
  69656. /**
  69657. * Manually render a set of post processes to a texture.
  69658. * @param postProcesses An array of post processes to be run.
  69659. * @param targetTexture The target texture to render to.
  69660. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  69661. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  69662. * @param lodLevel defines which lod of the texture to render to
  69663. */
  69664. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  69665. if (targetTexture === void 0) { targetTexture = null; }
  69666. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69667. if (faceIndex === void 0) { faceIndex = 0; }
  69668. if (lodLevel === void 0) { lodLevel = 0; }
  69669. var engine = this._scene.getEngine();
  69670. for (var index = 0; index < postProcesses.length; index++) {
  69671. if (index < postProcesses.length - 1) {
  69672. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  69673. }
  69674. else {
  69675. if (targetTexture) {
  69676. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  69677. }
  69678. else {
  69679. engine.restoreDefaultFramebuffer();
  69680. }
  69681. }
  69682. var pp = postProcesses[index];
  69683. var effect = pp.apply();
  69684. if (effect) {
  69685. pp.onBeforeRenderObservable.notifyObservers(effect);
  69686. // VBOs
  69687. this._prepareBuffers();
  69688. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69689. // Draw order
  69690. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69691. pp.onAfterRenderObservable.notifyObservers(effect);
  69692. }
  69693. }
  69694. // Restore depth buffer
  69695. engine.setDepthBuffer(true);
  69696. engine.setDepthWrite(true);
  69697. };
  69698. /**
  69699. * Finalize the result of the output of the postprocesses.
  69700. * @param doNotPresent If true the result will not be displayed to the screen.
  69701. * @param targetTexture The target texture to render to.
  69702. * @param faceIndex The index of the face to bind the target texture to.
  69703. * @param postProcesses The array of post processes to render.
  69704. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  69705. * @hidden
  69706. */
  69707. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  69708. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69709. var camera = this._scene.activeCamera;
  69710. if (!camera) {
  69711. return;
  69712. }
  69713. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69714. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69715. return;
  69716. }
  69717. var engine = this._scene.getEngine();
  69718. for (var index = 0, len = postProcesses.length; index < len; index++) {
  69719. var pp = postProcesses[index];
  69720. if (index < len - 1) {
  69721. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  69722. }
  69723. else {
  69724. if (targetTexture) {
  69725. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  69726. pp._outputTexture = targetTexture;
  69727. }
  69728. else {
  69729. engine.restoreDefaultFramebuffer();
  69730. pp._outputTexture = null;
  69731. }
  69732. }
  69733. if (doNotPresent) {
  69734. break;
  69735. }
  69736. var effect = pp.apply();
  69737. if (effect) {
  69738. pp.onBeforeRenderObservable.notifyObservers(effect);
  69739. // VBOs
  69740. this._prepareBuffers();
  69741. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69742. // Draw order
  69743. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69744. pp.onAfterRenderObservable.notifyObservers(effect);
  69745. }
  69746. }
  69747. // Restore states
  69748. engine.setDepthBuffer(true);
  69749. engine.setDepthWrite(true);
  69750. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69751. };
  69752. /**
  69753. * Disposes of the post process manager.
  69754. */
  69755. PostProcessManager.prototype.dispose = function () {
  69756. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69757. if (buffer) {
  69758. buffer.dispose();
  69759. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69760. }
  69761. if (this._indexBuffer) {
  69762. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69763. this._indexBuffer = null;
  69764. }
  69765. };
  69766. return PostProcessManager;
  69767. }());
  69768. BABYLON.PostProcessManager = PostProcessManager;
  69769. })(BABYLON || (BABYLON = {}));
  69770. //# sourceMappingURL=babylon.postProcessManager.js.map
  69771. var BABYLON;
  69772. (function (BABYLON) {
  69773. /**
  69774. * PostProcess can be used to apply a shader to a texture after it has been rendered
  69775. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69776. */
  69777. var PostProcess = /** @class */ (function () {
  69778. /**
  69779. * Creates a new instance PostProcess
  69780. * @param name The name of the PostProcess.
  69781. * @param fragmentUrl The url of the fragment shader to be used.
  69782. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  69783. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  69784. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69785. * @param camera The camera to apply the render pass to.
  69786. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69787. * @param engine The engine which the post process will be applied. (default: current engine)
  69788. * @param reusable If the post process can be reused on the same frame. (default: false)
  69789. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  69790. * @param textureType Type of textures used when performing the post process. (default: 0)
  69791. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  69792. * @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
  69793. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  69794. */
  69795. function PostProcess(
  69796. /** Name of the PostProcess. */
  69797. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  69798. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  69799. if (defines === void 0) { defines = null; }
  69800. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69801. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  69802. if (blockCompilation === void 0) { blockCompilation = false; }
  69803. this.name = name;
  69804. /**
  69805. * Width of the texture to apply the post process on
  69806. */
  69807. this.width = -1;
  69808. /**
  69809. * Height of the texture to apply the post process on
  69810. */
  69811. this.height = -1;
  69812. /**
  69813. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  69814. * @hidden
  69815. */
  69816. this._outputTexture = null;
  69817. /**
  69818. * If the buffer needs to be cleared before applying the post process. (default: true)
  69819. * Should be set to false if shader will overwrite all previous pixels.
  69820. */
  69821. this.autoClear = true;
  69822. /**
  69823. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  69824. */
  69825. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  69826. /**
  69827. * Animations to be used for the post processing
  69828. */
  69829. this.animations = new Array();
  69830. /**
  69831. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  69832. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  69833. */
  69834. this.enablePixelPerfectMode = false;
  69835. /**
  69836. * Force the postprocess to be applied without taking in account viewport
  69837. */
  69838. this.forceFullscreenViewport = true;
  69839. /**
  69840. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  69841. *
  69842. * | Value | Type | Description |
  69843. * | ----- | ----------------------------------- | ----------- |
  69844. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  69845. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  69846. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  69847. *
  69848. */
  69849. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  69850. /**
  69851. * Force textures to be a power of two (default: false)
  69852. */
  69853. this.alwaysForcePOT = false;
  69854. this._samples = 1;
  69855. /**
  69856. * Modify the scale of the post process to be the same as the viewport (default: false)
  69857. */
  69858. this.adaptScaleToCurrentViewport = false;
  69859. this._reusable = false;
  69860. /**
  69861. * Smart array of input and output textures for the post process.
  69862. * @hidden
  69863. */
  69864. this._textures = new BABYLON.SmartArray(2);
  69865. /**
  69866. * The index in _textures that corresponds to the output texture.
  69867. * @hidden
  69868. */
  69869. this._currentRenderTextureInd = 0;
  69870. this._scaleRatio = new BABYLON.Vector2(1, 1);
  69871. this._texelSize = BABYLON.Vector2.Zero();
  69872. // Events
  69873. /**
  69874. * An event triggered when the postprocess is activated.
  69875. */
  69876. this.onActivateObservable = new BABYLON.Observable();
  69877. /**
  69878. * An event triggered when the postprocess changes its size.
  69879. */
  69880. this.onSizeChangedObservable = new BABYLON.Observable();
  69881. /**
  69882. * An event triggered when the postprocess applies its effect.
  69883. */
  69884. this.onApplyObservable = new BABYLON.Observable();
  69885. /**
  69886. * An event triggered before rendering the postprocess
  69887. */
  69888. this.onBeforeRenderObservable = new BABYLON.Observable();
  69889. /**
  69890. * An event triggered after rendering the postprocess
  69891. */
  69892. this.onAfterRenderObservable = new BABYLON.Observable();
  69893. if (camera != null) {
  69894. this._camera = camera;
  69895. this._scene = camera.getScene();
  69896. camera.attachPostProcess(this);
  69897. this._engine = this._scene.getEngine();
  69898. this._scene.postProcesses.push(this);
  69899. }
  69900. else if (engine) {
  69901. this._engine = engine;
  69902. this._engine.postProcesses.push(this);
  69903. }
  69904. this._options = options;
  69905. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  69906. this._reusable = reusable || false;
  69907. this._textureType = textureType;
  69908. this._samplers = samplers || [];
  69909. this._samplers.push("textureSampler");
  69910. this._fragmentUrl = fragmentUrl;
  69911. this._vertexUrl = vertexUrl;
  69912. this._parameters = parameters || [];
  69913. this._parameters.push("scale");
  69914. this._indexParameters = indexParameters;
  69915. if (!blockCompilation) {
  69916. this.updateEffect(defines);
  69917. }
  69918. }
  69919. Object.defineProperty(PostProcess.prototype, "samples", {
  69920. /**
  69921. * Number of sample textures (default: 1)
  69922. */
  69923. get: function () {
  69924. return this._samples;
  69925. },
  69926. set: function (n) {
  69927. var _this = this;
  69928. this._samples = n;
  69929. this._textures.forEach(function (texture) {
  69930. if (texture.samples !== _this._samples) {
  69931. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  69932. }
  69933. });
  69934. },
  69935. enumerable: true,
  69936. configurable: true
  69937. });
  69938. Object.defineProperty(PostProcess.prototype, "onActivate", {
  69939. /**
  69940. * A function that is added to the onActivateObservable
  69941. */
  69942. set: function (callback) {
  69943. if (this._onActivateObserver) {
  69944. this.onActivateObservable.remove(this._onActivateObserver);
  69945. }
  69946. if (callback) {
  69947. this._onActivateObserver = this.onActivateObservable.add(callback);
  69948. }
  69949. },
  69950. enumerable: true,
  69951. configurable: true
  69952. });
  69953. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  69954. /**
  69955. * A function that is added to the onSizeChangedObservable
  69956. */
  69957. set: function (callback) {
  69958. if (this._onSizeChangedObserver) {
  69959. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  69960. }
  69961. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  69962. },
  69963. enumerable: true,
  69964. configurable: true
  69965. });
  69966. Object.defineProperty(PostProcess.prototype, "onApply", {
  69967. /**
  69968. * A function that is added to the onApplyObservable
  69969. */
  69970. set: function (callback) {
  69971. if (this._onApplyObserver) {
  69972. this.onApplyObservable.remove(this._onApplyObserver);
  69973. }
  69974. this._onApplyObserver = this.onApplyObservable.add(callback);
  69975. },
  69976. enumerable: true,
  69977. configurable: true
  69978. });
  69979. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  69980. /**
  69981. * A function that is added to the onBeforeRenderObservable
  69982. */
  69983. set: function (callback) {
  69984. if (this._onBeforeRenderObserver) {
  69985. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69986. }
  69987. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69988. },
  69989. enumerable: true,
  69990. configurable: true
  69991. });
  69992. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  69993. /**
  69994. * A function that is added to the onAfterRenderObservable
  69995. */
  69996. set: function (callback) {
  69997. if (this._onAfterRenderObserver) {
  69998. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69999. }
  70000. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  70001. },
  70002. enumerable: true,
  70003. configurable: true
  70004. });
  70005. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  70006. /**
  70007. * 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
  70008. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  70009. */
  70010. get: function () {
  70011. return this._textures.data[this._currentRenderTextureInd];
  70012. },
  70013. set: function (value) {
  70014. this._forcedOutputTexture = value;
  70015. },
  70016. enumerable: true,
  70017. configurable: true
  70018. });
  70019. /**
  70020. * Gets the camera which post process is applied to.
  70021. * @returns The camera the post process is applied to.
  70022. */
  70023. PostProcess.prototype.getCamera = function () {
  70024. return this._camera;
  70025. };
  70026. Object.defineProperty(PostProcess.prototype, "texelSize", {
  70027. /**
  70028. * Gets the texel size of the postprocess.
  70029. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  70030. */
  70031. get: function () {
  70032. if (this._shareOutputWithPostProcess) {
  70033. return this._shareOutputWithPostProcess.texelSize;
  70034. }
  70035. if (this._forcedOutputTexture) {
  70036. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  70037. }
  70038. return this._texelSize;
  70039. },
  70040. enumerable: true,
  70041. configurable: true
  70042. });
  70043. /**
  70044. * Gets the engine which this post process belongs to.
  70045. * @returns The engine the post process was enabled with.
  70046. */
  70047. PostProcess.prototype.getEngine = function () {
  70048. return this._engine;
  70049. };
  70050. /**
  70051. * The effect that is created when initializing the post process.
  70052. * @returns The created effect corrisponding the the postprocess.
  70053. */
  70054. PostProcess.prototype.getEffect = function () {
  70055. return this._effect;
  70056. };
  70057. /**
  70058. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  70059. * @param postProcess The post process to share the output with.
  70060. * @returns This post process.
  70061. */
  70062. PostProcess.prototype.shareOutputWith = function (postProcess) {
  70063. this._disposeTextures();
  70064. this._shareOutputWithPostProcess = postProcess;
  70065. return this;
  70066. };
  70067. /**
  70068. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  70069. * This should be called if the post process that shares output with this post process is disabled/disposed.
  70070. */
  70071. PostProcess.prototype.useOwnOutput = function () {
  70072. if (this._textures.length == 0) {
  70073. this._textures = new BABYLON.SmartArray(2);
  70074. }
  70075. this._shareOutputWithPostProcess = null;
  70076. };
  70077. /**
  70078. * Updates the effect with the current post process compile time values and recompiles the shader.
  70079. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70080. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70081. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70082. * @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
  70083. * @param onCompiled Called when the shader has been compiled.
  70084. * @param onError Called if there is an error when compiling a shader.
  70085. */
  70086. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70087. if (defines === void 0) { defines = null; }
  70088. if (uniforms === void 0) { uniforms = null; }
  70089. if (samplers === void 0) { samplers = null; }
  70090. 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);
  70091. };
  70092. /**
  70093. * The post process is reusable if it can be used multiple times within one frame.
  70094. * @returns If the post process is reusable
  70095. */
  70096. PostProcess.prototype.isReusable = function () {
  70097. return this._reusable;
  70098. };
  70099. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  70100. PostProcess.prototype.markTextureDirty = function () {
  70101. this.width = -1;
  70102. };
  70103. /**
  70104. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  70105. * 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.
  70106. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  70107. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  70108. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  70109. * @returns The target texture that was bound to be written to.
  70110. */
  70111. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  70112. var _this = this;
  70113. if (sourceTexture === void 0) { sourceTexture = null; }
  70114. camera = camera || this._camera;
  70115. var scene = camera.getScene();
  70116. var engine = scene.getEngine();
  70117. var maxSize = engine.getCaps().maxTextureSize;
  70118. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  70119. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  70120. // 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
  70121. var webVRCamera = camera.parent;
  70122. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  70123. requiredWidth /= 2;
  70124. }
  70125. var desiredWidth = (this._options.width || requiredWidth);
  70126. var desiredHeight = this._options.height || requiredHeight;
  70127. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  70128. if (this.adaptScaleToCurrentViewport) {
  70129. var currentViewport = engine.currentViewport;
  70130. if (currentViewport) {
  70131. desiredWidth *= currentViewport.width;
  70132. desiredHeight *= currentViewport.height;
  70133. }
  70134. }
  70135. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  70136. if (!this._options.width) {
  70137. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  70138. }
  70139. if (!this._options.height) {
  70140. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  70141. }
  70142. }
  70143. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  70144. if (this._textures.length > 0) {
  70145. for (var i = 0; i < this._textures.length; i++) {
  70146. this._engine._releaseTexture(this._textures.data[i]);
  70147. }
  70148. this._textures.reset();
  70149. }
  70150. this.width = desiredWidth;
  70151. this.height = desiredHeight;
  70152. var textureSize = { width: this.width, height: this.height };
  70153. var textureOptions = {
  70154. generateMipMaps: false,
  70155. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  70156. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  70157. samplingMode: this.renderTargetSamplingMode,
  70158. type: this._textureType
  70159. };
  70160. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  70161. if (this._reusable) {
  70162. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  70163. }
  70164. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  70165. this.onSizeChangedObservable.notifyObservers(this);
  70166. }
  70167. this._textures.forEach(function (texture) {
  70168. if (texture.samples !== _this.samples) {
  70169. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  70170. }
  70171. });
  70172. }
  70173. var target;
  70174. if (this._shareOutputWithPostProcess) {
  70175. target = this._shareOutputWithPostProcess.inputTexture;
  70176. }
  70177. else if (this._forcedOutputTexture) {
  70178. target = this._forcedOutputTexture;
  70179. this.width = this._forcedOutputTexture.width;
  70180. this.height = this._forcedOutputTexture.height;
  70181. }
  70182. else {
  70183. target = this.inputTexture;
  70184. }
  70185. // Bind the input of this post process to be used as the output of the previous post process.
  70186. if (this.enablePixelPerfectMode) {
  70187. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  70188. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  70189. }
  70190. else {
  70191. this._scaleRatio.copyFromFloats(1, 1);
  70192. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  70193. }
  70194. this.onActivateObservable.notifyObservers(camera);
  70195. // Clear
  70196. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  70197. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  70198. }
  70199. if (this._reusable) {
  70200. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  70201. }
  70202. return target;
  70203. };
  70204. Object.defineProperty(PostProcess.prototype, "isSupported", {
  70205. /**
  70206. * If the post process is supported.
  70207. */
  70208. get: function () {
  70209. return this._effect.isSupported;
  70210. },
  70211. enumerable: true,
  70212. configurable: true
  70213. });
  70214. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  70215. /**
  70216. * The aspect ratio of the output texture.
  70217. */
  70218. get: function () {
  70219. if (this._shareOutputWithPostProcess) {
  70220. return this._shareOutputWithPostProcess.aspectRatio;
  70221. }
  70222. if (this._forcedOutputTexture) {
  70223. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  70224. }
  70225. return this.width / this.height;
  70226. },
  70227. enumerable: true,
  70228. configurable: true
  70229. });
  70230. /**
  70231. * Get a value indicating if the post-process is ready to be used
  70232. * @returns true if the post-process is ready (shader is compiled)
  70233. */
  70234. PostProcess.prototype.isReady = function () {
  70235. return this._effect && this._effect.isReady();
  70236. };
  70237. /**
  70238. * Binds all textures and uniforms to the shader, this will be run on every pass.
  70239. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  70240. */
  70241. PostProcess.prototype.apply = function () {
  70242. // Check
  70243. if (!this._effect || !this._effect.isReady())
  70244. return null;
  70245. // States
  70246. this._engine.enableEffect(this._effect);
  70247. this._engine.setState(false);
  70248. this._engine.setDepthBuffer(false);
  70249. this._engine.setDepthWrite(false);
  70250. // Alpha
  70251. this._engine.setAlphaMode(this.alphaMode);
  70252. if (this.alphaConstants) {
  70253. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  70254. }
  70255. // Bind the output texture of the preivous post process as the input to this post process.
  70256. var source;
  70257. if (this._shareOutputWithPostProcess) {
  70258. source = this._shareOutputWithPostProcess.inputTexture;
  70259. }
  70260. else if (this._forcedOutputTexture) {
  70261. source = this._forcedOutputTexture;
  70262. }
  70263. else {
  70264. source = this.inputTexture;
  70265. }
  70266. this._effect._bindTexture("textureSampler", source);
  70267. // Parameters
  70268. this._effect.setVector2("scale", this._scaleRatio);
  70269. this.onApplyObservable.notifyObservers(this._effect);
  70270. return this._effect;
  70271. };
  70272. PostProcess.prototype._disposeTextures = function () {
  70273. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  70274. return;
  70275. }
  70276. if (this._textures.length > 0) {
  70277. for (var i = 0; i < this._textures.length; i++) {
  70278. this._engine._releaseTexture(this._textures.data[i]);
  70279. }
  70280. }
  70281. this._textures.dispose();
  70282. };
  70283. /**
  70284. * Disposes the post process.
  70285. * @param camera The camera to dispose the post process on.
  70286. */
  70287. PostProcess.prototype.dispose = function (camera) {
  70288. camera = camera || this._camera;
  70289. this._disposeTextures();
  70290. if (this._scene) {
  70291. var index_1 = this._scene.postProcesses.indexOf(this);
  70292. if (index_1 !== -1) {
  70293. this._scene.postProcesses.splice(index_1, 1);
  70294. }
  70295. }
  70296. else {
  70297. var index_2 = this._engine.postProcesses.indexOf(this);
  70298. if (index_2 !== -1) {
  70299. this._engine.postProcesses.splice(index_2, 1);
  70300. }
  70301. }
  70302. if (!camera) {
  70303. return;
  70304. }
  70305. camera.detachPostProcess(this);
  70306. var index = camera._postProcesses.indexOf(this);
  70307. if (index === 0 && camera._postProcesses.length > 0) {
  70308. var firstPostProcess = this._camera._getFirstPostProcess();
  70309. if (firstPostProcess) {
  70310. firstPostProcess.markTextureDirty();
  70311. }
  70312. }
  70313. this.onActivateObservable.clear();
  70314. this.onAfterRenderObservable.clear();
  70315. this.onApplyObservable.clear();
  70316. this.onBeforeRenderObservable.clear();
  70317. this.onSizeChangedObservable.clear();
  70318. };
  70319. return PostProcess;
  70320. }());
  70321. BABYLON.PostProcess = PostProcess;
  70322. })(BABYLON || (BABYLON = {}));
  70323. //# sourceMappingURL=babylon.postProcess.js.map
  70324. var BABYLON;
  70325. (function (BABYLON) {
  70326. var PassPostProcess = /** @class */ (function (_super) {
  70327. __extends(PassPostProcess, _super);
  70328. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70329. if (camera === void 0) { camera = null; }
  70330. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70331. if (blockCompilation === void 0) { blockCompilation = false; }
  70332. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  70333. }
  70334. return PassPostProcess;
  70335. }(BABYLON.PostProcess));
  70336. BABYLON.PassPostProcess = PassPostProcess;
  70337. })(BABYLON || (BABYLON = {}));
  70338. //# sourceMappingURL=babylon.passPostProcess.js.map
  70339. var __assign = (this && this.__assign) || function () {
  70340. __assign = Object.assign || function(t) {
  70341. for (var s, i = 1, n = arguments.length; i < n; i++) {
  70342. s = arguments[i];
  70343. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  70344. t[p] = s[p];
  70345. }
  70346. return t;
  70347. };
  70348. return __assign.apply(this, arguments);
  70349. };
  70350. var BABYLON;
  70351. (function (BABYLON) {
  70352. /**
  70353. * Default implementation IShadowGenerator.
  70354. * This is the main object responsible of generating shadows in the framework.
  70355. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  70356. */
  70357. var ShadowGenerator = /** @class */ (function () {
  70358. /**
  70359. * Creates a ShadowGenerator object.
  70360. * A ShadowGenerator is the required tool to use the shadows.
  70361. * Each light casting shadows needs to use its own ShadowGenerator.
  70362. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  70363. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  70364. * @param light The light object generating the shadows.
  70365. * @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.
  70366. */
  70367. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  70368. this._bias = 0.00005;
  70369. this._normalBias = 0;
  70370. this._blurBoxOffset = 1;
  70371. this._blurScale = 2;
  70372. this._blurKernel = 1;
  70373. this._useKernelBlur = false;
  70374. this._filter = ShadowGenerator.FILTER_NONE;
  70375. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  70376. this._contactHardeningLightSizeUVRatio = 0.1;
  70377. this._darkness = 0;
  70378. this._transparencyShadow = false;
  70379. /**
  70380. * Controls the extent to which the shadows fade out at the edge of the frustum
  70381. * Used only by directionals and spots
  70382. */
  70383. this.frustumEdgeFalloff = 0;
  70384. /**
  70385. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  70386. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  70387. * It might on the other hand introduce peter panning.
  70388. */
  70389. this.forceBackFacesOnly = false;
  70390. this._lightDirection = BABYLON.Vector3.Zero();
  70391. this._viewMatrix = BABYLON.Matrix.Zero();
  70392. this._projectionMatrix = BABYLON.Matrix.Zero();
  70393. this._transformMatrix = BABYLON.Matrix.Zero();
  70394. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  70395. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  70396. this._currentFaceIndex = 0;
  70397. this._currentFaceIndexCache = 0;
  70398. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  70399. this._mapSize = mapSize;
  70400. this._light = light;
  70401. this._scene = light.getScene();
  70402. light._shadowGenerator = this;
  70403. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  70404. if (!component) {
  70405. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  70406. this._scene._addComponent(component);
  70407. }
  70408. // Texture type fallback from float to int if not supported.
  70409. var caps = this._scene.getEngine().getCaps();
  70410. if (!useFullFloatFirst) {
  70411. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  70412. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70413. }
  70414. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  70415. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70416. }
  70417. else {
  70418. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70419. }
  70420. }
  70421. else {
  70422. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  70423. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70424. }
  70425. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  70426. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70427. }
  70428. else {
  70429. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70430. }
  70431. }
  70432. this._initializeGenerator();
  70433. this._applyFilterValues();
  70434. }
  70435. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  70436. /**
  70437. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  70438. */
  70439. get: function () {
  70440. return this._bias;
  70441. },
  70442. /**
  70443. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  70444. */
  70445. set: function (bias) {
  70446. this._bias = bias;
  70447. },
  70448. enumerable: true,
  70449. configurable: true
  70450. });
  70451. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  70452. /**
  70453. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  70454. */
  70455. get: function () {
  70456. return this._normalBias;
  70457. },
  70458. /**
  70459. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  70460. */
  70461. set: function (normalBias) {
  70462. this._normalBias = normalBias;
  70463. },
  70464. enumerable: true,
  70465. configurable: true
  70466. });
  70467. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  70468. /**
  70469. * Gets the blur box offset: offset applied during the blur pass.
  70470. * Only usefull if useKernelBlur = false
  70471. */
  70472. get: function () {
  70473. return this._blurBoxOffset;
  70474. },
  70475. /**
  70476. * Sets the blur box offset: offset applied during the blur pass.
  70477. * Only usefull if useKernelBlur = false
  70478. */
  70479. set: function (value) {
  70480. if (this._blurBoxOffset === value) {
  70481. return;
  70482. }
  70483. this._blurBoxOffset = value;
  70484. this._disposeBlurPostProcesses();
  70485. },
  70486. enumerable: true,
  70487. configurable: true
  70488. });
  70489. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  70490. /**
  70491. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  70492. * 2 means half of the size.
  70493. */
  70494. get: function () {
  70495. return this._blurScale;
  70496. },
  70497. /**
  70498. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  70499. * 2 means half of the size.
  70500. */
  70501. set: function (value) {
  70502. if (this._blurScale === value) {
  70503. return;
  70504. }
  70505. this._blurScale = value;
  70506. this._disposeBlurPostProcesses();
  70507. },
  70508. enumerable: true,
  70509. configurable: true
  70510. });
  70511. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  70512. /**
  70513. * Gets the blur kernel: kernel size of the blur pass.
  70514. * Only usefull if useKernelBlur = true
  70515. */
  70516. get: function () {
  70517. return this._blurKernel;
  70518. },
  70519. /**
  70520. * Sets the blur kernel: kernel size of the blur pass.
  70521. * Only usefull if useKernelBlur = true
  70522. */
  70523. set: function (value) {
  70524. if (this._blurKernel === value) {
  70525. return;
  70526. }
  70527. this._blurKernel = value;
  70528. this._disposeBlurPostProcesses();
  70529. },
  70530. enumerable: true,
  70531. configurable: true
  70532. });
  70533. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  70534. /**
  70535. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  70536. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  70537. */
  70538. get: function () {
  70539. return this._useKernelBlur;
  70540. },
  70541. /**
  70542. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  70543. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  70544. */
  70545. set: function (value) {
  70546. if (this._useKernelBlur === value) {
  70547. return;
  70548. }
  70549. this._useKernelBlur = value;
  70550. this._disposeBlurPostProcesses();
  70551. },
  70552. enumerable: true,
  70553. configurable: true
  70554. });
  70555. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  70556. /**
  70557. * Gets the depth scale used in ESM mode.
  70558. */
  70559. get: function () {
  70560. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  70561. },
  70562. /**
  70563. * Sets the depth scale used in ESM mode.
  70564. * This can override the scale stored on the light.
  70565. */
  70566. set: function (value) {
  70567. this._depthScale = value;
  70568. },
  70569. enumerable: true,
  70570. configurable: true
  70571. });
  70572. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  70573. /**
  70574. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  70575. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  70576. */
  70577. get: function () {
  70578. return this._filter;
  70579. },
  70580. /**
  70581. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  70582. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  70583. */
  70584. set: function (value) {
  70585. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  70586. if (this._light.needCube()) {
  70587. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70588. this.useExponentialShadowMap = true;
  70589. return;
  70590. }
  70591. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70592. this.useCloseExponentialShadowMap = true;
  70593. return;
  70594. }
  70595. // PCF on cubemap would also be expensive
  70596. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70597. this.usePoissonSampling = true;
  70598. return;
  70599. }
  70600. }
  70601. // Weblg1 fallback for PCF.
  70602. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70603. if (this._scene.getEngine().webGLVersion === 1) {
  70604. this.usePoissonSampling = true;
  70605. return;
  70606. }
  70607. }
  70608. if (this._filter === value) {
  70609. return;
  70610. }
  70611. this._filter = value;
  70612. this._disposeBlurPostProcesses();
  70613. this._applyFilterValues();
  70614. this._light._markMeshesAsLightDirty();
  70615. },
  70616. enumerable: true,
  70617. configurable: true
  70618. });
  70619. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  70620. /**
  70621. * Gets if the current filter is set to Poisson Sampling.
  70622. */
  70623. get: function () {
  70624. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  70625. },
  70626. /**
  70627. * Sets the current filter to Poisson Sampling.
  70628. */
  70629. set: function (value) {
  70630. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  70631. return;
  70632. }
  70633. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  70634. },
  70635. enumerable: true,
  70636. configurable: true
  70637. });
  70638. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  70639. /**
  70640. * Gets if the current filter is set to VSM.
  70641. * DEPRECATED. Should use useExponentialShadowMap instead.
  70642. */
  70643. get: function () {
  70644. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70645. return this.useExponentialShadowMap;
  70646. },
  70647. /**
  70648. * Sets the current filter is to VSM.
  70649. * DEPRECATED. Should use useExponentialShadowMap instead.
  70650. */
  70651. set: function (value) {
  70652. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70653. this.useExponentialShadowMap = value;
  70654. },
  70655. enumerable: true,
  70656. configurable: true
  70657. });
  70658. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  70659. /**
  70660. * Gets if the current filter is set to blurred VSM.
  70661. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70662. */
  70663. get: function () {
  70664. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70665. return this.useBlurExponentialShadowMap;
  70666. },
  70667. /**
  70668. * Sets the current filter is to blurred VSM.
  70669. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70670. */
  70671. set: function (value) {
  70672. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70673. this.useBlurExponentialShadowMap = value;
  70674. },
  70675. enumerable: true,
  70676. configurable: true
  70677. });
  70678. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  70679. /**
  70680. * Gets if the current filter is set to ESM.
  70681. */
  70682. get: function () {
  70683. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  70684. },
  70685. /**
  70686. * Sets the current filter is to ESM.
  70687. */
  70688. set: function (value) {
  70689. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  70690. return;
  70691. }
  70692. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70693. },
  70694. enumerable: true,
  70695. configurable: true
  70696. });
  70697. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  70698. /**
  70699. * Gets if the current filter is set to filtered ESM.
  70700. */
  70701. get: function () {
  70702. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  70703. },
  70704. /**
  70705. * Gets if the current filter is set to filtered ESM.
  70706. */
  70707. set: function (value) {
  70708. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70709. return;
  70710. }
  70711. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70712. },
  70713. enumerable: true,
  70714. configurable: true
  70715. });
  70716. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  70717. /**
  70718. * Gets if the current filter is set to "close ESM" (using the inverse of the
  70719. * exponential to prevent steep falloff artifacts).
  70720. */
  70721. get: function () {
  70722. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  70723. },
  70724. /**
  70725. * Sets the current filter to "close ESM" (using the inverse of the
  70726. * exponential to prevent steep falloff artifacts).
  70727. */
  70728. set: function (value) {
  70729. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  70730. return;
  70731. }
  70732. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70733. },
  70734. enumerable: true,
  70735. configurable: true
  70736. });
  70737. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  70738. /**
  70739. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  70740. * exponential to prevent steep falloff artifacts).
  70741. */
  70742. get: function () {
  70743. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  70744. },
  70745. /**
  70746. * Sets the current filter to filtered "close ESM" (using the inverse of the
  70747. * exponential to prevent steep falloff artifacts).
  70748. */
  70749. set: function (value) {
  70750. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70751. return;
  70752. }
  70753. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70754. },
  70755. enumerable: true,
  70756. configurable: true
  70757. });
  70758. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  70759. /**
  70760. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  70761. */
  70762. get: function () {
  70763. return this.filter === ShadowGenerator.FILTER_PCF;
  70764. },
  70765. /**
  70766. * Sets the current filter to "PCF" (percentage closer filtering).
  70767. */
  70768. set: function (value) {
  70769. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  70770. return;
  70771. }
  70772. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  70773. },
  70774. enumerable: true,
  70775. configurable: true
  70776. });
  70777. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  70778. /**
  70779. * Gets the PCF or PCSS Quality.
  70780. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70781. */
  70782. get: function () {
  70783. return this._filteringQuality;
  70784. },
  70785. /**
  70786. * Sets the PCF or PCSS Quality.
  70787. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70788. */
  70789. set: function (filteringQuality) {
  70790. this._filteringQuality = filteringQuality;
  70791. },
  70792. enumerable: true,
  70793. configurable: true
  70794. });
  70795. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  70796. /**
  70797. * Gets if the current filter is set to "PCSS" (contact hardening).
  70798. */
  70799. get: function () {
  70800. return this.filter === ShadowGenerator.FILTER_PCSS;
  70801. },
  70802. /**
  70803. * Sets the current filter to "PCSS" (contact hardening).
  70804. */
  70805. set: function (value) {
  70806. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  70807. return;
  70808. }
  70809. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  70810. },
  70811. enumerable: true,
  70812. configurable: true
  70813. });
  70814. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  70815. /**
  70816. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70817. * Using a ratio helps keeping shape stability independently of the map size.
  70818. *
  70819. * It does not account for the light projection as it was having too much
  70820. * instability during the light setup or during light position changes.
  70821. *
  70822. * Only valid if useContactHardeningShadow is true.
  70823. */
  70824. get: function () {
  70825. return this._contactHardeningLightSizeUVRatio;
  70826. },
  70827. /**
  70828. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70829. * Using a ratio helps keeping shape stability independently of the map size.
  70830. *
  70831. * It does not account for the light projection as it was having too much
  70832. * instability during the light setup or during light position changes.
  70833. *
  70834. * Only valid if useContactHardeningShadow is true.
  70835. */
  70836. set: function (contactHardeningLightSizeUVRatio) {
  70837. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  70838. },
  70839. enumerable: true,
  70840. configurable: true
  70841. });
  70842. /**
  70843. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  70844. * 0 means strongest and 1 would means no shadow.
  70845. * @returns the darkness.
  70846. */
  70847. ShadowGenerator.prototype.getDarkness = function () {
  70848. return this._darkness;
  70849. };
  70850. /**
  70851. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  70852. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  70853. * @returns the shadow generator allowing fluent coding.
  70854. */
  70855. ShadowGenerator.prototype.setDarkness = function (darkness) {
  70856. if (darkness >= 1.0)
  70857. this._darkness = 1.0;
  70858. else if (darkness <= 0.0)
  70859. this._darkness = 0.0;
  70860. else
  70861. this._darkness = darkness;
  70862. return this;
  70863. };
  70864. /**
  70865. * Sets the ability to have transparent shadow (boolean).
  70866. * @param transparent True if transparent else False
  70867. * @returns the shadow generator allowing fluent coding
  70868. */
  70869. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  70870. this._transparencyShadow = transparent;
  70871. return this;
  70872. };
  70873. /**
  70874. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  70875. * @returns The render target texture if present otherwise, null
  70876. */
  70877. ShadowGenerator.prototype.getShadowMap = function () {
  70878. return this._shadowMap;
  70879. };
  70880. /**
  70881. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  70882. * @returns The render target texture if the shadow map is present otherwise, null
  70883. */
  70884. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  70885. if (this._shadowMap2) {
  70886. return this._shadowMap2;
  70887. }
  70888. return this._shadowMap;
  70889. };
  70890. /**
  70891. * Helper function to add a mesh and its descendants to the list of shadow casters.
  70892. * @param mesh Mesh to add
  70893. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  70894. * @returns the Shadow Generator itself
  70895. */
  70896. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  70897. if (includeDescendants === void 0) { includeDescendants = true; }
  70898. var _a;
  70899. if (!this._shadowMap) {
  70900. return this;
  70901. }
  70902. if (!this._shadowMap.renderList) {
  70903. this._shadowMap.renderList = [];
  70904. }
  70905. this._shadowMap.renderList.push(mesh);
  70906. if (includeDescendants) {
  70907. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  70908. }
  70909. return this;
  70910. };
  70911. /**
  70912. * Helper function to remove a mesh and its descendants from the list of shadow casters
  70913. * @param mesh Mesh to remove
  70914. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  70915. * @returns the Shadow Generator itself
  70916. */
  70917. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  70918. if (includeDescendants === void 0) { includeDescendants = true; }
  70919. if (!this._shadowMap || !this._shadowMap.renderList) {
  70920. return this;
  70921. }
  70922. var index = this._shadowMap.renderList.indexOf(mesh);
  70923. if (index !== -1) {
  70924. this._shadowMap.renderList.splice(index, 1);
  70925. }
  70926. if (includeDescendants) {
  70927. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  70928. var child = _a[_i];
  70929. this.removeShadowCaster(child);
  70930. }
  70931. }
  70932. return this;
  70933. };
  70934. /**
  70935. * Returns the associated light object.
  70936. * @returns the light generating the shadow
  70937. */
  70938. ShadowGenerator.prototype.getLight = function () {
  70939. return this._light;
  70940. };
  70941. ShadowGenerator.prototype._initializeGenerator = function () {
  70942. this._light._markMeshesAsLightDirty();
  70943. this._initializeShadowMap();
  70944. };
  70945. ShadowGenerator.prototype._initializeShadowMap = function () {
  70946. var _this = this;
  70947. // Render target
  70948. var engine = this._scene.getEngine();
  70949. if (engine.webGLVersion > 1) {
  70950. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  70951. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  70952. }
  70953. else {
  70954. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  70955. }
  70956. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70957. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70958. this._shadowMap.anisotropicFilteringLevel = 1;
  70959. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70960. this._shadowMap.renderParticles = false;
  70961. this._shadowMap.ignoreCameraViewport = true;
  70962. // Record Face Index before render.
  70963. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  70964. _this._currentFaceIndex = faceIndex;
  70965. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70966. engine.setColorWrite(false);
  70967. }
  70968. });
  70969. // Custom render function.
  70970. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  70971. // Blur if required afer render.
  70972. this._shadowMap.onAfterUnbindObservable.add(function () {
  70973. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70974. engine.setColorWrite(true);
  70975. }
  70976. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  70977. return;
  70978. }
  70979. var shadowMap = _this.getShadowMapForRendering();
  70980. if (shadowMap) {
  70981. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  70982. }
  70983. });
  70984. // Clear according to the chosen filter.
  70985. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  70986. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  70987. this._shadowMap.onClearObservable.add(function (engine) {
  70988. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70989. engine.clear(clearOne, false, true, false);
  70990. }
  70991. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  70992. engine.clear(clearZero, true, true, false);
  70993. }
  70994. else {
  70995. engine.clear(clearOne, true, true, false);
  70996. }
  70997. });
  70998. };
  70999. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  71000. var _this = this;
  71001. var engine = this._scene.getEngine();
  71002. var targetSize = this._mapSize / this.blurScale;
  71003. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  71004. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  71005. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71006. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71007. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71008. }
  71009. if (this.useKernelBlur) {
  71010. 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);
  71011. this._kernelBlurXPostprocess.width = targetSize;
  71012. this._kernelBlurXPostprocess.height = targetSize;
  71013. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  71014. effect.setTexture("textureSampler", _this._shadowMap);
  71015. });
  71016. 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);
  71017. this._kernelBlurXPostprocess.autoClear = false;
  71018. this._kernelBlurYPostprocess.autoClear = false;
  71019. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71020. this._kernelBlurXPostprocess.packedFloat = true;
  71021. this._kernelBlurYPostprocess.packedFloat = true;
  71022. }
  71023. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  71024. }
  71025. else {
  71026. 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);
  71027. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  71028. effect.setFloat2("screenSize", targetSize, targetSize);
  71029. effect.setTexture("textureSampler", _this._shadowMap);
  71030. });
  71031. this._boxBlurPostprocess.autoClear = false;
  71032. this._blurPostProcesses = [this._boxBlurPostprocess];
  71033. }
  71034. };
  71035. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71036. var index;
  71037. var engine = this._scene.getEngine();
  71038. if (depthOnlySubMeshes.length) {
  71039. engine.setColorWrite(false);
  71040. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71041. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  71042. }
  71043. engine.setColorWrite(true);
  71044. }
  71045. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71046. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  71047. }
  71048. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71049. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  71050. }
  71051. if (this._transparencyShadow) {
  71052. for (index = 0; index < transparentSubMeshes.length; index++) {
  71053. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  71054. }
  71055. }
  71056. };
  71057. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  71058. var _this = this;
  71059. var mesh = subMesh.getRenderingMesh();
  71060. var scene = this._scene;
  71061. var engine = scene.getEngine();
  71062. var material = subMesh.getMaterial();
  71063. if (!material) {
  71064. return;
  71065. }
  71066. // Culling
  71067. engine.setState(material.backFaceCulling);
  71068. // Managing instances
  71069. var batch = mesh._getInstancesRenderList(subMesh._id);
  71070. if (batch.mustReturn) {
  71071. return;
  71072. }
  71073. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71074. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  71075. engine.enableEffect(this._effect);
  71076. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  71077. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  71078. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  71079. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  71080. this._effect.setVector3("lightData", this._cachedDirection);
  71081. }
  71082. else {
  71083. this._effect.setVector3("lightData", this._cachedPosition);
  71084. }
  71085. if (scene.activeCamera) {
  71086. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  71087. }
  71088. // Alpha test
  71089. if (material && material.needAlphaTesting()) {
  71090. var alphaTexture = material.getAlphaTestTexture();
  71091. if (alphaTexture) {
  71092. this._effect.setTexture("diffuseSampler", alphaTexture);
  71093. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  71094. }
  71095. }
  71096. // Bones
  71097. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71098. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  71099. }
  71100. // Morph targets
  71101. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  71102. if (this.forceBackFacesOnly) {
  71103. engine.setState(true, 0, false, true);
  71104. }
  71105. // Draw
  71106. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71107. if (this.forceBackFacesOnly) {
  71108. engine.setState(true, 0, false, false);
  71109. }
  71110. }
  71111. else {
  71112. // Need to reset refresh rate of the shadowMap
  71113. if (this._shadowMap) {
  71114. this._shadowMap.resetRefreshCounter();
  71115. }
  71116. }
  71117. };
  71118. ShadowGenerator.prototype._applyFilterValues = function () {
  71119. if (!this._shadowMap) {
  71120. return;
  71121. }
  71122. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  71123. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  71124. }
  71125. else {
  71126. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71127. }
  71128. };
  71129. /**
  71130. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  71131. * @param onCompiled Callback triggered at the and of the effects compilation
  71132. * @param options Sets of optional options forcing the compilation with different modes
  71133. */
  71134. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  71135. var _this = this;
  71136. var localOptions = __assign({ useInstances: false }, options);
  71137. var shadowMap = this.getShadowMap();
  71138. if (!shadowMap) {
  71139. if (onCompiled) {
  71140. onCompiled(this);
  71141. }
  71142. return;
  71143. }
  71144. var renderList = shadowMap.renderList;
  71145. if (!renderList) {
  71146. if (onCompiled) {
  71147. onCompiled(this);
  71148. }
  71149. return;
  71150. }
  71151. var subMeshes = new Array();
  71152. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  71153. var mesh = renderList_1[_i];
  71154. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  71155. }
  71156. if (subMeshes.length === 0) {
  71157. if (onCompiled) {
  71158. onCompiled(this);
  71159. }
  71160. return;
  71161. }
  71162. var currentIndex = 0;
  71163. var checkReady = function () {
  71164. if (!_this._scene || !_this._scene.getEngine()) {
  71165. return;
  71166. }
  71167. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  71168. currentIndex++;
  71169. if (currentIndex >= subMeshes.length) {
  71170. if (onCompiled) {
  71171. onCompiled(_this);
  71172. }
  71173. return;
  71174. }
  71175. }
  71176. setTimeout(checkReady, 16);
  71177. };
  71178. checkReady();
  71179. };
  71180. /**
  71181. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  71182. * @param options Sets of optional options forcing the compilation with different modes
  71183. * @returns A promise that resolves when the compilation completes
  71184. */
  71185. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  71186. var _this = this;
  71187. return new Promise(function (resolve) {
  71188. _this.forceCompilation(function () {
  71189. resolve();
  71190. }, options);
  71191. });
  71192. };
  71193. /**
  71194. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  71195. * @param subMesh The submesh we want to render in the shadow map
  71196. * @param useInstances Defines wether will draw in the map using instances
  71197. * @returns true if ready otherwise, false
  71198. */
  71199. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  71200. var defines = [];
  71201. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71202. defines.push("#define FLOAT");
  71203. }
  71204. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  71205. defines.push("#define ESM");
  71206. }
  71207. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  71208. defines.push("#define DEPTHTEXTURE");
  71209. }
  71210. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71211. var mesh = subMesh.getMesh();
  71212. var material = subMesh.getMaterial();
  71213. // Normal bias.
  71214. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  71215. attribs.push(BABYLON.VertexBuffer.NormalKind);
  71216. defines.push("#define NORMAL");
  71217. if (mesh.nonUniformScaling) {
  71218. defines.push("#define NONUNIFORMSCALING");
  71219. }
  71220. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  71221. defines.push("#define DIRECTIONINLIGHTDATA");
  71222. }
  71223. }
  71224. // Alpha test
  71225. if (material && material.needAlphaTesting()) {
  71226. var alphaTexture = material.getAlphaTestTexture();
  71227. if (alphaTexture) {
  71228. defines.push("#define ALPHATEST");
  71229. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71230. attribs.push(BABYLON.VertexBuffer.UVKind);
  71231. defines.push("#define UV1");
  71232. }
  71233. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71234. if (alphaTexture.coordinatesIndex === 1) {
  71235. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71236. defines.push("#define UV2");
  71237. }
  71238. }
  71239. }
  71240. }
  71241. // Bones
  71242. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71243. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71244. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71245. if (mesh.numBoneInfluencers > 4) {
  71246. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71247. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71248. }
  71249. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71250. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  71251. }
  71252. else {
  71253. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71254. }
  71255. // Morph targets
  71256. var manager = mesh.morphTargetManager;
  71257. var morphInfluencers = 0;
  71258. if (manager) {
  71259. if (manager.numInfluencers > 0) {
  71260. defines.push("#define MORPHTARGETS");
  71261. morphInfluencers = manager.numInfluencers;
  71262. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  71263. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  71264. }
  71265. }
  71266. // Instances
  71267. if (useInstances) {
  71268. defines.push("#define INSTANCES");
  71269. attribs.push("world0");
  71270. attribs.push("world1");
  71271. attribs.push("world2");
  71272. attribs.push("world3");
  71273. }
  71274. // Get correct effect
  71275. var join = defines.join("\n");
  71276. if (this._cachedDefines !== join) {
  71277. this._cachedDefines = join;
  71278. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  71279. }
  71280. if (!this._effect.isReady()) {
  71281. return false;
  71282. }
  71283. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  71284. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  71285. this._initializeBlurRTTAndPostProcesses();
  71286. }
  71287. }
  71288. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  71289. return false;
  71290. }
  71291. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  71292. return false;
  71293. }
  71294. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  71295. return false;
  71296. }
  71297. return true;
  71298. };
  71299. /**
  71300. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  71301. * @param defines Defines of the material we want to update
  71302. * @param lightIndex Index of the light in the enabled light list of the material
  71303. */
  71304. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  71305. var scene = this._scene;
  71306. var light = this._light;
  71307. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  71308. return;
  71309. }
  71310. defines["SHADOW" + lightIndex] = true;
  71311. if (this.useContactHardeningShadow) {
  71312. defines["SHADOWPCSS" + lightIndex] = true;
  71313. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  71314. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  71315. }
  71316. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  71317. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  71318. }
  71319. // else default to high.
  71320. }
  71321. if (this.usePercentageCloserFiltering) {
  71322. defines["SHADOWPCF" + lightIndex] = true;
  71323. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  71324. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  71325. }
  71326. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  71327. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  71328. }
  71329. // else default to high.
  71330. }
  71331. else if (this.usePoissonSampling) {
  71332. defines["SHADOWPOISSON" + lightIndex] = true;
  71333. }
  71334. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  71335. defines["SHADOWESM" + lightIndex] = true;
  71336. }
  71337. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  71338. defines["SHADOWCLOSEESM" + lightIndex] = true;
  71339. }
  71340. if (light.needCube()) {
  71341. defines["SHADOWCUBE" + lightIndex] = true;
  71342. }
  71343. };
  71344. /**
  71345. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  71346. * defined in the generator but impacting the effect).
  71347. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  71348. * @param effect The effect we are binfing the information for
  71349. */
  71350. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  71351. var light = this._light;
  71352. var scene = this._scene;
  71353. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  71354. return;
  71355. }
  71356. var camera = scene.activeCamera;
  71357. if (!camera) {
  71358. return;
  71359. }
  71360. var shadowMap = this.getShadowMap();
  71361. if (!shadowMap) {
  71362. return;
  71363. }
  71364. if (!light.needCube()) {
  71365. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  71366. }
  71367. // Only PCF uses depth stencil texture.
  71368. if (this._filter === ShadowGenerator.FILTER_PCF) {
  71369. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71370. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  71371. }
  71372. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  71373. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71374. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  71375. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  71376. }
  71377. else {
  71378. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71379. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  71380. }
  71381. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  71382. };
  71383. /**
  71384. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  71385. * (eq to shadow prjection matrix * light transform matrix)
  71386. * @returns The transform matrix used to create the shadow map
  71387. */
  71388. ShadowGenerator.prototype.getTransformMatrix = function () {
  71389. var scene = this._scene;
  71390. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  71391. return this._transformMatrix;
  71392. }
  71393. this._currentRenderID = scene.getRenderId();
  71394. this._currentFaceIndexCache = this._currentFaceIndex;
  71395. var lightPosition = this._light.position;
  71396. if (this._light.computeTransformedInformation()) {
  71397. lightPosition = this._light.transformedPosition;
  71398. }
  71399. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  71400. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  71401. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  71402. }
  71403. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  71404. this._cachedPosition.copyFrom(lightPosition);
  71405. this._cachedDirection.copyFrom(this._lightDirection);
  71406. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  71407. var shadowMap = this.getShadowMap();
  71408. if (shadowMap) {
  71409. var renderList = shadowMap.renderList;
  71410. if (renderList) {
  71411. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  71412. }
  71413. }
  71414. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  71415. }
  71416. return this._transformMatrix;
  71417. };
  71418. /**
  71419. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  71420. * Cube and 2D textures for instance.
  71421. */
  71422. ShadowGenerator.prototype.recreateShadowMap = function () {
  71423. var shadowMap = this._shadowMap;
  71424. if (!shadowMap) {
  71425. return;
  71426. }
  71427. // Track render list.
  71428. var renderList = shadowMap.renderList;
  71429. // Clean up existing data.
  71430. this._disposeRTTandPostProcesses();
  71431. // Reinitializes.
  71432. this._initializeGenerator();
  71433. // Reaffect the filter to ensure a correct fallback if necessary.
  71434. this.filter = this.filter;
  71435. // Reaffect the filter.
  71436. this._applyFilterValues();
  71437. // Reaffect Render List.
  71438. this._shadowMap.renderList = renderList;
  71439. };
  71440. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  71441. if (this._shadowMap2) {
  71442. this._shadowMap2.dispose();
  71443. this._shadowMap2 = null;
  71444. }
  71445. if (this._boxBlurPostprocess) {
  71446. this._boxBlurPostprocess.dispose();
  71447. this._boxBlurPostprocess = null;
  71448. }
  71449. if (this._kernelBlurXPostprocess) {
  71450. this._kernelBlurXPostprocess.dispose();
  71451. this._kernelBlurXPostprocess = null;
  71452. }
  71453. if (this._kernelBlurYPostprocess) {
  71454. this._kernelBlurYPostprocess.dispose();
  71455. this._kernelBlurYPostprocess = null;
  71456. }
  71457. this._blurPostProcesses = [];
  71458. };
  71459. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  71460. if (this._shadowMap) {
  71461. this._shadowMap.dispose();
  71462. this._shadowMap = null;
  71463. }
  71464. this._disposeBlurPostProcesses();
  71465. };
  71466. /**
  71467. * Disposes the ShadowGenerator.
  71468. * Returns nothing.
  71469. */
  71470. ShadowGenerator.prototype.dispose = function () {
  71471. this._disposeRTTandPostProcesses();
  71472. if (this._light) {
  71473. this._light._shadowGenerator = null;
  71474. this._light._markMeshesAsLightDirty();
  71475. }
  71476. };
  71477. /**
  71478. * Serializes the shadow generator setup to a json object.
  71479. * @returns The serialized JSON object
  71480. */
  71481. ShadowGenerator.prototype.serialize = function () {
  71482. var serializationObject = {};
  71483. var shadowMap = this.getShadowMap();
  71484. if (!shadowMap) {
  71485. return serializationObject;
  71486. }
  71487. serializationObject.lightId = this._light.id;
  71488. serializationObject.mapSize = shadowMap.getRenderSize();
  71489. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  71490. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  71491. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  71492. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  71493. serializationObject.usePoissonSampling = this.usePoissonSampling;
  71494. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  71495. serializationObject.depthScale = this.depthScale;
  71496. serializationObject.darkness = this.getDarkness();
  71497. serializationObject.blurBoxOffset = this.blurBoxOffset;
  71498. serializationObject.blurKernel = this.blurKernel;
  71499. serializationObject.blurScale = this.blurScale;
  71500. serializationObject.useKernelBlur = this.useKernelBlur;
  71501. serializationObject.transparencyShadow = this._transparencyShadow;
  71502. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  71503. serializationObject.bias = this.bias;
  71504. serializationObject.normalBias = this.normalBias;
  71505. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  71506. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  71507. serializationObject.filteringQuality = this.filteringQuality;
  71508. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  71509. serializationObject.renderList = [];
  71510. if (shadowMap.renderList) {
  71511. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  71512. var mesh = shadowMap.renderList[meshIndex];
  71513. serializationObject.renderList.push(mesh.id);
  71514. }
  71515. }
  71516. return serializationObject;
  71517. };
  71518. /**
  71519. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  71520. * @param parsedShadowGenerator The JSON object to parse
  71521. * @param scene The scene to create the shadow map for
  71522. * @returns The parsed shadow generator
  71523. */
  71524. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  71525. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  71526. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  71527. var shadowMap = shadowGenerator.getShadowMap();
  71528. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  71529. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  71530. meshes.forEach(function (mesh) {
  71531. if (!shadowMap) {
  71532. return;
  71533. }
  71534. if (!shadowMap.renderList) {
  71535. shadowMap.renderList = [];
  71536. }
  71537. shadowMap.renderList.push(mesh);
  71538. });
  71539. }
  71540. if (parsedShadowGenerator.usePoissonSampling) {
  71541. shadowGenerator.usePoissonSampling = true;
  71542. }
  71543. else if (parsedShadowGenerator.useExponentialShadowMap) {
  71544. shadowGenerator.useExponentialShadowMap = true;
  71545. }
  71546. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  71547. shadowGenerator.useBlurExponentialShadowMap = true;
  71548. }
  71549. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  71550. shadowGenerator.useCloseExponentialShadowMap = true;
  71551. }
  71552. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  71553. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  71554. }
  71555. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  71556. shadowGenerator.usePercentageCloserFiltering = true;
  71557. }
  71558. else if (parsedShadowGenerator.useContactHardeningShadow) {
  71559. shadowGenerator.useContactHardeningShadow = true;
  71560. }
  71561. if (parsedShadowGenerator.filteringQuality) {
  71562. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  71563. }
  71564. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  71565. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  71566. }
  71567. // Backward compat
  71568. else if (parsedShadowGenerator.useVarianceShadowMap) {
  71569. shadowGenerator.useExponentialShadowMap = true;
  71570. }
  71571. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  71572. shadowGenerator.useBlurExponentialShadowMap = true;
  71573. }
  71574. if (parsedShadowGenerator.depthScale) {
  71575. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  71576. }
  71577. if (parsedShadowGenerator.blurScale) {
  71578. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  71579. }
  71580. if (parsedShadowGenerator.blurBoxOffset) {
  71581. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  71582. }
  71583. if (parsedShadowGenerator.useKernelBlur) {
  71584. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  71585. }
  71586. if (parsedShadowGenerator.blurKernel) {
  71587. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  71588. }
  71589. if (parsedShadowGenerator.bias !== undefined) {
  71590. shadowGenerator.bias = parsedShadowGenerator.bias;
  71591. }
  71592. if (parsedShadowGenerator.normalBias !== undefined) {
  71593. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  71594. }
  71595. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  71596. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  71597. }
  71598. if (parsedShadowGenerator.darkness) {
  71599. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  71600. }
  71601. if (parsedShadowGenerator.transparencyShadow) {
  71602. shadowGenerator.setTransparencyShadow(true);
  71603. }
  71604. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  71605. return shadowGenerator;
  71606. };
  71607. /**
  71608. * Shadow generator mode None: no filtering applied.
  71609. */
  71610. ShadowGenerator.FILTER_NONE = 0;
  71611. /**
  71612. * Shadow generator mode ESM: Exponential Shadow Mapping.
  71613. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71614. */
  71615. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  71616. /**
  71617. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  71618. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  71619. */
  71620. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  71621. /**
  71622. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  71623. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71624. */
  71625. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  71626. /**
  71627. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  71628. * edge artifacts on steep falloff.
  71629. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71630. */
  71631. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  71632. /**
  71633. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  71634. * edge artifacts on steep falloff.
  71635. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71636. */
  71637. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  71638. /**
  71639. * Shadow generator mode PCF: Percentage Closer Filtering
  71640. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71641. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  71642. */
  71643. ShadowGenerator.FILTER_PCF = 6;
  71644. /**
  71645. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  71646. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71647. * Contact Hardening
  71648. */
  71649. ShadowGenerator.FILTER_PCSS = 7;
  71650. /**
  71651. * Reserved for PCF and PCSS
  71652. * Highest Quality.
  71653. *
  71654. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  71655. *
  71656. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  71657. */
  71658. ShadowGenerator.QUALITY_HIGH = 0;
  71659. /**
  71660. * Reserved for PCF and PCSS
  71661. * Good tradeoff for quality/perf cross devices
  71662. *
  71663. * Execute PCF on a 3*3 kernel.
  71664. *
  71665. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  71666. */
  71667. ShadowGenerator.QUALITY_MEDIUM = 1;
  71668. /**
  71669. * Reserved for PCF and PCSS
  71670. * The lowest quality but the fastest.
  71671. *
  71672. * Execute PCF on a 1*1 kernel.
  71673. *
  71674. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  71675. */
  71676. ShadowGenerator.QUALITY_LOW = 2;
  71677. return ShadowGenerator;
  71678. }());
  71679. BABYLON.ShadowGenerator = ShadowGenerator;
  71680. })(BABYLON || (BABYLON = {}));
  71681. //# sourceMappingURL=babylon.shadowGenerator.js.map
  71682. var BABYLON;
  71683. (function (BABYLON) {
  71684. // Adds the parser to the scene parsers.
  71685. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  71686. // Shadows
  71687. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  71688. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  71689. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  71690. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  71691. // SG would be available on their associated lights
  71692. }
  71693. }
  71694. });
  71695. /**
  71696. * Defines the shadow generator component responsible to manage any shadow generators
  71697. * in a given scene.
  71698. */
  71699. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  71700. /**
  71701. * Creates a new instance of the component for the given scene
  71702. * @param scene Defines the scene to register the component in
  71703. */
  71704. function ShadowGeneratorSceneComponent(scene) {
  71705. /**
  71706. * The component name helpfull to identify the component in the list of scene components.
  71707. */
  71708. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  71709. this.scene = scene;
  71710. }
  71711. /**
  71712. * Registers the component in a given scene
  71713. */
  71714. ShadowGeneratorSceneComponent.prototype.register = function () {
  71715. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  71716. };
  71717. /**
  71718. * Rebuilds the elements related to this component in case of
  71719. * context lost for instance.
  71720. */
  71721. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  71722. // Nothing To Do Here.
  71723. };
  71724. /**
  71725. * Serializes the component data to the specified json object
  71726. * @param serializationObject The object to serialize to
  71727. */
  71728. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  71729. // Shadows
  71730. serializationObject.shadowGenerators = [];
  71731. var lights = this.scene.lights;
  71732. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  71733. var light = lights_1[_i];
  71734. var shadowGenerator = light.getShadowGenerator();
  71735. if (shadowGenerator) {
  71736. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71737. }
  71738. }
  71739. };
  71740. /**
  71741. * Adds all the element from the container to the scene
  71742. * @param container the container holding the elements
  71743. */
  71744. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  71745. // Nothing To Do Here. (directly attached to a light)
  71746. };
  71747. /**
  71748. * Removes all the elements in the container from the scene
  71749. * @param container contains the elements to remove
  71750. */
  71751. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  71752. // Nothing To Do Here. (directly attached to a light)
  71753. };
  71754. /**
  71755. * Rebuilds the elements related to this component in case of
  71756. * context lost for instance.
  71757. */
  71758. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  71759. // Nothing To Do Here.
  71760. };
  71761. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  71762. // Shadows
  71763. var scene = this.scene;
  71764. if (this.scene.shadowsEnabled) {
  71765. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  71766. var light = scene.lights[lightIndex];
  71767. var shadowGenerator = light.getShadowGenerator();
  71768. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  71769. var shadowMap = (shadowGenerator.getShadowMap());
  71770. if (scene.textures.indexOf(shadowMap) !== -1) {
  71771. renderTargets.push(shadowMap);
  71772. }
  71773. }
  71774. }
  71775. }
  71776. };
  71777. return ShadowGeneratorSceneComponent;
  71778. }());
  71779. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  71780. })(BABYLON || (BABYLON = {}));
  71781. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  71782. var BABYLON;
  71783. (function (BABYLON) {
  71784. var DefaultLoadingScreen = /** @class */ (function () {
  71785. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  71786. if (_loadingText === void 0) { _loadingText = ""; }
  71787. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  71788. var _this = this;
  71789. this._renderingCanvas = _renderingCanvas;
  71790. this._loadingText = _loadingText;
  71791. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  71792. // Resize
  71793. this._resizeLoadingUI = function () {
  71794. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  71795. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  71796. if (!_this._loadingDiv) {
  71797. return;
  71798. }
  71799. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  71800. _this._loadingDiv.style.left = canvasRect.left + "px";
  71801. _this._loadingDiv.style.top = canvasRect.top + "px";
  71802. _this._loadingDiv.style.width = canvasRect.width + "px";
  71803. _this._loadingDiv.style.height = canvasRect.height + "px";
  71804. };
  71805. }
  71806. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  71807. if (this._loadingDiv) {
  71808. // Do not add a loading screen if there is already one
  71809. return;
  71810. }
  71811. this._loadingDiv = document.createElement("div");
  71812. this._loadingDiv.id = "babylonjsLoadingDiv";
  71813. this._loadingDiv.style.opacity = "0";
  71814. this._loadingDiv.style.transition = "opacity 1.5s ease";
  71815. this._loadingDiv.style.pointerEvents = "none";
  71816. // Loading text
  71817. this._loadingTextDiv = document.createElement("div");
  71818. this._loadingTextDiv.style.position = "absolute";
  71819. this._loadingTextDiv.style.left = "0";
  71820. this._loadingTextDiv.style.top = "50%";
  71821. this._loadingTextDiv.style.marginTop = "80px";
  71822. this._loadingTextDiv.style.width = "100%";
  71823. this._loadingTextDiv.style.height = "20px";
  71824. this._loadingTextDiv.style.fontFamily = "Arial";
  71825. this._loadingTextDiv.style.fontSize = "14px";
  71826. this._loadingTextDiv.style.color = "white";
  71827. this._loadingTextDiv.style.textAlign = "center";
  71828. this._loadingTextDiv.innerHTML = "Loading";
  71829. this._loadingDiv.appendChild(this._loadingTextDiv);
  71830. //set the predefined text
  71831. this._loadingTextDiv.innerHTML = this._loadingText;
  71832. // Generating keyframes
  71833. var style = document.createElement('style');
  71834. style.type = 'text/css';
  71835. 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 }";
  71836. style.innerHTML = keyFrames;
  71837. document.getElementsByTagName('head')[0].appendChild(style);
  71838. // Loading img
  71839. var imgBack = new Image();
  71840. 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";
  71841. imgBack.style.position = "absolute";
  71842. imgBack.style.left = "50%";
  71843. imgBack.style.top = "50%";
  71844. imgBack.style.marginLeft = "-60px";
  71845. imgBack.style.marginTop = "-60px";
  71846. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  71847. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  71848. imgBack.style.transformOrigin = "50% 50%";
  71849. imgBack.style.webkitTransformOrigin = "50% 50%";
  71850. this._loadingDiv.appendChild(imgBack);
  71851. this._resizeLoadingUI();
  71852. window.addEventListener("resize", this._resizeLoadingUI);
  71853. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71854. document.body.appendChild(this._loadingDiv);
  71855. this._loadingDiv.style.opacity = "1";
  71856. };
  71857. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  71858. var _this = this;
  71859. if (!this._loadingDiv) {
  71860. return;
  71861. }
  71862. var onTransitionEnd = function () {
  71863. if (!_this._loadingDiv) {
  71864. return;
  71865. }
  71866. document.body.removeChild(_this._loadingDiv);
  71867. window.removeEventListener("resize", _this._resizeLoadingUI);
  71868. _this._loadingDiv = null;
  71869. };
  71870. this._loadingDiv.style.opacity = "0";
  71871. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  71872. };
  71873. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  71874. set: function (text) {
  71875. this._loadingText = text;
  71876. if (this._loadingTextDiv) {
  71877. this._loadingTextDiv.innerHTML = this._loadingText;
  71878. }
  71879. },
  71880. enumerable: true,
  71881. configurable: true
  71882. });
  71883. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  71884. get: function () {
  71885. return this._loadingDivBackgroundColor;
  71886. },
  71887. set: function (color) {
  71888. this._loadingDivBackgroundColor = color;
  71889. if (!this._loadingDiv) {
  71890. return;
  71891. }
  71892. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71893. },
  71894. enumerable: true,
  71895. configurable: true
  71896. });
  71897. return DefaultLoadingScreen;
  71898. }());
  71899. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  71900. })(BABYLON || (BABYLON = {}));
  71901. //# sourceMappingURL=babylon.loadingScreen.js.map
  71902. var BABYLON;
  71903. (function (BABYLON) {
  71904. var SceneLoaderProgressEvent = /** @class */ (function () {
  71905. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  71906. this.lengthComputable = lengthComputable;
  71907. this.loaded = loaded;
  71908. this.total = total;
  71909. }
  71910. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  71911. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  71912. };
  71913. return SceneLoaderProgressEvent;
  71914. }());
  71915. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  71916. var SceneLoader = /** @class */ (function () {
  71917. function SceneLoader() {
  71918. }
  71919. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  71920. get: function () {
  71921. return 0;
  71922. },
  71923. enumerable: true,
  71924. configurable: true
  71925. });
  71926. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  71927. get: function () {
  71928. return 1;
  71929. },
  71930. enumerable: true,
  71931. configurable: true
  71932. });
  71933. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  71934. get: function () {
  71935. return 2;
  71936. },
  71937. enumerable: true,
  71938. configurable: true
  71939. });
  71940. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  71941. get: function () {
  71942. return 3;
  71943. },
  71944. enumerable: true,
  71945. configurable: true
  71946. });
  71947. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  71948. get: function () {
  71949. return SceneLoader._ForceFullSceneLoadingForIncremental;
  71950. },
  71951. set: function (value) {
  71952. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  71953. },
  71954. enumerable: true,
  71955. configurable: true
  71956. });
  71957. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  71958. get: function () {
  71959. return SceneLoader._ShowLoadingScreen;
  71960. },
  71961. set: function (value) {
  71962. SceneLoader._ShowLoadingScreen = value;
  71963. },
  71964. enumerable: true,
  71965. configurable: true
  71966. });
  71967. Object.defineProperty(SceneLoader, "loggingLevel", {
  71968. get: function () {
  71969. return SceneLoader._loggingLevel;
  71970. },
  71971. set: function (value) {
  71972. SceneLoader._loggingLevel = value;
  71973. },
  71974. enumerable: true,
  71975. configurable: true
  71976. });
  71977. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  71978. get: function () {
  71979. return SceneLoader._CleanBoneMatrixWeights;
  71980. },
  71981. set: function (value) {
  71982. SceneLoader._CleanBoneMatrixWeights = value;
  71983. },
  71984. enumerable: true,
  71985. configurable: true
  71986. });
  71987. SceneLoader._getDefaultPlugin = function () {
  71988. return SceneLoader._registeredPlugins[".babylon"];
  71989. };
  71990. SceneLoader._getPluginForExtension = function (extension) {
  71991. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  71992. if (registeredPlugin) {
  71993. return registeredPlugin;
  71994. }
  71995. 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");
  71996. return SceneLoader._getDefaultPlugin();
  71997. };
  71998. SceneLoader._getPluginForDirectLoad = function (data) {
  71999. for (var extension in SceneLoader._registeredPlugins) {
  72000. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  72001. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  72002. return SceneLoader._registeredPlugins[extension];
  72003. }
  72004. }
  72005. return SceneLoader._getDefaultPlugin();
  72006. };
  72007. SceneLoader._getPluginForFilename = function (sceneFilename) {
  72008. var queryStringPosition = sceneFilename.indexOf("?");
  72009. if (queryStringPosition !== -1) {
  72010. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  72011. }
  72012. var dotPosition = sceneFilename.lastIndexOf(".");
  72013. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  72014. return SceneLoader._getPluginForExtension(extension);
  72015. };
  72016. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  72017. SceneLoader._getDirectLoad = function (sceneFilename) {
  72018. if (sceneFilename.substr(0, 5) === "data:") {
  72019. return sceneFilename.substr(5);
  72020. }
  72021. return null;
  72022. };
  72023. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  72024. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  72025. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  72026. var plugin;
  72027. if (registeredPlugin.plugin.createPlugin) {
  72028. plugin = registeredPlugin.plugin.createPlugin();
  72029. }
  72030. else {
  72031. plugin = registeredPlugin.plugin;
  72032. }
  72033. var useArrayBuffer = registeredPlugin.isBinary;
  72034. var database;
  72035. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  72036. var dataCallback = function (data, responseURL) {
  72037. if (scene.isDisposed) {
  72038. onError("Scene has been disposed");
  72039. return;
  72040. }
  72041. scene.database = database;
  72042. onSuccess(plugin, data, responseURL);
  72043. };
  72044. var request = null;
  72045. var pluginDisposed = false;
  72046. var onDisposeObservable = plugin.onDisposeObservable;
  72047. if (onDisposeObservable) {
  72048. onDisposeObservable.add(function () {
  72049. pluginDisposed = true;
  72050. if (request) {
  72051. request.abort();
  72052. request = null;
  72053. }
  72054. onDispose();
  72055. });
  72056. }
  72057. var manifestChecked = function () {
  72058. if (pluginDisposed) {
  72059. return;
  72060. }
  72061. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  72062. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  72063. } : undefined, database, useArrayBuffer, function (request, exception) {
  72064. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  72065. });
  72066. };
  72067. if (directLoad) {
  72068. dataCallback(directLoad);
  72069. return plugin;
  72070. }
  72071. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  72072. var engine = scene.getEngine();
  72073. var canUseOfflineSupport = engine.enableOfflineSupport;
  72074. if (canUseOfflineSupport) {
  72075. // Also check for exceptions
  72076. var exceptionFound = false;
  72077. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  72078. var regex = _a[_i];
  72079. if (regex.test(fileInfo.url)) {
  72080. exceptionFound = true;
  72081. break;
  72082. }
  72083. }
  72084. canUseOfflineSupport = !exceptionFound;
  72085. }
  72086. if (canUseOfflineSupport) {
  72087. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  72088. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  72089. }
  72090. else {
  72091. manifestChecked();
  72092. }
  72093. }
  72094. // Loading file from disk via input file or drag'n'drop
  72095. else {
  72096. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  72097. if (file) {
  72098. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  72099. }
  72100. else {
  72101. onError("Unable to find file named " + fileInfo.name);
  72102. }
  72103. }
  72104. return plugin;
  72105. };
  72106. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  72107. var url;
  72108. var name;
  72109. if (!sceneFilename) {
  72110. url = rootUrl;
  72111. name = BABYLON.Tools.GetFilename(rootUrl);
  72112. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  72113. }
  72114. else {
  72115. if (sceneFilename.substr(0, 1) === "/") {
  72116. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  72117. return null;
  72118. }
  72119. url = rootUrl + sceneFilename;
  72120. name = sceneFilename;
  72121. }
  72122. ;
  72123. return {
  72124. url: url,
  72125. rootUrl: rootUrl,
  72126. name: name
  72127. };
  72128. };
  72129. // Public functions
  72130. SceneLoader.GetPluginForExtension = function (extension) {
  72131. return SceneLoader._getPluginForExtension(extension).plugin;
  72132. };
  72133. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  72134. return !!SceneLoader._registeredPlugins[extension];
  72135. };
  72136. SceneLoader.RegisterPlugin = function (plugin) {
  72137. if (typeof plugin.extensions === "string") {
  72138. var extension = plugin.extensions;
  72139. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  72140. plugin: plugin,
  72141. isBinary: false
  72142. };
  72143. }
  72144. else {
  72145. var extensions = plugin.extensions;
  72146. Object.keys(extensions).forEach(function (extension) {
  72147. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  72148. plugin: plugin,
  72149. isBinary: extensions[extension].isBinary
  72150. };
  72151. });
  72152. }
  72153. };
  72154. /**
  72155. * Import meshes into a scene
  72156. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  72157. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72158. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72159. * @param scene the instance of BABYLON.Scene to append to
  72160. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  72161. * @param onProgress a callback with a progress event for each file being loaded
  72162. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72163. * @param pluginExtension the extension used to determine the plugin
  72164. * @returns The loaded plugin
  72165. */
  72166. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  72167. if (sceneFilename === void 0) { sceneFilename = ""; }
  72168. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72169. if (onSuccess === void 0) { onSuccess = null; }
  72170. if (onProgress === void 0) { onProgress = null; }
  72171. if (onError === void 0) { onError = null; }
  72172. if (pluginExtension === void 0) { pluginExtension = null; }
  72173. if (!scene) {
  72174. BABYLON.Tools.Error("No scene available to import mesh to");
  72175. return null;
  72176. }
  72177. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  72178. if (!fileInfo) {
  72179. return null;
  72180. }
  72181. var loadingToken = {};
  72182. scene._addPendingData(loadingToken);
  72183. var disposeHandler = function () {
  72184. scene._removePendingData(loadingToken);
  72185. };
  72186. var errorHandler = function (message, exception) {
  72187. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  72188. if (onError) {
  72189. onError(scene, errorMessage, exception);
  72190. }
  72191. else {
  72192. BABYLON.Tools.Error(errorMessage);
  72193. // should the exception be thrown?
  72194. }
  72195. disposeHandler();
  72196. };
  72197. var progressHandler = onProgress ? function (event) {
  72198. try {
  72199. onProgress(event);
  72200. }
  72201. catch (e) {
  72202. errorHandler("Error in onProgress callback", e);
  72203. }
  72204. } : undefined;
  72205. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  72206. scene.importedMeshesFiles.push(fileInfo.url);
  72207. if (onSuccess) {
  72208. try {
  72209. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  72210. }
  72211. catch (e) {
  72212. errorHandler("Error in onSuccess callback", e);
  72213. }
  72214. }
  72215. scene._removePendingData(loadingToken);
  72216. };
  72217. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  72218. if (plugin.rewriteRootURL) {
  72219. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  72220. }
  72221. if (plugin.importMesh) {
  72222. var syncedPlugin = plugin;
  72223. var meshes = new Array();
  72224. var particleSystems = new Array();
  72225. var skeletons = new Array();
  72226. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  72227. return;
  72228. }
  72229. scene.loadingPluginName = plugin.name;
  72230. successHandler(meshes, particleSystems, skeletons, []);
  72231. }
  72232. else {
  72233. var asyncedPlugin = plugin;
  72234. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  72235. scene.loadingPluginName = plugin.name;
  72236. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  72237. }).catch(function (error) {
  72238. errorHandler(error.message, error);
  72239. });
  72240. }
  72241. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  72242. };
  72243. /**
  72244. * Import meshes into a scene
  72245. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  72246. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72247. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72248. * @param scene the instance of BABYLON.Scene to append to
  72249. * @param onProgress a callback with a progress event for each file being loaded
  72250. * @param pluginExtension the extension used to determine the plugin
  72251. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  72252. */
  72253. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  72254. if (sceneFilename === void 0) { sceneFilename = ""; }
  72255. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72256. if (onProgress === void 0) { onProgress = null; }
  72257. if (pluginExtension === void 0) { pluginExtension = null; }
  72258. return new Promise(function (resolve, reject) {
  72259. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  72260. resolve({
  72261. meshes: meshes,
  72262. particleSystems: particleSystems,
  72263. skeletons: skeletons,
  72264. animationGroups: animationGroups
  72265. });
  72266. }, onProgress, function (scene, message, exception) {
  72267. reject(exception || new Error(message));
  72268. }, pluginExtension);
  72269. });
  72270. };
  72271. /**
  72272. * Load a scene
  72273. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72274. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72275. * @param engine is the instance of BABYLON.Engine to use to create the scene
  72276. * @param onSuccess a callback with the scene when import succeeds
  72277. * @param onProgress a callback with a progress event for each file being loaded
  72278. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72279. * @param pluginExtension the extension used to determine the plugin
  72280. * @returns The loaded plugin
  72281. */
  72282. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  72283. if (onSuccess === void 0) { onSuccess = null; }
  72284. if (onProgress === void 0) { onProgress = null; }
  72285. if (onError === void 0) { onError = null; }
  72286. if (pluginExtension === void 0) { pluginExtension = null; }
  72287. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  72288. };
  72289. /**
  72290. * Load a scene
  72291. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72292. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72293. * @param engine is the instance of BABYLON.Engine to use to create the scene
  72294. * @param onProgress a callback with a progress event for each file being loaded
  72295. * @param pluginExtension the extension used to determine the plugin
  72296. * @returns The loaded scene
  72297. */
  72298. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  72299. if (onProgress === void 0) { onProgress = null; }
  72300. if (pluginExtension === void 0) { pluginExtension = null; }
  72301. return new Promise(function (resolve, reject) {
  72302. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  72303. resolve(scene);
  72304. }, onProgress, function (scene, message, exception) {
  72305. reject(exception || new Error(message));
  72306. }, pluginExtension);
  72307. });
  72308. };
  72309. /**
  72310. * Append a scene
  72311. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72312. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72313. * @param scene is the instance of BABYLON.Scene to append to
  72314. * @param onSuccess a callback with the scene when import succeeds
  72315. * @param onProgress a callback with a progress event for each file being loaded
  72316. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72317. * @param pluginExtension the extension used to determine the plugin
  72318. * @returns The loaded plugin
  72319. */
  72320. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  72321. if (sceneFilename === void 0) { sceneFilename = ""; }
  72322. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72323. if (onSuccess === void 0) { onSuccess = null; }
  72324. if (onProgress === void 0) { onProgress = null; }
  72325. if (onError === void 0) { onError = null; }
  72326. if (pluginExtension === void 0) { pluginExtension = null; }
  72327. if (!scene) {
  72328. BABYLON.Tools.Error("No scene available to append to");
  72329. return null;
  72330. }
  72331. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  72332. if (!fileInfo) {
  72333. return null;
  72334. }
  72335. if (SceneLoader.ShowLoadingScreen) {
  72336. scene.getEngine().displayLoadingUI();
  72337. }
  72338. var loadingToken = {};
  72339. scene._addPendingData(loadingToken);
  72340. var disposeHandler = function () {
  72341. scene._removePendingData(loadingToken);
  72342. scene.getEngine().hideLoadingUI();
  72343. };
  72344. var errorHandler = function (message, exception) {
  72345. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  72346. if (onError) {
  72347. onError(scene, errorMessage, exception);
  72348. }
  72349. else {
  72350. BABYLON.Tools.Error(errorMessage);
  72351. // should the exception be thrown?
  72352. }
  72353. disposeHandler();
  72354. };
  72355. var progressHandler = onProgress ? function (event) {
  72356. try {
  72357. onProgress(event);
  72358. }
  72359. catch (e) {
  72360. errorHandler("Error in onProgress callback", e);
  72361. }
  72362. } : undefined;
  72363. var successHandler = function () {
  72364. if (onSuccess) {
  72365. try {
  72366. onSuccess(scene);
  72367. }
  72368. catch (e) {
  72369. errorHandler("Error in onSuccess callback", e);
  72370. }
  72371. }
  72372. scene._removePendingData(loadingToken);
  72373. };
  72374. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  72375. if (plugin.load) {
  72376. var syncedPlugin = plugin;
  72377. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  72378. return;
  72379. }
  72380. scene.loadingPluginName = plugin.name;
  72381. successHandler();
  72382. }
  72383. else {
  72384. var asyncedPlugin = plugin;
  72385. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  72386. scene.loadingPluginName = plugin.name;
  72387. successHandler();
  72388. }).catch(function (error) {
  72389. errorHandler(error.message, error);
  72390. });
  72391. }
  72392. if (SceneLoader.ShowLoadingScreen) {
  72393. scene.executeWhenReady(function () {
  72394. scene.getEngine().hideLoadingUI();
  72395. });
  72396. }
  72397. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  72398. };
  72399. /**
  72400. * Append a scene
  72401. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72402. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72403. * @param scene is the instance of BABYLON.Scene to append to
  72404. * @param onProgress a callback with a progress event for each file being loaded
  72405. * @param pluginExtension the extension used to determine the plugin
  72406. * @returns The given scene
  72407. */
  72408. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  72409. if (sceneFilename === void 0) { sceneFilename = ""; }
  72410. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72411. if (onProgress === void 0) { onProgress = null; }
  72412. if (pluginExtension === void 0) { pluginExtension = null; }
  72413. return new Promise(function (resolve, reject) {
  72414. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  72415. resolve(scene);
  72416. }, onProgress, function (scene, message, exception) {
  72417. reject(exception || new Error(message));
  72418. }, pluginExtension);
  72419. });
  72420. };
  72421. /**
  72422. * Load a scene into an asset container
  72423. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72424. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72425. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  72426. * @param onSuccess a callback with the scene when import succeeds
  72427. * @param onProgress a callback with a progress event for each file being loaded
  72428. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72429. * @param pluginExtension the extension used to determine the plugin
  72430. * @returns The loaded plugin
  72431. */
  72432. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  72433. if (sceneFilename === void 0) { sceneFilename = ""; }
  72434. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72435. if (onSuccess === void 0) { onSuccess = null; }
  72436. if (onProgress === void 0) { onProgress = null; }
  72437. if (onError === void 0) { onError = null; }
  72438. if (pluginExtension === void 0) { pluginExtension = null; }
  72439. if (!scene) {
  72440. BABYLON.Tools.Error("No scene available to load asset container to");
  72441. return null;
  72442. }
  72443. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  72444. if (!fileInfo) {
  72445. return null;
  72446. }
  72447. var loadingToken = {};
  72448. scene._addPendingData(loadingToken);
  72449. var disposeHandler = function () {
  72450. scene._removePendingData(loadingToken);
  72451. };
  72452. var errorHandler = function (message, exception) {
  72453. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  72454. if (onError) {
  72455. onError(scene, errorMessage, exception);
  72456. }
  72457. else {
  72458. BABYLON.Tools.Error(errorMessage);
  72459. // should the exception be thrown?
  72460. }
  72461. disposeHandler();
  72462. };
  72463. var progressHandler = onProgress ? function (event) {
  72464. try {
  72465. onProgress(event);
  72466. }
  72467. catch (e) {
  72468. errorHandler("Error in onProgress callback", e);
  72469. }
  72470. } : undefined;
  72471. var successHandler = function (assets) {
  72472. if (onSuccess) {
  72473. try {
  72474. onSuccess(assets);
  72475. }
  72476. catch (e) {
  72477. errorHandler("Error in onSuccess callback", e);
  72478. }
  72479. }
  72480. scene._removePendingData(loadingToken);
  72481. };
  72482. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  72483. if (plugin.loadAssetContainer) {
  72484. var syncedPlugin = plugin;
  72485. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  72486. if (!assetContainer) {
  72487. return;
  72488. }
  72489. scene.loadingPluginName = plugin.name;
  72490. successHandler(assetContainer);
  72491. }
  72492. else if (plugin.loadAssetContainerAsync) {
  72493. var asyncedPlugin = plugin;
  72494. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  72495. scene.loadingPluginName = plugin.name;
  72496. successHandler(assetContainer);
  72497. }).catch(function (error) {
  72498. errorHandler(error.message, error);
  72499. });
  72500. }
  72501. else {
  72502. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  72503. }
  72504. if (SceneLoader.ShowLoadingScreen) {
  72505. scene.executeWhenReady(function () {
  72506. scene.getEngine().hideLoadingUI();
  72507. });
  72508. }
  72509. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  72510. };
  72511. /**
  72512. * Load a scene into an asset container
  72513. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  72514. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  72515. * @param scene is the instance of BABYLON.Scene to append to
  72516. * @param onProgress a callback with a progress event for each file being loaded
  72517. * @param pluginExtension the extension used to determine the plugin
  72518. * @returns The loaded asset container
  72519. */
  72520. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  72521. if (sceneFilename === void 0) { sceneFilename = ""; }
  72522. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72523. if (onProgress === void 0) { onProgress = null; }
  72524. if (pluginExtension === void 0) { pluginExtension = null; }
  72525. return new Promise(function (resolve, reject) {
  72526. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  72527. resolve(assetContainer);
  72528. }, onProgress, function (scene, message, exception) {
  72529. reject(exception || new Error(message));
  72530. }, pluginExtension);
  72531. });
  72532. };
  72533. // Flags
  72534. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  72535. SceneLoader._ShowLoadingScreen = true;
  72536. SceneLoader._CleanBoneMatrixWeights = false;
  72537. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  72538. // Members
  72539. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  72540. SceneLoader._registeredPlugins = {};
  72541. return SceneLoader;
  72542. }());
  72543. BABYLON.SceneLoader = SceneLoader;
  72544. ;
  72545. })(BABYLON || (BABYLON = {}));
  72546. //# sourceMappingURL=babylon.sceneLoader.js.map
  72547. var BABYLON;
  72548. (function (BABYLON) {
  72549. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  72550. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72551. var parsedMaterial = parsedData.materials[index];
  72552. if (parsedMaterial.id === id) {
  72553. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72554. }
  72555. }
  72556. return null;
  72557. };
  72558. var isDescendantOf = function (mesh, names, hierarchyIds) {
  72559. for (var i in names) {
  72560. if (mesh.name === names[i]) {
  72561. hierarchyIds.push(mesh.id);
  72562. return true;
  72563. }
  72564. }
  72565. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  72566. hierarchyIds.push(mesh.id);
  72567. return true;
  72568. }
  72569. return false;
  72570. };
  72571. var logOperation = function (operation, producer) {
  72572. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  72573. };
  72574. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  72575. if (addToScene === void 0) { addToScene = false; }
  72576. var container = new BABYLON.AssetContainer(scene);
  72577. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72578. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72579. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72580. // and avoid problems with multiple concurrent .babylon loads.
  72581. var log = "importScene has failed JSON parse";
  72582. try {
  72583. var parsedData = JSON.parse(data);
  72584. log = "";
  72585. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72586. var index;
  72587. var cache;
  72588. // Lights
  72589. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  72590. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  72591. var parsedLight = parsedData.lights[index];
  72592. var light = BABYLON.Light.Parse(parsedLight, scene);
  72593. if (light) {
  72594. container.lights.push(light);
  72595. log += (index === 0 ? "\n\tLights:" : "");
  72596. log += "\n\t\t" + light.toString(fullDetails);
  72597. }
  72598. }
  72599. }
  72600. // Animations
  72601. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  72602. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  72603. var parsedAnimation = parsedData.animations[index];
  72604. var animation = BABYLON.Animation.Parse(parsedAnimation);
  72605. scene.animations.push(animation);
  72606. container.animations.push(animation);
  72607. log += (index === 0 ? "\n\tAnimations:" : "");
  72608. log += "\n\t\t" + animation.toString(fullDetails);
  72609. }
  72610. }
  72611. // Materials
  72612. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  72613. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72614. var parsedMaterial = parsedData.materials[index];
  72615. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72616. container.materials.push(mat);
  72617. log += (index === 0 ? "\n\tMaterials:" : "");
  72618. log += "\n\t\t" + mat.toString(fullDetails);
  72619. }
  72620. }
  72621. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72622. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  72623. var parsedMultiMaterial = parsedData.multiMaterials[index];
  72624. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72625. container.multiMaterials.push(mmat);
  72626. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  72627. log += "\n\t\t" + mmat.toString(fullDetails);
  72628. }
  72629. }
  72630. // Morph targets
  72631. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72632. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72633. var managerData = _a[_i];
  72634. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  72635. }
  72636. }
  72637. // Skeletons
  72638. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72639. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  72640. var parsedSkeleton = parsedData.skeletons[index];
  72641. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72642. container.skeletons.push(skeleton);
  72643. log += (index === 0 ? "\n\tSkeletons:" : "");
  72644. log += "\n\t\t" + skeleton.toString(fullDetails);
  72645. }
  72646. }
  72647. // Geometries
  72648. var geometries = parsedData.geometries;
  72649. if (geometries !== undefined && geometries !== null) {
  72650. var addedGeometry = new Array();
  72651. // Boxes
  72652. var boxes = geometries.boxes;
  72653. if (boxes !== undefined && boxes !== null) {
  72654. for (index = 0, cache = boxes.length; index < cache; index++) {
  72655. var parsedBox = boxes[index];
  72656. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  72657. }
  72658. }
  72659. // Spheres
  72660. var spheres = geometries.spheres;
  72661. if (spheres !== undefined && spheres !== null) {
  72662. for (index = 0, cache = spheres.length; index < cache; index++) {
  72663. var parsedSphere = spheres[index];
  72664. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  72665. }
  72666. }
  72667. // Cylinders
  72668. var cylinders = geometries.cylinders;
  72669. if (cylinders !== undefined && cylinders !== null) {
  72670. for (index = 0, cache = cylinders.length; index < cache; index++) {
  72671. var parsedCylinder = cylinders[index];
  72672. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  72673. }
  72674. }
  72675. // Toruses
  72676. var toruses = geometries.toruses;
  72677. if (toruses !== undefined && toruses !== null) {
  72678. for (index = 0, cache = toruses.length; index < cache; index++) {
  72679. var parsedTorus = toruses[index];
  72680. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  72681. }
  72682. }
  72683. // Grounds
  72684. var grounds = geometries.grounds;
  72685. if (grounds !== undefined && grounds !== null) {
  72686. for (index = 0, cache = grounds.length; index < cache; index++) {
  72687. var parsedGround = grounds[index];
  72688. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  72689. }
  72690. }
  72691. // Planes
  72692. var planes = geometries.planes;
  72693. if (planes !== undefined && planes !== null) {
  72694. for (index = 0, cache = planes.length; index < cache; index++) {
  72695. var parsedPlane = planes[index];
  72696. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  72697. }
  72698. }
  72699. // TorusKnots
  72700. var torusKnots = geometries.torusKnots;
  72701. if (torusKnots !== undefined && torusKnots !== null) {
  72702. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  72703. var parsedTorusKnot = torusKnots[index];
  72704. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  72705. }
  72706. }
  72707. // VertexData
  72708. var vertexData = geometries.vertexData;
  72709. if (vertexData !== undefined && vertexData !== null) {
  72710. for (index = 0, cache = vertexData.length; index < cache; index++) {
  72711. var parsedVertexData = vertexData[index];
  72712. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  72713. }
  72714. }
  72715. addedGeometry.forEach(function (g) {
  72716. if (g) {
  72717. container.geometries.push(g);
  72718. }
  72719. });
  72720. }
  72721. // Transform nodes
  72722. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  72723. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  72724. var parsedTransformNode = parsedData.transformNodes[index];
  72725. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  72726. container.transformNodes.push(node);
  72727. }
  72728. }
  72729. // Meshes
  72730. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72731. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72732. var parsedMesh = parsedData.meshes[index];
  72733. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72734. container.meshes.push(mesh);
  72735. log += (index === 0 ? "\n\tMeshes:" : "");
  72736. log += "\n\t\t" + mesh.toString(fullDetails);
  72737. }
  72738. }
  72739. // Cameras
  72740. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  72741. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  72742. var parsedCamera = parsedData.cameras[index];
  72743. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  72744. container.cameras.push(camera);
  72745. log += (index === 0 ? "\n\tCameras:" : "");
  72746. log += "\n\t\t" + camera.toString(fullDetails);
  72747. }
  72748. }
  72749. // Animation Groups
  72750. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  72751. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  72752. var parsedAnimationGroup = parsedData.animationGroups[index];
  72753. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  72754. container.animationGroups.push(animationGroup);
  72755. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  72756. log += "\n\t\t" + animationGroup.toString(fullDetails);
  72757. }
  72758. }
  72759. // Browsing all the graph to connect the dots
  72760. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  72761. var camera = scene.cameras[index];
  72762. if (camera._waitingParentId) {
  72763. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  72764. camera._waitingParentId = null;
  72765. }
  72766. }
  72767. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72768. var light_1 = scene.lights[index];
  72769. if (light_1 && light_1._waitingParentId) {
  72770. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  72771. light_1._waitingParentId = null;
  72772. }
  72773. }
  72774. // Connect parents & children and parse actions
  72775. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  72776. var transformNode = scene.transformNodes[index];
  72777. if (transformNode._waitingParentId) {
  72778. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  72779. transformNode._waitingParentId = null;
  72780. }
  72781. }
  72782. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72783. var mesh = scene.meshes[index];
  72784. if (mesh._waitingParentId) {
  72785. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  72786. mesh._waitingParentId = null;
  72787. }
  72788. if (mesh._waitingActions) {
  72789. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  72790. mesh._waitingActions = null;
  72791. }
  72792. }
  72793. // freeze world matrix application
  72794. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72795. var currentMesh = scene.meshes[index];
  72796. if (currentMesh._waitingFreezeWorldMatrix) {
  72797. currentMesh.freezeWorldMatrix();
  72798. currentMesh._waitingFreezeWorldMatrix = null;
  72799. }
  72800. else {
  72801. currentMesh.computeWorldMatrix(true);
  72802. }
  72803. }
  72804. // Lights exclusions / inclusions
  72805. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72806. var light_2 = scene.lights[index];
  72807. // Excluded check
  72808. if (light_2._excludedMeshesIds.length > 0) {
  72809. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  72810. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  72811. if (excludedMesh) {
  72812. light_2.excludedMeshes.push(excludedMesh);
  72813. }
  72814. }
  72815. light_2._excludedMeshesIds = [];
  72816. }
  72817. // Included check
  72818. if (light_2._includedOnlyMeshesIds.length > 0) {
  72819. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  72820. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  72821. if (includedOnlyMesh) {
  72822. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  72823. }
  72824. }
  72825. light_2._includedOnlyMeshesIds = [];
  72826. }
  72827. }
  72828. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  72829. // Actions (scene)
  72830. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  72831. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  72832. }
  72833. if (!addToScene) {
  72834. container.removeAllFromScene();
  72835. }
  72836. }
  72837. catch (err) {
  72838. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  72839. if (onError) {
  72840. onError(msg, err);
  72841. }
  72842. else {
  72843. BABYLON.Tools.Log(msg);
  72844. throw err;
  72845. }
  72846. }
  72847. finally {
  72848. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72849. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72850. }
  72851. }
  72852. return container;
  72853. };
  72854. BABYLON.SceneLoader.RegisterPlugin({
  72855. name: "babylon.js",
  72856. extensions: ".babylon",
  72857. canDirectLoad: function (data) {
  72858. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  72859. return true;
  72860. }
  72861. return false;
  72862. },
  72863. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  72864. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72865. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72866. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72867. // and avoid problems with multiple concurrent .babylon loads.
  72868. var log = "importMesh has failed JSON parse";
  72869. try {
  72870. var parsedData = JSON.parse(data);
  72871. log = "";
  72872. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72873. if (!meshesNames) {
  72874. meshesNames = null;
  72875. }
  72876. else if (!Array.isArray(meshesNames)) {
  72877. meshesNames = [meshesNames];
  72878. }
  72879. var hierarchyIds = new Array();
  72880. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72881. var loadedSkeletonsIds = [];
  72882. var loadedMaterialsIds = [];
  72883. var index;
  72884. var cache;
  72885. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72886. var parsedMesh = parsedData.meshes[index];
  72887. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  72888. if (meshesNames !== null) {
  72889. // Remove found mesh name from list.
  72890. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  72891. }
  72892. //Geometry?
  72893. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  72894. //does the file contain geometries?
  72895. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  72896. //find the correct geometry and add it to the scene
  72897. var found = false;
  72898. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  72899. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  72900. return;
  72901. }
  72902. else {
  72903. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  72904. if (parsedGeometryData.id === parsedMesh.geometryId) {
  72905. switch (geometryType) {
  72906. case "boxes":
  72907. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  72908. break;
  72909. case "spheres":
  72910. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  72911. break;
  72912. case "cylinders":
  72913. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  72914. break;
  72915. case "toruses":
  72916. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  72917. break;
  72918. case "grounds":
  72919. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  72920. break;
  72921. case "planes":
  72922. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  72923. break;
  72924. case "torusKnots":
  72925. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  72926. break;
  72927. case "vertexData":
  72928. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  72929. break;
  72930. }
  72931. found = true;
  72932. }
  72933. });
  72934. }
  72935. });
  72936. if (found === false) {
  72937. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  72938. }
  72939. }
  72940. }
  72941. // Material ?
  72942. if (parsedMesh.materialId) {
  72943. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  72944. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72945. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  72946. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  72947. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  72948. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  72949. var subMatId = parsedMultiMaterial.materials[matIndex];
  72950. loadedMaterialsIds.push(subMatId);
  72951. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  72952. if (mat) {
  72953. log += "\n\tMaterial " + mat.toString(fullDetails);
  72954. }
  72955. }
  72956. loadedMaterialsIds.push(parsedMultiMaterial.id);
  72957. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72958. if (mmat) {
  72959. materialFound = true;
  72960. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  72961. }
  72962. break;
  72963. }
  72964. }
  72965. }
  72966. if (materialFound === false) {
  72967. loadedMaterialsIds.push(parsedMesh.materialId);
  72968. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  72969. if (!mat) {
  72970. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  72971. }
  72972. else {
  72973. log += "\n\tMaterial " + mat.toString(fullDetails);
  72974. }
  72975. }
  72976. }
  72977. // Skeleton ?
  72978. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72979. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  72980. if (skeletonAlreadyLoaded === false) {
  72981. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  72982. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  72983. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  72984. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72985. skeletons.push(skeleton);
  72986. loadedSkeletonsIds.push(parsedSkeleton.id);
  72987. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  72988. }
  72989. }
  72990. }
  72991. }
  72992. // Morph targets ?
  72993. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72994. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72995. var managerData = _a[_i];
  72996. BABYLON.MorphTargetManager.Parse(managerData, scene);
  72997. }
  72998. }
  72999. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  73000. meshes.push(mesh);
  73001. log += "\n\tMesh " + mesh.toString(fullDetails);
  73002. }
  73003. }
  73004. // Connecting parents
  73005. var currentMesh;
  73006. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  73007. currentMesh = scene.meshes[index];
  73008. if (currentMesh._waitingParentId) {
  73009. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  73010. currentMesh._waitingParentId = null;
  73011. }
  73012. }
  73013. // freeze and compute world matrix application
  73014. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  73015. currentMesh = scene.meshes[index];
  73016. if (currentMesh._waitingFreezeWorldMatrix) {
  73017. currentMesh.freezeWorldMatrix();
  73018. currentMesh._waitingFreezeWorldMatrix = null;
  73019. }
  73020. else {
  73021. currentMesh.computeWorldMatrix(true);
  73022. }
  73023. }
  73024. }
  73025. // Particles
  73026. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  73027. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  73028. if (parser) {
  73029. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  73030. var parsedParticleSystem = parsedData.particleSystems[index];
  73031. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  73032. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  73033. }
  73034. }
  73035. }
  73036. }
  73037. return true;
  73038. }
  73039. catch (err) {
  73040. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  73041. if (onError) {
  73042. onError(msg, err);
  73043. }
  73044. else {
  73045. BABYLON.Tools.Log(msg);
  73046. throw err;
  73047. }
  73048. }
  73049. finally {
  73050. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  73051. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  73052. }
  73053. }
  73054. return false;
  73055. },
  73056. load: function (scene, data, rootUrl, onError) {
  73057. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  73058. // when SceneLoader.debugLogging = true (default), or exception encountered.
  73059. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  73060. // and avoid problems with multiple concurrent .babylon loads.
  73061. var log = "importScene has failed JSON parse";
  73062. try {
  73063. var parsedData = JSON.parse(data);
  73064. log = "";
  73065. // Scene
  73066. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  73067. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  73068. }
  73069. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  73070. scene.autoClear = parsedData.autoClear;
  73071. }
  73072. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  73073. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  73074. }
  73075. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  73076. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  73077. }
  73078. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  73079. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  73080. }
  73081. // Fog
  73082. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  73083. scene.fogMode = parsedData.fogMode;
  73084. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  73085. scene.fogStart = parsedData.fogStart;
  73086. scene.fogEnd = parsedData.fogEnd;
  73087. scene.fogDensity = parsedData.fogDensity;
  73088. log += "\tFog mode for scene: ";
  73089. switch (scene.fogMode) {
  73090. // getters not compiling, so using hardcoded
  73091. case 1:
  73092. log += "exp\n";
  73093. break;
  73094. case 2:
  73095. log += "exp2\n";
  73096. break;
  73097. case 3:
  73098. log += "linear\n";
  73099. break;
  73100. }
  73101. }
  73102. //Physics
  73103. if (parsedData.physicsEnabled) {
  73104. var physicsPlugin;
  73105. if (parsedData.physicsEngine === "cannon") {
  73106. physicsPlugin = new BABYLON.CannonJSPlugin();
  73107. }
  73108. else if (parsedData.physicsEngine === "oimo") {
  73109. physicsPlugin = new BABYLON.OimoJSPlugin();
  73110. }
  73111. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  73112. //else - default engine, which is currently oimo
  73113. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  73114. scene.enablePhysics(physicsGravity, physicsPlugin);
  73115. }
  73116. // Metadata
  73117. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  73118. scene.metadata = parsedData.metadata;
  73119. }
  73120. //collisions, if defined. otherwise, default is true
  73121. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  73122. scene.collisionsEnabled = parsedData.collisionsEnabled;
  73123. }
  73124. scene.workerCollisions = !!parsedData.workerCollisions;
  73125. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  73126. if (!container) {
  73127. return false;
  73128. }
  73129. if (parsedData.autoAnimate) {
  73130. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  73131. }
  73132. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  73133. scene.setActiveCameraByID(parsedData.activeCameraID);
  73134. }
  73135. // Environment texture
  73136. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  73137. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  73138. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  73139. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  73140. if (parsedData.environmentTextureRotationY) {
  73141. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  73142. }
  73143. scene.environmentTexture = hdrTexture;
  73144. }
  73145. else {
  73146. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  73147. if (parsedData.environmentTextureRotationY) {
  73148. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  73149. }
  73150. scene.environmentTexture = cubeTexture;
  73151. }
  73152. if (parsedData.createDefaultSkybox === true) {
  73153. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  73154. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  73155. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  73156. }
  73157. }
  73158. // Finish
  73159. return true;
  73160. }
  73161. catch (err) {
  73162. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  73163. if (onError) {
  73164. onError(msg, err);
  73165. }
  73166. else {
  73167. BABYLON.Tools.Log(msg);
  73168. throw err;
  73169. }
  73170. }
  73171. finally {
  73172. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  73173. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  73174. }
  73175. }
  73176. return false;
  73177. },
  73178. loadAssetContainer: function (scene, data, rootUrl, onError) {
  73179. var container = loadAssetContainer(scene, data, rootUrl, onError);
  73180. return container;
  73181. }
  73182. });
  73183. })(BABYLON || (BABYLON = {}));
  73184. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  73185. var BABYLON;
  73186. (function (BABYLON) {
  73187. var FilesInput = /** @class */ (function () {
  73188. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  73189. this.onProcessFileCallback = function () { return true; };
  73190. this._engine = engine;
  73191. this._currentScene = scene;
  73192. this._sceneLoadedCallback = sceneLoadedCallback;
  73193. this._progressCallback = progressCallback;
  73194. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  73195. this._textureLoadingCallback = textureLoadingCallback;
  73196. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  73197. this._onReloadCallback = onReloadCallback;
  73198. this._errorCallback = errorCallback;
  73199. }
  73200. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  73201. var _this = this;
  73202. if (elementToMonitor) {
  73203. this._elementToMonitor = elementToMonitor;
  73204. this._dragEnterHandler = function (e) { _this.drag(e); };
  73205. this._dragOverHandler = function (e) { _this.drag(e); };
  73206. this._dropHandler = function (e) { _this.drop(e); };
  73207. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  73208. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  73209. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  73210. }
  73211. };
  73212. FilesInput.prototype.dispose = function () {
  73213. if (!this._elementToMonitor) {
  73214. return;
  73215. }
  73216. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  73217. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  73218. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  73219. };
  73220. FilesInput.prototype.renderFunction = function () {
  73221. if (this._additionalRenderLoopLogicCallback) {
  73222. this._additionalRenderLoopLogicCallback();
  73223. }
  73224. if (this._currentScene) {
  73225. if (this._textureLoadingCallback) {
  73226. var remaining = this._currentScene.getWaitingItemsCount();
  73227. if (remaining > 0) {
  73228. this._textureLoadingCallback(remaining);
  73229. }
  73230. }
  73231. this._currentScene.render();
  73232. }
  73233. };
  73234. FilesInput.prototype.drag = function (e) {
  73235. e.stopPropagation();
  73236. e.preventDefault();
  73237. };
  73238. FilesInput.prototype.drop = function (eventDrop) {
  73239. eventDrop.stopPropagation();
  73240. eventDrop.preventDefault();
  73241. this.loadFiles(eventDrop);
  73242. };
  73243. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  73244. var _this = this;
  73245. var reader = folder.createReader();
  73246. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  73247. reader.readEntries(function (entries) {
  73248. remaining.count += entries.length;
  73249. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  73250. var entry = entries_1[_i];
  73251. if (entry.isFile) {
  73252. entry.file(function (file) {
  73253. file.correctName = relativePath + file.name;
  73254. files.push(file);
  73255. if (--remaining.count === 0) {
  73256. callback();
  73257. }
  73258. });
  73259. }
  73260. else if (entry.isDirectory) {
  73261. _this._traverseFolder(entry, files, remaining, callback);
  73262. }
  73263. }
  73264. if (--remaining.count) {
  73265. callback();
  73266. }
  73267. });
  73268. };
  73269. FilesInput.prototype._processFiles = function (files) {
  73270. for (var i = 0; i < files.length; i++) {
  73271. var name = files[i].correctName.toLowerCase();
  73272. var extension = name.split('.').pop();
  73273. if (!this.onProcessFileCallback(files[i], name, extension)) {
  73274. continue;
  73275. }
  73276. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  73277. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  73278. this._sceneFileToLoad = files[i];
  73279. }
  73280. FilesInput.FilesToLoad[name] = files[i];
  73281. }
  73282. };
  73283. FilesInput.prototype.loadFiles = function (event) {
  73284. var _this = this;
  73285. // Handling data transfer via drag'n'drop
  73286. if (event && event.dataTransfer && event.dataTransfer.files) {
  73287. this._filesToLoad = event.dataTransfer.files;
  73288. }
  73289. // Handling files from input files
  73290. if (event && event.target && event.target.files) {
  73291. this._filesToLoad = event.target.files;
  73292. }
  73293. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  73294. return;
  73295. }
  73296. if (this._startingProcessingFilesCallback) {
  73297. this._startingProcessingFilesCallback(this._filesToLoad);
  73298. }
  73299. if (this._filesToLoad && this._filesToLoad.length > 0) {
  73300. var files_1 = new Array();
  73301. var folders = [];
  73302. var items = event.dataTransfer ? event.dataTransfer.items : null;
  73303. for (var i = 0; i < this._filesToLoad.length; i++) {
  73304. var fileToLoad = this._filesToLoad[i];
  73305. var name_1 = fileToLoad.name.toLowerCase();
  73306. var entry = void 0;
  73307. fileToLoad.correctName = name_1;
  73308. if (items) {
  73309. var item = items[i];
  73310. if (item.getAsEntry) {
  73311. entry = item.getAsEntry();
  73312. }
  73313. else if (item.webkitGetAsEntry) {
  73314. entry = item.webkitGetAsEntry();
  73315. }
  73316. }
  73317. if (!entry) {
  73318. files_1.push(fileToLoad);
  73319. }
  73320. else {
  73321. if (entry.isDirectory) {
  73322. folders.push(entry);
  73323. }
  73324. else {
  73325. files_1.push(fileToLoad);
  73326. }
  73327. }
  73328. }
  73329. if (folders.length === 0) {
  73330. this._processFiles(files_1);
  73331. this._processReload();
  73332. }
  73333. else {
  73334. var remaining = { count: folders.length };
  73335. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  73336. var folder = folders_1[_i];
  73337. this._traverseFolder(folder, files_1, remaining, function () {
  73338. _this._processFiles(files_1);
  73339. if (remaining.count === 0) {
  73340. _this._processReload();
  73341. }
  73342. });
  73343. }
  73344. }
  73345. }
  73346. };
  73347. FilesInput.prototype._processReload = function () {
  73348. if (this._onReloadCallback) {
  73349. this._onReloadCallback(this._sceneFileToLoad);
  73350. }
  73351. else {
  73352. this.reload();
  73353. }
  73354. };
  73355. FilesInput.prototype.reload = function () {
  73356. var _this = this;
  73357. // If a scene file has been provided
  73358. if (this._sceneFileToLoad) {
  73359. if (this._currentScene) {
  73360. if (BABYLON.Tools.errorsCount > 0) {
  73361. BABYLON.Tools.ClearLogCache();
  73362. }
  73363. this._engine.stopRenderLoop();
  73364. }
  73365. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  73366. if (_this._progressCallback) {
  73367. _this._progressCallback(progress);
  73368. }
  73369. }).then(function (scene) {
  73370. if (_this._currentScene) {
  73371. _this._currentScene.dispose();
  73372. }
  73373. _this._currentScene = scene;
  73374. if (_this._sceneLoadedCallback) {
  73375. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  73376. }
  73377. // Wait for textures and shaders to be ready
  73378. _this._currentScene.executeWhenReady(function () {
  73379. _this._engine.runRenderLoop(function () {
  73380. _this.renderFunction();
  73381. });
  73382. });
  73383. }).catch(function (error) {
  73384. if (_this._errorCallback) {
  73385. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  73386. }
  73387. });
  73388. }
  73389. else {
  73390. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  73391. }
  73392. };
  73393. FilesInput.FilesToLoad = {};
  73394. return FilesInput;
  73395. }());
  73396. BABYLON.FilesInput = FilesInput;
  73397. })(BABYLON || (BABYLON = {}));
  73398. //# sourceMappingURL=babylon.filesInput.js.map
  73399. var BABYLON;
  73400. (function (BABYLON) {
  73401. var Tags = /** @class */ (function () {
  73402. function Tags() {
  73403. }
  73404. Tags.EnableFor = function (obj) {
  73405. obj._tags = obj._tags || {};
  73406. obj.hasTags = function () {
  73407. return Tags.HasTags(obj);
  73408. };
  73409. obj.addTags = function (tagsString) {
  73410. return Tags.AddTagsTo(obj, tagsString);
  73411. };
  73412. obj.removeTags = function (tagsString) {
  73413. return Tags.RemoveTagsFrom(obj, tagsString);
  73414. };
  73415. obj.matchesTagsQuery = function (tagsQuery) {
  73416. return Tags.MatchesQuery(obj, tagsQuery);
  73417. };
  73418. };
  73419. Tags.DisableFor = function (obj) {
  73420. delete obj._tags;
  73421. delete obj.hasTags;
  73422. delete obj.addTags;
  73423. delete obj.removeTags;
  73424. delete obj.matchesTagsQuery;
  73425. };
  73426. Tags.HasTags = function (obj) {
  73427. if (!obj._tags) {
  73428. return false;
  73429. }
  73430. return !BABYLON.Tools.IsEmpty(obj._tags);
  73431. };
  73432. Tags.GetTags = function (obj, asString) {
  73433. if (asString === void 0) { asString = true; }
  73434. if (!obj._tags) {
  73435. return null;
  73436. }
  73437. if (asString) {
  73438. var tagsArray = [];
  73439. for (var tag in obj._tags) {
  73440. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  73441. tagsArray.push(tag);
  73442. }
  73443. }
  73444. return tagsArray.join(" ");
  73445. }
  73446. else {
  73447. return obj._tags;
  73448. }
  73449. };
  73450. // the tags 'true' and 'false' are reserved and cannot be used as tags
  73451. // a tag cannot start with '||', '&&', and '!'
  73452. // it cannot contain whitespaces
  73453. Tags.AddTagsTo = function (obj, tagsString) {
  73454. if (!tagsString) {
  73455. return;
  73456. }
  73457. if (typeof tagsString !== "string") {
  73458. return;
  73459. }
  73460. var tags = tagsString.split(" ");
  73461. tags.forEach(function (tag, index, array) {
  73462. Tags._AddTagTo(obj, tag);
  73463. });
  73464. };
  73465. Tags._AddTagTo = function (obj, tag) {
  73466. tag = tag.trim();
  73467. if (tag === "" || tag === "true" || tag === "false") {
  73468. return;
  73469. }
  73470. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  73471. return;
  73472. }
  73473. Tags.EnableFor(obj);
  73474. obj._tags[tag] = true;
  73475. };
  73476. Tags.RemoveTagsFrom = function (obj, tagsString) {
  73477. if (!Tags.HasTags(obj)) {
  73478. return;
  73479. }
  73480. var tags = tagsString.split(" ");
  73481. for (var t in tags) {
  73482. Tags._RemoveTagFrom(obj, tags[t]);
  73483. }
  73484. };
  73485. Tags._RemoveTagFrom = function (obj, tag) {
  73486. delete obj._tags[tag];
  73487. };
  73488. Tags.MatchesQuery = function (obj, tagsQuery) {
  73489. if (tagsQuery === undefined) {
  73490. return true;
  73491. }
  73492. if (tagsQuery === "") {
  73493. return Tags.HasTags(obj);
  73494. }
  73495. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  73496. };
  73497. return Tags;
  73498. }());
  73499. BABYLON.Tags = Tags;
  73500. })(BABYLON || (BABYLON = {}));
  73501. //# sourceMappingURL=babylon.tags.js.map
  73502. var BABYLON;
  73503. (function (BABYLON) {
  73504. /**
  73505. * Class used to evalaute queries containing `and` and `or` operators
  73506. */
  73507. var AndOrNotEvaluator = /** @class */ (function () {
  73508. function AndOrNotEvaluator() {
  73509. }
  73510. /**
  73511. * Evaluate a query
  73512. * @param query defines the query to evaluate
  73513. * @param evaluateCallback defines the callback used to filter result
  73514. * @returns true if the query matches
  73515. */
  73516. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  73517. if (!query.match(/\([^\(\)]*\)/g)) {
  73518. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  73519. }
  73520. else {
  73521. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  73522. // remove parenthesis
  73523. r = r.slice(1, r.length - 1);
  73524. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  73525. });
  73526. }
  73527. if (query === "true") {
  73528. return true;
  73529. }
  73530. if (query === "false") {
  73531. return false;
  73532. }
  73533. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  73534. };
  73535. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  73536. evaluateCallback = evaluateCallback || (function (r) {
  73537. return r === "true" ? true : false;
  73538. });
  73539. var result;
  73540. var or = parenthesisContent.split("||");
  73541. for (var i in or) {
  73542. if (or.hasOwnProperty(i)) {
  73543. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  73544. var and = ori.split("&&");
  73545. if (and.length > 1) {
  73546. for (var j = 0; j < and.length; ++j) {
  73547. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  73548. if (andj !== "true" && andj !== "false") {
  73549. if (andj[0] === "!") {
  73550. result = !evaluateCallback(andj.substring(1));
  73551. }
  73552. else {
  73553. result = evaluateCallback(andj);
  73554. }
  73555. }
  73556. else {
  73557. result = andj === "true" ? true : false;
  73558. }
  73559. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  73560. ori = "false";
  73561. break;
  73562. }
  73563. }
  73564. }
  73565. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  73566. result = true;
  73567. break;
  73568. }
  73569. // result equals false (or undefined)
  73570. if (ori !== "true" && ori !== "false") {
  73571. if (ori[0] === "!") {
  73572. result = !evaluateCallback(ori.substring(1));
  73573. }
  73574. else {
  73575. result = evaluateCallback(ori);
  73576. }
  73577. }
  73578. else {
  73579. result = ori === "true" ? true : false;
  73580. }
  73581. }
  73582. }
  73583. // the whole parenthesis scope is replaced by 'true' or 'false'
  73584. return result ? "true" : "false";
  73585. };
  73586. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  73587. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  73588. // remove whitespaces
  73589. r = r.replace(/[\s]/g, function () { return ""; });
  73590. return r.length % 2 ? "!" : "";
  73591. });
  73592. booleanString = booleanString.trim();
  73593. if (booleanString === "!true") {
  73594. booleanString = "false";
  73595. }
  73596. else if (booleanString === "!false") {
  73597. booleanString = "true";
  73598. }
  73599. return booleanString;
  73600. };
  73601. return AndOrNotEvaluator;
  73602. }());
  73603. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  73604. })(BABYLON || (BABYLON = {}));
  73605. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  73606. var BABYLON;
  73607. (function (BABYLON) {
  73608. /**
  73609. * Class used to enable access to IndexedDB
  73610. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  73611. */
  73612. var Database = /** @class */ (function () {
  73613. /**
  73614. * Creates a new Database
  73615. * @param urlToScene defines the url to load the scene
  73616. * @param callbackManifestChecked defines the callback to use when manifest is checked
  73617. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  73618. */
  73619. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  73620. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  73621. var _this = this;
  73622. // Handling various flavors of prefixed version of IndexedDB
  73623. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  73624. this.callbackManifestChecked = callbackManifestChecked;
  73625. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  73626. this.db = null;
  73627. this._enableSceneOffline = false;
  73628. this._enableTexturesOffline = false;
  73629. this.manifestVersionFound = 0;
  73630. this.mustUpdateRessources = false;
  73631. this.hasReachedQuota = false;
  73632. if (!Database.IDBStorageEnabled) {
  73633. this.callbackManifestChecked(true);
  73634. }
  73635. else {
  73636. if (disableManifestCheck) {
  73637. this._enableSceneOffline = true;
  73638. this._enableTexturesOffline = true;
  73639. this.manifestVersionFound = 1;
  73640. BABYLON.Tools.SetImmediate(function () {
  73641. _this.callbackManifestChecked(true);
  73642. });
  73643. }
  73644. else {
  73645. this._checkManifestFile();
  73646. }
  73647. }
  73648. }
  73649. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  73650. /**
  73651. * Gets a boolean indicating if scene must be saved in the database
  73652. */
  73653. get: function () {
  73654. return this._enableSceneOffline;
  73655. },
  73656. enumerable: true,
  73657. configurable: true
  73658. });
  73659. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  73660. /**
  73661. * Gets a boolean indicating if textures must be saved in the database
  73662. */
  73663. get: function () {
  73664. return this._enableTexturesOffline;
  73665. },
  73666. enumerable: true,
  73667. configurable: true
  73668. });
  73669. Database.prototype._checkManifestFile = function () {
  73670. var _this = this;
  73671. var noManifestFile = function () {
  73672. _this._enableSceneOffline = false;
  73673. _this._enableTexturesOffline = false;
  73674. _this.callbackManifestChecked(false);
  73675. };
  73676. var timeStampUsed = false;
  73677. var manifestURL = this.currentSceneUrl + ".manifest";
  73678. var xhr = new XMLHttpRequest();
  73679. if (navigator.onLine) {
  73680. // Adding a timestamp to by-pass browsers' cache
  73681. timeStampUsed = true;
  73682. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  73683. }
  73684. xhr.open("GET", manifestURL, true);
  73685. xhr.addEventListener("load", function () {
  73686. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73687. try {
  73688. var manifestFile = JSON.parse(xhr.response);
  73689. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  73690. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  73691. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  73692. _this.manifestVersionFound = manifestFile.version;
  73693. }
  73694. if (_this.callbackManifestChecked) {
  73695. _this.callbackManifestChecked(true);
  73696. }
  73697. }
  73698. catch (ex) {
  73699. noManifestFile();
  73700. }
  73701. }
  73702. else {
  73703. noManifestFile();
  73704. }
  73705. }, false);
  73706. xhr.addEventListener("error", function (event) {
  73707. if (timeStampUsed) {
  73708. timeStampUsed = false;
  73709. // Let's retry without the timeStamp
  73710. // It could fail when coupled with HTML5 Offline API
  73711. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  73712. xhr.open("GET", retryManifestURL, true);
  73713. xhr.send();
  73714. }
  73715. else {
  73716. noManifestFile();
  73717. }
  73718. }, false);
  73719. try {
  73720. xhr.send();
  73721. }
  73722. catch (ex) {
  73723. BABYLON.Tools.Error("Error on XHR send request.");
  73724. this.callbackManifestChecked(false);
  73725. }
  73726. };
  73727. /**
  73728. * Open the database and make it available
  73729. * @param successCallback defines the callback to call on success
  73730. * @param errorCallback defines the callback to call on error
  73731. */
  73732. Database.prototype.openAsync = function (successCallback, errorCallback) {
  73733. var _this = this;
  73734. var handleError = function () {
  73735. _this.isSupported = false;
  73736. if (errorCallback)
  73737. errorCallback();
  73738. };
  73739. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  73740. // Your browser doesn't support IndexedDB
  73741. this.isSupported = false;
  73742. if (errorCallback)
  73743. errorCallback();
  73744. }
  73745. else {
  73746. // If the DB hasn't been opened or created yet
  73747. if (!this.db) {
  73748. this.hasReachedQuota = false;
  73749. this.isSupported = true;
  73750. var request = this.idbFactory.open("babylonjs", 1);
  73751. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  73752. request.onerror = function (event) {
  73753. handleError();
  73754. };
  73755. // executes when a version change transaction cannot complete due to other active transactions
  73756. request.onblocked = function (event) {
  73757. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  73758. handleError();
  73759. };
  73760. // DB has been opened successfully
  73761. request.onsuccess = function (event) {
  73762. _this.db = request.result;
  73763. successCallback();
  73764. };
  73765. // Initialization of the DB. Creating Scenes & Textures stores
  73766. request.onupgradeneeded = function (event) {
  73767. _this.db = (event.target).result;
  73768. if (_this.db) {
  73769. try {
  73770. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  73771. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  73772. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  73773. }
  73774. catch (ex) {
  73775. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  73776. handleError();
  73777. }
  73778. }
  73779. };
  73780. }
  73781. // DB has already been created and opened
  73782. else {
  73783. if (successCallback)
  73784. successCallback();
  73785. }
  73786. }
  73787. };
  73788. /**
  73789. * Loads an image from the database
  73790. * @param url defines the url to load from
  73791. * @param image defines the target DOM image
  73792. */
  73793. Database.prototype.loadImageFromDB = function (url, image) {
  73794. var _this = this;
  73795. var completeURL = Database._ReturnFullUrlLocation(url);
  73796. var saveAndLoadImage = function () {
  73797. if (!_this.hasReachedQuota && _this.db !== null) {
  73798. // the texture is not yet in the DB, let's try to save it
  73799. _this._saveImageIntoDBAsync(completeURL, image);
  73800. }
  73801. // If the texture is not in the DB and we've reached the DB quota limit
  73802. // let's load it directly from the web
  73803. else {
  73804. image.src = url;
  73805. }
  73806. };
  73807. if (!this.mustUpdateRessources) {
  73808. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  73809. }
  73810. // First time we're download the images or update requested in the manifest file by a version change
  73811. else {
  73812. saveAndLoadImage();
  73813. }
  73814. };
  73815. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  73816. if (this.isSupported && this.db !== null) {
  73817. var texture;
  73818. var transaction = this.db.transaction(["textures"]);
  73819. transaction.onabort = function (event) {
  73820. image.src = url;
  73821. };
  73822. transaction.oncomplete = function (event) {
  73823. var blobTextureURL;
  73824. if (texture) {
  73825. var URL = window.URL || window.webkitURL;
  73826. blobTextureURL = URL.createObjectURL(texture.data);
  73827. image.onerror = function () {
  73828. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  73829. image.src = url;
  73830. };
  73831. image.src = blobTextureURL;
  73832. }
  73833. else {
  73834. notInDBCallback();
  73835. }
  73836. };
  73837. var getRequest = transaction.objectStore("textures").get(url);
  73838. getRequest.onsuccess = function (event) {
  73839. texture = (event.target).result;
  73840. };
  73841. getRequest.onerror = function (event) {
  73842. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  73843. image.src = url;
  73844. };
  73845. }
  73846. else {
  73847. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73848. image.src = url;
  73849. }
  73850. };
  73851. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  73852. var _this = this;
  73853. if (this.isSupported) {
  73854. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  73855. var generateBlobUrl = function () {
  73856. var blobTextureURL;
  73857. if (blob) {
  73858. var URL = window.URL || window.webkitURL;
  73859. try {
  73860. blobTextureURL = URL.createObjectURL(blob);
  73861. }
  73862. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  73863. catch (ex) {
  73864. blobTextureURL = URL.createObjectURL(blob);
  73865. }
  73866. }
  73867. if (blobTextureURL) {
  73868. image.src = blobTextureURL;
  73869. }
  73870. };
  73871. if (Database.IsUASupportingBlobStorage) { // Create XHR
  73872. var xhr = new XMLHttpRequest(), blob;
  73873. xhr.open("GET", url, true);
  73874. xhr.responseType = "blob";
  73875. xhr.addEventListener("load", function () {
  73876. if (xhr.status === 200 && _this.db) {
  73877. // Blob as response (XHR2)
  73878. blob = xhr.response;
  73879. var transaction = _this.db.transaction(["textures"], "readwrite");
  73880. // the transaction could abort because of a QuotaExceededError error
  73881. transaction.onabort = function (event) {
  73882. try {
  73883. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73884. var srcElement = (event.srcElement || event.target);
  73885. var error = srcElement.error;
  73886. if (error && error.name === "QuotaExceededError") {
  73887. _this.hasReachedQuota = true;
  73888. }
  73889. }
  73890. catch (ex) { }
  73891. generateBlobUrl();
  73892. };
  73893. transaction.oncomplete = function (event) {
  73894. generateBlobUrl();
  73895. };
  73896. var newTexture = { textureUrl: url, data: blob };
  73897. try {
  73898. // Put the blob into the dabase
  73899. var addRequest = transaction.objectStore("textures").put(newTexture);
  73900. addRequest.onsuccess = function (event) {
  73901. };
  73902. addRequest.onerror = function (event) {
  73903. generateBlobUrl();
  73904. };
  73905. }
  73906. catch (ex) {
  73907. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  73908. if (ex.code === 25) {
  73909. Database.IsUASupportingBlobStorage = false;
  73910. }
  73911. image.src = url;
  73912. }
  73913. }
  73914. else {
  73915. image.src = url;
  73916. }
  73917. }, false);
  73918. xhr.addEventListener("error", function (event) {
  73919. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  73920. image.src = url;
  73921. }, false);
  73922. xhr.send();
  73923. }
  73924. else {
  73925. image.src = url;
  73926. }
  73927. }
  73928. else {
  73929. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73930. image.src = url;
  73931. }
  73932. };
  73933. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  73934. var _this = this;
  73935. var updateVersion = function () {
  73936. // the version is not yet in the DB or we need to update it
  73937. _this._saveVersionIntoDBAsync(url, versionLoaded);
  73938. };
  73939. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  73940. };
  73941. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  73942. var _this = this;
  73943. if (this.isSupported && this.db) {
  73944. var version;
  73945. try {
  73946. var transaction = this.db.transaction(["versions"]);
  73947. transaction.oncomplete = function (event) {
  73948. if (version) {
  73949. // If the version in the JSON file is different from the version in DB
  73950. if (_this.manifestVersionFound !== version.data) {
  73951. _this.mustUpdateRessources = true;
  73952. updateInDBCallback();
  73953. }
  73954. else {
  73955. callback(version.data);
  73956. }
  73957. }
  73958. // version was not found in DB
  73959. else {
  73960. _this.mustUpdateRessources = true;
  73961. updateInDBCallback();
  73962. }
  73963. };
  73964. transaction.onabort = function (event) {
  73965. callback(-1);
  73966. };
  73967. var getRequest = transaction.objectStore("versions").get(url);
  73968. getRequest.onsuccess = function (event) {
  73969. version = (event.target).result;
  73970. };
  73971. getRequest.onerror = function (event) {
  73972. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  73973. callback(-1);
  73974. };
  73975. }
  73976. catch (ex) {
  73977. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  73978. callback(-1);
  73979. }
  73980. }
  73981. else {
  73982. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73983. callback(-1);
  73984. }
  73985. };
  73986. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  73987. var _this = this;
  73988. if (this.isSupported && !this.hasReachedQuota && this.db) {
  73989. try {
  73990. // Open a transaction to the database
  73991. var transaction = this.db.transaction(["versions"], "readwrite");
  73992. // the transaction could abort because of a QuotaExceededError error
  73993. transaction.onabort = function (event) {
  73994. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73995. var error = event.srcElement['error'];
  73996. if (error && error.name === "QuotaExceededError") {
  73997. _this.hasReachedQuota = true;
  73998. }
  73999. }
  74000. catch (ex) { }
  74001. callback(-1);
  74002. };
  74003. transaction.oncomplete = function (event) {
  74004. callback(_this.manifestVersionFound);
  74005. };
  74006. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  74007. // Put the scene into the database
  74008. var addRequest = transaction.objectStore("versions").put(newVersion);
  74009. addRequest.onsuccess = function (event) {
  74010. };
  74011. addRequest.onerror = function (event) {
  74012. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  74013. };
  74014. }
  74015. catch (ex) {
  74016. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  74017. callback(-1);
  74018. }
  74019. }
  74020. else {
  74021. callback(-1);
  74022. }
  74023. };
  74024. /**
  74025. * Loads a file from database
  74026. * @param url defines the URL to load from
  74027. * @param sceneLoaded defines a callback to call on success
  74028. * @param progressCallBack defines a callback to call when progress changed
  74029. * @param errorCallback defines a callback to call on error
  74030. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  74031. */
  74032. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  74033. var _this = this;
  74034. var completeUrl = Database._ReturnFullUrlLocation(url);
  74035. var saveAndLoadFile = function () {
  74036. // the scene is not yet in the DB, let's try to save it
  74037. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  74038. };
  74039. this._checkVersionFromDB(completeUrl, function (version) {
  74040. if (version !== -1) {
  74041. if (!_this.mustUpdateRessources) {
  74042. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  74043. }
  74044. else {
  74045. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  74046. }
  74047. }
  74048. else {
  74049. if (errorCallback) {
  74050. errorCallback();
  74051. }
  74052. }
  74053. });
  74054. };
  74055. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  74056. if (this.isSupported && this.db) {
  74057. var targetStore;
  74058. if (url.indexOf(".babylon") !== -1) {
  74059. targetStore = "scenes";
  74060. }
  74061. else {
  74062. targetStore = "textures";
  74063. }
  74064. var file;
  74065. var transaction = this.db.transaction([targetStore]);
  74066. transaction.oncomplete = function (event) {
  74067. if (file) {
  74068. callback(file.data);
  74069. }
  74070. // file was not found in DB
  74071. else {
  74072. notInDBCallback();
  74073. }
  74074. };
  74075. transaction.onabort = function (event) {
  74076. notInDBCallback();
  74077. };
  74078. var getRequest = transaction.objectStore(targetStore).get(url);
  74079. getRequest.onsuccess = function (event) {
  74080. file = (event.target).result;
  74081. };
  74082. getRequest.onerror = function (event) {
  74083. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  74084. notInDBCallback();
  74085. };
  74086. }
  74087. else {
  74088. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  74089. callback();
  74090. }
  74091. };
  74092. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  74093. var _this = this;
  74094. if (this.isSupported) {
  74095. var targetStore;
  74096. if (url.indexOf(".babylon") !== -1) {
  74097. targetStore = "scenes";
  74098. }
  74099. else {
  74100. targetStore = "textures";
  74101. }
  74102. // Create XHR
  74103. var xhr = new XMLHttpRequest();
  74104. var fileData;
  74105. xhr.open("GET", url + "?" + Date.now(), true);
  74106. if (useArrayBuffer) {
  74107. xhr.responseType = "arraybuffer";
  74108. }
  74109. if (progressCallback) {
  74110. xhr.onprogress = progressCallback;
  74111. }
  74112. xhr.addEventListener("load", function () {
  74113. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  74114. // Blob as response (XHR2)
  74115. //fileData = xhr.responseText;
  74116. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  74117. if (!_this.hasReachedQuota && _this.db) {
  74118. // Open a transaction to the database
  74119. var transaction = _this.db.transaction([targetStore], "readwrite");
  74120. // the transaction could abort because of a QuotaExceededError error
  74121. transaction.onabort = function (event) {
  74122. try {
  74123. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  74124. var error = event.srcElement['error'];
  74125. if (error && error.name === "QuotaExceededError") {
  74126. _this.hasReachedQuota = true;
  74127. }
  74128. }
  74129. catch (ex) { }
  74130. callback(fileData);
  74131. };
  74132. transaction.oncomplete = function (event) {
  74133. callback(fileData);
  74134. };
  74135. var newFile;
  74136. if (targetStore === "scenes") {
  74137. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  74138. }
  74139. else {
  74140. newFile = { textureUrl: url, data: fileData };
  74141. }
  74142. try {
  74143. // Put the scene into the database
  74144. var addRequest = transaction.objectStore(targetStore).put(newFile);
  74145. addRequest.onsuccess = function (event) {
  74146. };
  74147. addRequest.onerror = function (event) {
  74148. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  74149. };
  74150. }
  74151. catch (ex) {
  74152. callback(fileData);
  74153. }
  74154. }
  74155. else {
  74156. callback(fileData);
  74157. }
  74158. }
  74159. else {
  74160. if (xhr.status >= 400 && errorCallback) {
  74161. errorCallback(xhr);
  74162. }
  74163. else {
  74164. callback();
  74165. }
  74166. }
  74167. }, false);
  74168. xhr.addEventListener("error", function (event) {
  74169. BABYLON.Tools.Error("error on XHR request.");
  74170. callback();
  74171. }, false);
  74172. xhr.send();
  74173. }
  74174. else {
  74175. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  74176. callback();
  74177. }
  74178. };
  74179. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  74180. Database.IsUASupportingBlobStorage = true;
  74181. /** Gets a boolean indicating if Database storate is enabled */
  74182. Database.IDBStorageEnabled = true;
  74183. Database._ParseURL = function (url) {
  74184. var a = document.createElement('a');
  74185. a.href = url;
  74186. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  74187. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  74188. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  74189. return absLocation;
  74190. };
  74191. Database._ReturnFullUrlLocation = function (url) {
  74192. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  74193. return (Database._ParseURL(window.location.href) + url);
  74194. }
  74195. else {
  74196. return url;
  74197. }
  74198. };
  74199. return Database;
  74200. }());
  74201. BABYLON.Database = Database;
  74202. })(BABYLON || (BABYLON = {}));
  74203. //# sourceMappingURL=babylon.database.js.map
  74204. var BABYLON;
  74205. (function (BABYLON) {
  74206. var FresnelParameters = /** @class */ (function () {
  74207. function FresnelParameters() {
  74208. this._isEnabled = true;
  74209. this.leftColor = BABYLON.Color3.White();
  74210. this.rightColor = BABYLON.Color3.Black();
  74211. this.bias = 0;
  74212. this.power = 1;
  74213. }
  74214. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  74215. get: function () {
  74216. return this._isEnabled;
  74217. },
  74218. set: function (value) {
  74219. if (this._isEnabled === value) {
  74220. return;
  74221. }
  74222. this._isEnabled = value;
  74223. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  74224. },
  74225. enumerable: true,
  74226. configurable: true
  74227. });
  74228. FresnelParameters.prototype.clone = function () {
  74229. var newFresnelParameters = new FresnelParameters();
  74230. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  74231. return newFresnelParameters;
  74232. };
  74233. FresnelParameters.prototype.serialize = function () {
  74234. var serializationObject = {};
  74235. serializationObject.isEnabled = this.isEnabled;
  74236. serializationObject.leftColor = this.leftColor.asArray();
  74237. serializationObject.rightColor = this.rightColor.asArray();
  74238. serializationObject.bias = this.bias;
  74239. serializationObject.power = this.power;
  74240. return serializationObject;
  74241. };
  74242. FresnelParameters.Parse = function (parsedFresnelParameters) {
  74243. var fresnelParameters = new FresnelParameters();
  74244. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  74245. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  74246. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  74247. fresnelParameters.bias = parsedFresnelParameters.bias;
  74248. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  74249. return fresnelParameters;
  74250. };
  74251. return FresnelParameters;
  74252. }());
  74253. BABYLON.FresnelParameters = FresnelParameters;
  74254. })(BABYLON || (BABYLON = {}));
  74255. //# sourceMappingURL=babylon.fresnelParameters.js.map
  74256. var BABYLON;
  74257. (function (BABYLON) {
  74258. var MultiMaterial = /** @class */ (function (_super) {
  74259. __extends(MultiMaterial, _super);
  74260. function MultiMaterial(name, scene) {
  74261. var _this = _super.call(this, name, scene, true) || this;
  74262. scene.multiMaterials.push(_this);
  74263. _this.subMaterials = new Array();
  74264. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  74265. return _this;
  74266. }
  74267. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  74268. get: function () {
  74269. return this._subMaterials;
  74270. },
  74271. set: function (value) {
  74272. this._subMaterials = value;
  74273. this._hookArray(value);
  74274. },
  74275. enumerable: true,
  74276. configurable: true
  74277. });
  74278. MultiMaterial.prototype._hookArray = function (array) {
  74279. var _this = this;
  74280. var oldPush = array.push;
  74281. array.push = function () {
  74282. var items = [];
  74283. for (var _i = 0; _i < arguments.length; _i++) {
  74284. items[_i] = arguments[_i];
  74285. }
  74286. var result = oldPush.apply(array, items);
  74287. _this._markAllSubMeshesAsTexturesDirty();
  74288. return result;
  74289. };
  74290. var oldSplice = array.splice;
  74291. array.splice = function (index, deleteCount) {
  74292. var deleted = oldSplice.apply(array, [index, deleteCount]);
  74293. _this._markAllSubMeshesAsTexturesDirty();
  74294. return deleted;
  74295. };
  74296. };
  74297. // Properties
  74298. MultiMaterial.prototype.getSubMaterial = function (index) {
  74299. if (index < 0 || index >= this.subMaterials.length) {
  74300. return this.getScene().defaultMaterial;
  74301. }
  74302. return this.subMaterials[index];
  74303. };
  74304. MultiMaterial.prototype.getActiveTextures = function () {
  74305. var _a;
  74306. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  74307. if (subMaterial) {
  74308. return subMaterial.getActiveTextures();
  74309. }
  74310. else {
  74311. return [];
  74312. }
  74313. }));
  74314. };
  74315. // Methods
  74316. MultiMaterial.prototype.getClassName = function () {
  74317. return "MultiMaterial";
  74318. };
  74319. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  74320. for (var index = 0; index < this.subMaterials.length; index++) {
  74321. var subMaterial = this.subMaterials[index];
  74322. if (subMaterial) {
  74323. if (subMaterial.storeEffectOnSubMeshes) {
  74324. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  74325. return false;
  74326. }
  74327. continue;
  74328. }
  74329. if (!subMaterial.isReady(mesh)) {
  74330. return false;
  74331. }
  74332. }
  74333. }
  74334. return true;
  74335. };
  74336. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  74337. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  74338. for (var index = 0; index < this.subMaterials.length; index++) {
  74339. var subMaterial = null;
  74340. var current = this.subMaterials[index];
  74341. if (cloneChildren && current) {
  74342. subMaterial = current.clone(name + "-" + current.name);
  74343. }
  74344. else {
  74345. subMaterial = this.subMaterials[index];
  74346. }
  74347. newMultiMaterial.subMaterials.push(subMaterial);
  74348. }
  74349. return newMultiMaterial;
  74350. };
  74351. MultiMaterial.prototype.serialize = function () {
  74352. var serializationObject = {};
  74353. serializationObject.name = this.name;
  74354. serializationObject.id = this.id;
  74355. if (BABYLON.Tags) {
  74356. serializationObject.tags = BABYLON.Tags.GetTags(this);
  74357. }
  74358. serializationObject.materials = [];
  74359. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  74360. var subMat = this.subMaterials[matIndex];
  74361. if (subMat) {
  74362. serializationObject.materials.push(subMat.id);
  74363. }
  74364. else {
  74365. serializationObject.materials.push(null);
  74366. }
  74367. }
  74368. return serializationObject;
  74369. };
  74370. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  74371. var scene = this.getScene();
  74372. if (!scene) {
  74373. return;
  74374. }
  74375. var index = scene.multiMaterials.indexOf(this);
  74376. if (index >= 0) {
  74377. scene.multiMaterials.splice(index, 1);
  74378. }
  74379. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  74380. };
  74381. return MultiMaterial;
  74382. }(BABYLON.Material));
  74383. BABYLON.MultiMaterial = MultiMaterial;
  74384. })(BABYLON || (BABYLON = {}));
  74385. //# sourceMappingURL=babylon.multiMaterial.js.map
  74386. var BABYLON;
  74387. (function (BABYLON) {
  74388. var FreeCameraTouchInput = /** @class */ (function () {
  74389. function FreeCameraTouchInput() {
  74390. this._offsetX = null;
  74391. this._offsetY = null;
  74392. this._pointerPressed = new Array();
  74393. this.touchAngularSensibility = 200000.0;
  74394. this.touchMoveSensibility = 250.0;
  74395. }
  74396. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  74397. var _this = this;
  74398. var previousPosition = null;
  74399. if (this._pointerInput === undefined) {
  74400. this._onLostFocus = function (evt) {
  74401. _this._offsetX = null;
  74402. _this._offsetY = null;
  74403. };
  74404. this._pointerInput = function (p, s) {
  74405. var evt = p.event;
  74406. if (evt.pointerType === "mouse") {
  74407. return;
  74408. }
  74409. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74410. if (!noPreventDefault) {
  74411. evt.preventDefault();
  74412. }
  74413. _this._pointerPressed.push(evt.pointerId);
  74414. if (_this._pointerPressed.length !== 1) {
  74415. return;
  74416. }
  74417. previousPosition = {
  74418. x: evt.clientX,
  74419. y: evt.clientY
  74420. };
  74421. }
  74422. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  74423. if (!noPreventDefault) {
  74424. evt.preventDefault();
  74425. }
  74426. var index = _this._pointerPressed.indexOf(evt.pointerId);
  74427. if (index === -1) {
  74428. return;
  74429. }
  74430. _this._pointerPressed.splice(index, 1);
  74431. if (index != 0) {
  74432. return;
  74433. }
  74434. previousPosition = null;
  74435. _this._offsetX = null;
  74436. _this._offsetY = null;
  74437. }
  74438. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  74439. if (!noPreventDefault) {
  74440. evt.preventDefault();
  74441. }
  74442. if (!previousPosition) {
  74443. return;
  74444. }
  74445. var index = _this._pointerPressed.indexOf(evt.pointerId);
  74446. if (index != 0) {
  74447. return;
  74448. }
  74449. _this._offsetX = evt.clientX - previousPosition.x;
  74450. _this._offsetY = -(evt.clientY - previousPosition.y);
  74451. }
  74452. };
  74453. }
  74454. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  74455. if (this._onLostFocus) {
  74456. element.addEventListener("blur", this._onLostFocus);
  74457. }
  74458. };
  74459. FreeCameraTouchInput.prototype.detachControl = function (element) {
  74460. if (this._pointerInput && element) {
  74461. if (this._observer) {
  74462. this.camera.getScene().onPointerObservable.remove(this._observer);
  74463. this._observer = null;
  74464. }
  74465. if (this._onLostFocus) {
  74466. element.removeEventListener("blur", this._onLostFocus);
  74467. this._onLostFocus = null;
  74468. }
  74469. this._pointerPressed = [];
  74470. this._offsetX = null;
  74471. this._offsetY = null;
  74472. }
  74473. };
  74474. FreeCameraTouchInput.prototype.checkInputs = function () {
  74475. if (this._offsetX && this._offsetY) {
  74476. var camera = this.camera;
  74477. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  74478. if (this._pointerPressed.length > 1) {
  74479. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  74480. }
  74481. else {
  74482. var speed = camera._computeLocalCameraSpeed();
  74483. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  74484. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  74485. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  74486. }
  74487. }
  74488. };
  74489. FreeCameraTouchInput.prototype.getClassName = function () {
  74490. return "FreeCameraTouchInput";
  74491. };
  74492. FreeCameraTouchInput.prototype.getSimpleName = function () {
  74493. return "touch";
  74494. };
  74495. __decorate([
  74496. BABYLON.serialize()
  74497. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  74498. __decorate([
  74499. BABYLON.serialize()
  74500. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  74501. return FreeCameraTouchInput;
  74502. }());
  74503. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  74504. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  74505. })(BABYLON || (BABYLON = {}));
  74506. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  74507. var BABYLON;
  74508. (function (BABYLON) {
  74509. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  74510. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  74511. });
  74512. // We're mainly based on the logic defined into the FreeCamera code
  74513. var TouchCamera = /** @class */ (function (_super) {
  74514. __extends(TouchCamera, _super);
  74515. //-- end properties for backward compatibility for inputs
  74516. function TouchCamera(name, position, scene) {
  74517. var _this = _super.call(this, name, position, scene) || this;
  74518. _this.inputs.addTouch();
  74519. _this._setupInputs();
  74520. return _this;
  74521. }
  74522. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  74523. //-- Begin properties for backward compatibility for inputs
  74524. get: function () {
  74525. var touch = this.inputs.attached["touch"];
  74526. if (touch)
  74527. return touch.touchAngularSensibility;
  74528. return 0;
  74529. },
  74530. set: function (value) {
  74531. var touch = this.inputs.attached["touch"];
  74532. if (touch)
  74533. touch.touchAngularSensibility = value;
  74534. },
  74535. enumerable: true,
  74536. configurable: true
  74537. });
  74538. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  74539. get: function () {
  74540. var touch = this.inputs.attached["touch"];
  74541. if (touch)
  74542. return touch.touchMoveSensibility;
  74543. return 0;
  74544. },
  74545. set: function (value) {
  74546. var touch = this.inputs.attached["touch"];
  74547. if (touch)
  74548. touch.touchMoveSensibility = value;
  74549. },
  74550. enumerable: true,
  74551. configurable: true
  74552. });
  74553. TouchCamera.prototype.getClassName = function () {
  74554. return "TouchCamera";
  74555. };
  74556. /** @hidden */
  74557. TouchCamera.prototype._setupInputs = function () {
  74558. var mouse = this.inputs.attached["mouse"];
  74559. if (mouse) {
  74560. mouse.touchEnabled = false;
  74561. }
  74562. };
  74563. return TouchCamera;
  74564. }(BABYLON.FreeCamera));
  74565. BABYLON.TouchCamera = TouchCamera;
  74566. })(BABYLON || (BABYLON = {}));
  74567. //# sourceMappingURL=babylon.touchCamera.js.map
  74568. var BABYLON;
  74569. (function (BABYLON) {
  74570. var ProceduralTexture = /** @class */ (function (_super) {
  74571. __extends(ProceduralTexture, _super);
  74572. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  74573. if (fallbackTexture === void 0) { fallbackTexture = null; }
  74574. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74575. if (isCube === void 0) { isCube = false; }
  74576. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  74577. _this.isCube = isCube;
  74578. _this.isEnabled = true;
  74579. _this._currentRefreshId = -1;
  74580. _this._refreshRate = 1;
  74581. /**
  74582. * Event raised when the texture is generated
  74583. */
  74584. _this.onGeneratedObservable = new BABYLON.Observable();
  74585. _this._vertexBuffers = {};
  74586. _this._uniforms = new Array();
  74587. _this._samplers = new Array();
  74588. /** @hidden */
  74589. _this._textures = {};
  74590. _this._floats = {};
  74591. _this._ints = {};
  74592. _this._floatsArrays = {};
  74593. _this._colors3 = {};
  74594. _this._colors4 = {};
  74595. _this._vectors2 = {};
  74596. _this._vectors3 = {};
  74597. _this._matrices = {};
  74598. _this._fallbackTextureUsed = false;
  74599. _this._cachedDefines = "";
  74600. _this._contentUpdateId = -1;
  74601. scene = _this.getScene();
  74602. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  74603. if (!component) {
  74604. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  74605. scene._addComponent(component);
  74606. }
  74607. scene.proceduralTextures.push(_this);
  74608. _this._engine = scene.getEngine();
  74609. _this.name = name;
  74610. _this.isRenderTarget = true;
  74611. _this._size = size;
  74612. _this._generateMipMaps = generateMipMaps;
  74613. _this.setFragment(fragment);
  74614. _this._fallbackTexture = fallbackTexture;
  74615. if (isCube) {
  74616. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  74617. _this.setFloat("face", 0);
  74618. }
  74619. else {
  74620. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  74621. }
  74622. // VBO
  74623. var vertices = [];
  74624. vertices.push(1, 1);
  74625. vertices.push(-1, 1);
  74626. vertices.push(-1, -1);
  74627. vertices.push(1, -1);
  74628. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74629. _this._createIndexBuffer();
  74630. return _this;
  74631. }
  74632. /**
  74633. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  74634. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  74635. */
  74636. ProceduralTexture.prototype.getContent = function () {
  74637. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  74638. return this._contentData;
  74639. }
  74640. this._contentData = this.readPixels(0, 0, this._contentData);
  74641. this._contentUpdateId = this._currentRefreshId;
  74642. return this._contentData;
  74643. };
  74644. ProceduralTexture.prototype._createIndexBuffer = function () {
  74645. var engine = this._engine;
  74646. // Indices
  74647. var indices = [];
  74648. indices.push(0);
  74649. indices.push(1);
  74650. indices.push(2);
  74651. indices.push(0);
  74652. indices.push(2);
  74653. indices.push(3);
  74654. this._indexBuffer = engine.createIndexBuffer(indices);
  74655. };
  74656. /** @hidden */
  74657. ProceduralTexture.prototype._rebuild = function () {
  74658. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74659. if (vb) {
  74660. vb._rebuild();
  74661. }
  74662. this._createIndexBuffer();
  74663. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  74664. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  74665. }
  74666. };
  74667. ProceduralTexture.prototype.reset = function () {
  74668. if (this._effect === undefined) {
  74669. return;
  74670. }
  74671. var engine = this._engine;
  74672. engine._releaseEffect(this._effect);
  74673. };
  74674. ProceduralTexture.prototype._getDefines = function () {
  74675. return "";
  74676. };
  74677. ProceduralTexture.prototype.isReady = function () {
  74678. var _this = this;
  74679. var engine = this._engine;
  74680. var shaders;
  74681. if (!this._fragment) {
  74682. return false;
  74683. }
  74684. if (this._fallbackTextureUsed) {
  74685. return true;
  74686. }
  74687. var defines = this._getDefines();
  74688. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  74689. return true;
  74690. }
  74691. if (this._fragment.fragmentElement !== undefined) {
  74692. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  74693. }
  74694. else {
  74695. shaders = { vertex: "procedural", fragment: this._fragment };
  74696. }
  74697. this._cachedDefines = defines;
  74698. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  74699. _this.releaseInternalTexture();
  74700. if (_this._fallbackTexture) {
  74701. _this._texture = _this._fallbackTexture._texture;
  74702. if (_this._texture) {
  74703. _this._texture.incrementReferences();
  74704. }
  74705. }
  74706. _this._fallbackTextureUsed = true;
  74707. });
  74708. return this._effect.isReady();
  74709. };
  74710. ProceduralTexture.prototype.resetRefreshCounter = function () {
  74711. this._currentRefreshId = -1;
  74712. };
  74713. ProceduralTexture.prototype.setFragment = function (fragment) {
  74714. this._fragment = fragment;
  74715. };
  74716. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  74717. get: function () {
  74718. return this._refreshRate;
  74719. },
  74720. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  74721. set: function (value) {
  74722. this._refreshRate = value;
  74723. this.resetRefreshCounter();
  74724. },
  74725. enumerable: true,
  74726. configurable: true
  74727. });
  74728. /** @hidden */
  74729. ProceduralTexture.prototype._shouldRender = function () {
  74730. if (!this.isEnabled || !this.isReady() || !this._texture) {
  74731. if (this._texture) {
  74732. this._texture.isReady = false;
  74733. }
  74734. return false;
  74735. }
  74736. if (this._fallbackTextureUsed) {
  74737. return false;
  74738. }
  74739. if (this._currentRefreshId === -1) { // At least render once
  74740. this._currentRefreshId = 1;
  74741. return true;
  74742. }
  74743. if (this.refreshRate === this._currentRefreshId) {
  74744. this._currentRefreshId = 1;
  74745. return true;
  74746. }
  74747. this._currentRefreshId++;
  74748. return false;
  74749. };
  74750. ProceduralTexture.prototype.getRenderSize = function () {
  74751. return this._size;
  74752. };
  74753. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  74754. if (this._fallbackTextureUsed) {
  74755. return;
  74756. }
  74757. this.releaseInternalTexture();
  74758. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  74759. // Update properties
  74760. this._size = size;
  74761. this._generateMipMaps = generateMipMaps;
  74762. };
  74763. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  74764. if (this._uniforms.indexOf(uniformName) === -1) {
  74765. this._uniforms.push(uniformName);
  74766. }
  74767. };
  74768. ProceduralTexture.prototype.setTexture = function (name, texture) {
  74769. if (this._samplers.indexOf(name) === -1) {
  74770. this._samplers.push(name);
  74771. }
  74772. this._textures[name] = texture;
  74773. return this;
  74774. };
  74775. ProceduralTexture.prototype.setFloat = function (name, value) {
  74776. this._checkUniform(name);
  74777. this._floats[name] = value;
  74778. return this;
  74779. };
  74780. /**
  74781. * Set the value of an uniform to an integer value
  74782. * @param name defines the name of the uniform
  74783. * @param value defines the value to set
  74784. * @returns the current procedural texture
  74785. */
  74786. ProceduralTexture.prototype.setInt = function (name, value) {
  74787. this._checkUniform(name);
  74788. this._ints[name] = value;
  74789. return this;
  74790. };
  74791. ProceduralTexture.prototype.setFloats = function (name, value) {
  74792. this._checkUniform(name);
  74793. this._floatsArrays[name] = value;
  74794. return this;
  74795. };
  74796. ProceduralTexture.prototype.setColor3 = function (name, value) {
  74797. this._checkUniform(name);
  74798. this._colors3[name] = value;
  74799. return this;
  74800. };
  74801. ProceduralTexture.prototype.setColor4 = function (name, value) {
  74802. this._checkUniform(name);
  74803. this._colors4[name] = value;
  74804. return this;
  74805. };
  74806. ProceduralTexture.prototype.setVector2 = function (name, value) {
  74807. this._checkUniform(name);
  74808. this._vectors2[name] = value;
  74809. return this;
  74810. };
  74811. ProceduralTexture.prototype.setVector3 = function (name, value) {
  74812. this._checkUniform(name);
  74813. this._vectors3[name] = value;
  74814. return this;
  74815. };
  74816. ProceduralTexture.prototype.setMatrix = function (name, value) {
  74817. this._checkUniform(name);
  74818. this._matrices[name] = value;
  74819. return this;
  74820. };
  74821. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74822. var scene = this.getScene();
  74823. if (!scene) {
  74824. return;
  74825. }
  74826. var engine = this._engine;
  74827. // Render
  74828. engine.enableEffect(this._effect);
  74829. engine.setState(false);
  74830. // Texture
  74831. for (var name in this._textures) {
  74832. this._effect.setTexture(name, this._textures[name]);
  74833. }
  74834. // Float
  74835. for (name in this._ints) {
  74836. this._effect.setInt(name, this._ints[name]);
  74837. }
  74838. // Float
  74839. for (name in this._floats) {
  74840. this._effect.setFloat(name, this._floats[name]);
  74841. }
  74842. // Floats
  74843. for (name in this._floatsArrays) {
  74844. this._effect.setArray(name, this._floatsArrays[name]);
  74845. }
  74846. // Color3
  74847. for (name in this._colors3) {
  74848. this._effect.setColor3(name, this._colors3[name]);
  74849. }
  74850. // Color4
  74851. for (name in this._colors4) {
  74852. var color = this._colors4[name];
  74853. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  74854. }
  74855. // Vector2
  74856. for (name in this._vectors2) {
  74857. this._effect.setVector2(name, this._vectors2[name]);
  74858. }
  74859. // Vector3
  74860. for (name in this._vectors3) {
  74861. this._effect.setVector3(name, this._vectors3[name]);
  74862. }
  74863. // Matrix
  74864. for (name in this._matrices) {
  74865. this._effect.setMatrix(name, this._matrices[name]);
  74866. }
  74867. if (!this._texture) {
  74868. return;
  74869. }
  74870. if (this.isCube) {
  74871. for (var face = 0; face < 6; face++) {
  74872. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  74873. // VBOs
  74874. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74875. this._effect.setFloat("face", face);
  74876. // Clear
  74877. engine.clear(scene.clearColor, true, true, true);
  74878. // Draw order
  74879. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74880. // Mipmaps
  74881. if (face === 5) {
  74882. engine.generateMipMapsForCubemap(this._texture);
  74883. }
  74884. }
  74885. }
  74886. else {
  74887. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  74888. // VBOs
  74889. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74890. // Clear
  74891. engine.clear(scene.clearColor, true, true, true);
  74892. // Draw order
  74893. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74894. }
  74895. // Unbind
  74896. engine.unBindFramebuffer(this._texture, this.isCube);
  74897. if (this.onGenerated) {
  74898. this.onGenerated();
  74899. }
  74900. this.onGeneratedObservable.notifyObservers(this);
  74901. };
  74902. ProceduralTexture.prototype.clone = function () {
  74903. var textureSize = this.getSize();
  74904. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  74905. // Base texture
  74906. newTexture.hasAlpha = this.hasAlpha;
  74907. newTexture.level = this.level;
  74908. // RenderTarget Texture
  74909. newTexture.coordinatesMode = this.coordinatesMode;
  74910. return newTexture;
  74911. };
  74912. ProceduralTexture.prototype.dispose = function () {
  74913. var scene = this.getScene();
  74914. if (!scene) {
  74915. return;
  74916. }
  74917. var index = scene.proceduralTextures.indexOf(this);
  74918. if (index >= 0) {
  74919. scene.proceduralTextures.splice(index, 1);
  74920. }
  74921. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74922. if (vertexBuffer) {
  74923. vertexBuffer.dispose();
  74924. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74925. }
  74926. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  74927. this._indexBuffer = null;
  74928. }
  74929. _super.prototype.dispose.call(this);
  74930. };
  74931. __decorate([
  74932. BABYLON.serialize()
  74933. ], ProceduralTexture.prototype, "_size", void 0);
  74934. __decorate([
  74935. BABYLON.serialize()
  74936. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  74937. __decorate([
  74938. BABYLON.serialize()
  74939. ], ProceduralTexture.prototype, "isEnabled", void 0);
  74940. __decorate([
  74941. BABYLON.serialize()
  74942. ], ProceduralTexture.prototype, "refreshRate", null);
  74943. return ProceduralTexture;
  74944. }(BABYLON.Texture));
  74945. BABYLON.ProceduralTexture = ProceduralTexture;
  74946. })(BABYLON || (BABYLON = {}));
  74947. //# sourceMappingURL=babylon.proceduralTexture.js.map
  74948. var BABYLON;
  74949. (function (BABYLON) {
  74950. /**
  74951. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  74952. * in a given scene.
  74953. */
  74954. var ProceduralTextureSceneComponent = /** @class */ (function () {
  74955. /**
  74956. * Creates a new instance of the component for the given scene
  74957. * @param scene Defines the scene to register the component in
  74958. */
  74959. function ProceduralTextureSceneComponent(scene) {
  74960. /**
  74961. * The component name helpfull to identify the component in the list of scene components.
  74962. */
  74963. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  74964. this.scene = scene;
  74965. this.scene.proceduralTextures = new Array();
  74966. scene.layers = new Array();
  74967. }
  74968. /**
  74969. * Registers the component in a given scene
  74970. */
  74971. ProceduralTextureSceneComponent.prototype.register = function () {
  74972. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  74973. };
  74974. /**
  74975. * Rebuilds the elements related to this component in case of
  74976. * context lost for instance.
  74977. */
  74978. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  74979. // Nothing to do here.
  74980. };
  74981. /**
  74982. * Disposes the component and the associated ressources.
  74983. */
  74984. ProceduralTextureSceneComponent.prototype.dispose = function () {
  74985. // Nothing to do here.
  74986. };
  74987. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  74988. if (this.scene.proceduralTexturesEnabled) {
  74989. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74990. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  74991. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  74992. if (proceduralTexture._shouldRender()) {
  74993. proceduralTexture.render();
  74994. }
  74995. }
  74996. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74997. }
  74998. };
  74999. return ProceduralTextureSceneComponent;
  75000. }());
  75001. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  75002. })(BABYLON || (BABYLON = {}));
  75003. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  75004. var BABYLON;
  75005. (function (BABYLON) {
  75006. var CustomProceduralTexture = /** @class */ (function (_super) {
  75007. __extends(CustomProceduralTexture, _super);
  75008. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  75009. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  75010. _this._animate = true;
  75011. _this._time = 0;
  75012. _this._texturePath = texturePath;
  75013. //Try to load json
  75014. _this.loadJson(texturePath);
  75015. _this.refreshRate = 1;
  75016. return _this;
  75017. }
  75018. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  75019. var _this = this;
  75020. var noConfigFile = function () {
  75021. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  75022. try {
  75023. _this.setFragment(_this._texturePath);
  75024. }
  75025. catch (ex) {
  75026. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  75027. }
  75028. };
  75029. var configFileUrl = jsonUrl + "/config.json";
  75030. var xhr = new XMLHttpRequest();
  75031. xhr.open("GET", configFileUrl, true);
  75032. xhr.addEventListener("load", function () {
  75033. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  75034. try {
  75035. _this._config = JSON.parse(xhr.response);
  75036. _this.updateShaderUniforms();
  75037. _this.updateTextures();
  75038. _this.setFragment(_this._texturePath + "/custom");
  75039. _this._animate = _this._config.animate;
  75040. _this.refreshRate = _this._config.refreshrate;
  75041. }
  75042. catch (ex) {
  75043. noConfigFile();
  75044. }
  75045. }
  75046. else {
  75047. noConfigFile();
  75048. }
  75049. }, false);
  75050. xhr.addEventListener("error", function () {
  75051. noConfigFile();
  75052. }, false);
  75053. try {
  75054. xhr.send();
  75055. }
  75056. catch (ex) {
  75057. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  75058. }
  75059. };
  75060. CustomProceduralTexture.prototype.isReady = function () {
  75061. if (!_super.prototype.isReady.call(this)) {
  75062. return false;
  75063. }
  75064. for (var name in this._textures) {
  75065. var texture = this._textures[name];
  75066. if (!texture.isReady()) {
  75067. return false;
  75068. }
  75069. }
  75070. return true;
  75071. };
  75072. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  75073. var scene = this.getScene();
  75074. if (this._animate && scene) {
  75075. this._time += scene.getAnimationRatio() * 0.03;
  75076. this.updateShaderUniforms();
  75077. }
  75078. _super.prototype.render.call(this, useCameraPostProcess);
  75079. };
  75080. CustomProceduralTexture.prototype.updateTextures = function () {
  75081. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  75082. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  75083. }
  75084. };
  75085. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  75086. if (this._config) {
  75087. for (var j = 0; j < this._config.uniforms.length; j++) {
  75088. var uniform = this._config.uniforms[j];
  75089. switch (uniform.type) {
  75090. case "float":
  75091. this.setFloat(uniform.name, uniform.value);
  75092. break;
  75093. case "color3":
  75094. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  75095. break;
  75096. case "color4":
  75097. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  75098. break;
  75099. case "vector2":
  75100. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  75101. break;
  75102. case "vector3":
  75103. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  75104. break;
  75105. }
  75106. }
  75107. }
  75108. this.setFloat("time", this._time);
  75109. };
  75110. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  75111. get: function () {
  75112. return this._animate;
  75113. },
  75114. set: function (value) {
  75115. this._animate = value;
  75116. },
  75117. enumerable: true,
  75118. configurable: true
  75119. });
  75120. return CustomProceduralTexture;
  75121. }(BABYLON.ProceduralTexture));
  75122. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  75123. })(BABYLON || (BABYLON = {}));
  75124. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  75125. var BABYLON;
  75126. (function (BABYLON) {
  75127. var FreeCameraGamepadInput = /** @class */ (function () {
  75128. function FreeCameraGamepadInput() {
  75129. this.gamepadAngularSensibility = 200;
  75130. this.gamepadMoveSensibility = 40;
  75131. // private members
  75132. this._cameraTransform = BABYLON.Matrix.Identity();
  75133. this._deltaTransform = BABYLON.Vector3.Zero();
  75134. this._vector3 = BABYLON.Vector3.Zero();
  75135. this._vector2 = BABYLON.Vector2.Zero();
  75136. }
  75137. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  75138. var _this = this;
  75139. var manager = this.camera.getScene().gamepadManager;
  75140. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  75141. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  75142. // prioritize XBOX gamepads.
  75143. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  75144. _this.gamepad = gamepad;
  75145. }
  75146. }
  75147. });
  75148. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  75149. if (_this.gamepad === gamepad) {
  75150. _this.gamepad = null;
  75151. }
  75152. });
  75153. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  75154. };
  75155. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  75156. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  75157. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  75158. this.gamepad = null;
  75159. };
  75160. FreeCameraGamepadInput.prototype.checkInputs = function () {
  75161. if (this.gamepad && this.gamepad.leftStick) {
  75162. var camera = this.camera;
  75163. var LSValues = this.gamepad.leftStick;
  75164. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  75165. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  75166. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  75167. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  75168. var RSValues = this.gamepad.rightStick;
  75169. if (RSValues) {
  75170. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  75171. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  75172. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  75173. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  75174. }
  75175. else {
  75176. RSValues = { x: 0, y: 0 };
  75177. }
  75178. if (!camera.rotationQuaternion) {
  75179. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  75180. }
  75181. else {
  75182. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  75183. }
  75184. var speed = camera._computeLocalCameraSpeed() * 50.0;
  75185. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  75186. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  75187. camera.cameraDirection.addInPlace(this._deltaTransform);
  75188. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  75189. camera.cameraRotation.addInPlace(this._vector2);
  75190. }
  75191. };
  75192. FreeCameraGamepadInput.prototype.getClassName = function () {
  75193. return "FreeCameraGamepadInput";
  75194. };
  75195. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  75196. return "gamepad";
  75197. };
  75198. __decorate([
  75199. BABYLON.serialize()
  75200. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  75201. __decorate([
  75202. BABYLON.serialize()
  75203. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  75204. return FreeCameraGamepadInput;
  75205. }());
  75206. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  75207. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  75208. })(BABYLON || (BABYLON = {}));
  75209. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  75210. var BABYLON;
  75211. (function (BABYLON) {
  75212. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  75213. function ArcRotateCameraGamepadInput() {
  75214. this.gamepadRotationSensibility = 80;
  75215. this.gamepadMoveSensibility = 40;
  75216. }
  75217. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  75218. var _this = this;
  75219. var manager = this.camera.getScene().gamepadManager;
  75220. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  75221. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  75222. // prioritize XBOX gamepads.
  75223. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  75224. _this.gamepad = gamepad;
  75225. }
  75226. }
  75227. });
  75228. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  75229. if (_this.gamepad === gamepad) {
  75230. _this.gamepad = null;
  75231. }
  75232. });
  75233. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  75234. };
  75235. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  75236. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  75237. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  75238. this.gamepad = null;
  75239. };
  75240. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  75241. if (this.gamepad) {
  75242. var camera = this.camera;
  75243. var RSValues = this.gamepad.rightStick;
  75244. if (RSValues) {
  75245. if (RSValues.x != 0) {
  75246. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  75247. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  75248. camera.inertialAlphaOffset += normalizedRX;
  75249. }
  75250. }
  75251. if (RSValues.y != 0) {
  75252. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  75253. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  75254. camera.inertialBetaOffset += normalizedRY;
  75255. }
  75256. }
  75257. }
  75258. var LSValues = this.gamepad.leftStick;
  75259. if (LSValues && LSValues.y != 0) {
  75260. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  75261. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  75262. this.camera.inertialRadiusOffset -= normalizedLY;
  75263. }
  75264. }
  75265. }
  75266. };
  75267. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  75268. return "ArcRotateCameraGamepadInput";
  75269. };
  75270. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  75271. return "gamepad";
  75272. };
  75273. __decorate([
  75274. BABYLON.serialize()
  75275. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  75276. __decorate([
  75277. BABYLON.serialize()
  75278. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  75279. return ArcRotateCameraGamepadInput;
  75280. }());
  75281. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  75282. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  75283. })(BABYLON || (BABYLON = {}));
  75284. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  75285. var BABYLON;
  75286. (function (BABYLON) {
  75287. var GamepadManager = /** @class */ (function () {
  75288. function GamepadManager(_scene) {
  75289. var _this = this;
  75290. this._scene = _scene;
  75291. this._babylonGamepads = [];
  75292. this._oneGamepadConnected = false;
  75293. /** @hidden */
  75294. this._isMonitoring = false;
  75295. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  75296. if (!BABYLON.Tools.IsWindowObjectExist()) {
  75297. this._gamepadEventSupported = false;
  75298. }
  75299. else {
  75300. this._gamepadEventSupported = 'GamepadEvent' in window;
  75301. this._gamepadSupport = (navigator.getGamepads ||
  75302. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  75303. }
  75304. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  75305. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  75306. for (var i in _this._babylonGamepads) {
  75307. var gamepad = _this._babylonGamepads[i];
  75308. if (gamepad && gamepad._isConnected) {
  75309. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  75310. }
  75311. }
  75312. });
  75313. this._onGamepadConnectedEvent = function (evt) {
  75314. var gamepad = evt.gamepad;
  75315. if (gamepad.index in _this._babylonGamepads) {
  75316. if (_this._babylonGamepads[gamepad.index].isConnected) {
  75317. return;
  75318. }
  75319. }
  75320. var newGamepad;
  75321. if (_this._babylonGamepads[gamepad.index]) {
  75322. newGamepad = _this._babylonGamepads[gamepad.index];
  75323. newGamepad.browserGamepad = gamepad;
  75324. newGamepad._isConnected = true;
  75325. }
  75326. else {
  75327. newGamepad = _this._addNewGamepad(gamepad);
  75328. }
  75329. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  75330. _this._startMonitoringGamepads();
  75331. };
  75332. this._onGamepadDisconnectedEvent = function (evt) {
  75333. var gamepad = evt.gamepad;
  75334. // Remove the gamepad from the list of gamepads to monitor.
  75335. for (var i in _this._babylonGamepads) {
  75336. if (_this._babylonGamepads[i].index === gamepad.index) {
  75337. var disconnectedGamepad = _this._babylonGamepads[i];
  75338. disconnectedGamepad._isConnected = false;
  75339. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  75340. break;
  75341. }
  75342. }
  75343. };
  75344. if (this._gamepadSupport) {
  75345. //first add already-connected gamepads
  75346. this._updateGamepadObjects();
  75347. if (this._babylonGamepads.length) {
  75348. this._startMonitoringGamepads();
  75349. }
  75350. // Checking if the gamepad connected event is supported (like in Firefox)
  75351. if (this._gamepadEventSupported) {
  75352. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  75353. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  75354. }
  75355. else {
  75356. this._startMonitoringGamepads();
  75357. }
  75358. }
  75359. }
  75360. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  75361. get: function () {
  75362. return this._babylonGamepads;
  75363. },
  75364. enumerable: true,
  75365. configurable: true
  75366. });
  75367. GamepadManager.prototype.getGamepadByType = function (type) {
  75368. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  75369. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  75370. var gamepad = _a[_i];
  75371. if (gamepad && gamepad.type === type) {
  75372. return gamepad;
  75373. }
  75374. }
  75375. return null;
  75376. };
  75377. GamepadManager.prototype.dispose = function () {
  75378. if (this._gamepadEventSupported) {
  75379. if (this._onGamepadConnectedEvent) {
  75380. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  75381. }
  75382. if (this._onGamepadDisconnectedEvent) {
  75383. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  75384. }
  75385. this._onGamepadConnectedEvent = null;
  75386. this._onGamepadDisconnectedEvent = null;
  75387. }
  75388. this._babylonGamepads.forEach(function (gamepad) {
  75389. gamepad.dispose();
  75390. });
  75391. this.onGamepadConnectedObservable.clear();
  75392. this.onGamepadDisconnectedObservable.clear();
  75393. this._oneGamepadConnected = false;
  75394. this._stopMonitoringGamepads();
  75395. this._babylonGamepads = [];
  75396. };
  75397. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  75398. if (!this._oneGamepadConnected) {
  75399. this._oneGamepadConnected = true;
  75400. }
  75401. var newGamepad;
  75402. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  75403. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  75404. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  75405. }
  75406. // if pose is supported, use the (WebVR) pose enabled controller
  75407. else if (gamepad.pose) {
  75408. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  75409. }
  75410. else {
  75411. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  75412. }
  75413. this._babylonGamepads[newGamepad.index] = newGamepad;
  75414. return newGamepad;
  75415. };
  75416. GamepadManager.prototype._startMonitoringGamepads = function () {
  75417. if (!this._isMonitoring) {
  75418. this._isMonitoring = true;
  75419. //back-comp
  75420. if (!this._scene) {
  75421. this._checkGamepadsStatus();
  75422. }
  75423. }
  75424. };
  75425. GamepadManager.prototype._stopMonitoringGamepads = function () {
  75426. this._isMonitoring = false;
  75427. };
  75428. /** @hidden */
  75429. GamepadManager.prototype._checkGamepadsStatus = function () {
  75430. var _this = this;
  75431. // Hack to be compatible Chrome
  75432. this._updateGamepadObjects();
  75433. for (var i in this._babylonGamepads) {
  75434. var gamepad = this._babylonGamepads[i];
  75435. if (!gamepad || !gamepad.isConnected) {
  75436. continue;
  75437. }
  75438. gamepad.update();
  75439. }
  75440. if (this._isMonitoring && !this._scene) {
  75441. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  75442. }
  75443. };
  75444. // This function is called only on Chrome, which does not properly support
  75445. // connection/disconnection events and forces you to recopy again the gamepad object
  75446. GamepadManager.prototype._updateGamepadObjects = function () {
  75447. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  75448. for (var i = 0; i < gamepads.length; i++) {
  75449. var gamepad = gamepads[i];
  75450. if (gamepad) {
  75451. if (!this._babylonGamepads[gamepad.index]) {
  75452. var newGamepad = this._addNewGamepad(gamepad);
  75453. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  75454. }
  75455. else {
  75456. // Forced to copy again this object for Chrome for unknown reason
  75457. this._babylonGamepads[i].browserGamepad = gamepad;
  75458. if (!this._babylonGamepads[i].isConnected) {
  75459. this._babylonGamepads[i]._isConnected = true;
  75460. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  75461. }
  75462. }
  75463. }
  75464. }
  75465. };
  75466. return GamepadManager;
  75467. }());
  75468. BABYLON.GamepadManager = GamepadManager;
  75469. })(BABYLON || (BABYLON = {}));
  75470. //# sourceMappingURL=babylon.gamepadManager.js.map
  75471. var BABYLON;
  75472. (function (BABYLON) {
  75473. var StickValues = /** @class */ (function () {
  75474. function StickValues(x, y) {
  75475. this.x = x;
  75476. this.y = y;
  75477. }
  75478. return StickValues;
  75479. }());
  75480. BABYLON.StickValues = StickValues;
  75481. var Gamepad = /** @class */ (function () {
  75482. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  75483. if (leftStickX === void 0) { leftStickX = 0; }
  75484. if (leftStickY === void 0) { leftStickY = 1; }
  75485. if (rightStickX === void 0) { rightStickX = 2; }
  75486. if (rightStickY === void 0) { rightStickY = 3; }
  75487. this.id = id;
  75488. this.index = index;
  75489. this.browserGamepad = browserGamepad;
  75490. this._leftStick = { x: 0, y: 0 };
  75491. this._rightStick = { x: 0, y: 0 };
  75492. /** @hidden */
  75493. this._isConnected = true;
  75494. this._invertLeftStickY = false;
  75495. this.type = Gamepad.GAMEPAD;
  75496. this._leftStickAxisX = leftStickX;
  75497. this._leftStickAxisY = leftStickY;
  75498. this._rightStickAxisX = rightStickX;
  75499. this._rightStickAxisY = rightStickY;
  75500. if (this.browserGamepad.axes.length >= 2) {
  75501. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  75502. }
  75503. if (this.browserGamepad.axes.length >= 4) {
  75504. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  75505. }
  75506. }
  75507. Object.defineProperty(Gamepad.prototype, "isConnected", {
  75508. get: function () {
  75509. return this._isConnected;
  75510. },
  75511. enumerable: true,
  75512. configurable: true
  75513. });
  75514. Gamepad.prototype.onleftstickchanged = function (callback) {
  75515. this._onleftstickchanged = callback;
  75516. };
  75517. Gamepad.prototype.onrightstickchanged = function (callback) {
  75518. this._onrightstickchanged = callback;
  75519. };
  75520. Object.defineProperty(Gamepad.prototype, "leftStick", {
  75521. get: function () {
  75522. return this._leftStick;
  75523. },
  75524. set: function (newValues) {
  75525. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  75526. this._onleftstickchanged(newValues);
  75527. }
  75528. this._leftStick = newValues;
  75529. },
  75530. enumerable: true,
  75531. configurable: true
  75532. });
  75533. Object.defineProperty(Gamepad.prototype, "rightStick", {
  75534. get: function () {
  75535. return this._rightStick;
  75536. },
  75537. set: function (newValues) {
  75538. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  75539. this._onrightstickchanged(newValues);
  75540. }
  75541. this._rightStick = newValues;
  75542. },
  75543. enumerable: true,
  75544. configurable: true
  75545. });
  75546. Gamepad.prototype.update = function () {
  75547. if (this._leftStick) {
  75548. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  75549. if (this._invertLeftStickY) {
  75550. this.leftStick.y *= -1;
  75551. }
  75552. }
  75553. if (this._rightStick) {
  75554. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  75555. }
  75556. };
  75557. Gamepad.prototype.dispose = function () {
  75558. };
  75559. Gamepad.GAMEPAD = 0;
  75560. Gamepad.GENERIC = 1;
  75561. Gamepad.XBOX = 2;
  75562. Gamepad.POSE_ENABLED = 3;
  75563. return Gamepad;
  75564. }());
  75565. BABYLON.Gamepad = Gamepad;
  75566. var GenericPad = /** @class */ (function (_super) {
  75567. __extends(GenericPad, _super);
  75568. function GenericPad(id, index, browserGamepad) {
  75569. var _this = _super.call(this, id, index, browserGamepad) || this;
  75570. _this.onButtonDownObservable = new BABYLON.Observable();
  75571. _this.onButtonUpObservable = new BABYLON.Observable();
  75572. _this.type = Gamepad.GENERIC;
  75573. _this._buttons = new Array(browserGamepad.buttons.length);
  75574. return _this;
  75575. }
  75576. GenericPad.prototype.onbuttondown = function (callback) {
  75577. this._onbuttondown = callback;
  75578. };
  75579. GenericPad.prototype.onbuttonup = function (callback) {
  75580. this._onbuttonup = callback;
  75581. };
  75582. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  75583. if (newValue !== currentValue) {
  75584. if (newValue === 1) {
  75585. if (this._onbuttondown) {
  75586. this._onbuttondown(buttonIndex);
  75587. }
  75588. this.onButtonDownObservable.notifyObservers(buttonIndex);
  75589. }
  75590. if (newValue === 0) {
  75591. if (this._onbuttonup) {
  75592. this._onbuttonup(buttonIndex);
  75593. }
  75594. this.onButtonUpObservable.notifyObservers(buttonIndex);
  75595. }
  75596. }
  75597. return newValue;
  75598. };
  75599. GenericPad.prototype.update = function () {
  75600. _super.prototype.update.call(this);
  75601. for (var index = 0; index < this._buttons.length; index++) {
  75602. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  75603. }
  75604. };
  75605. GenericPad.prototype.dispose = function () {
  75606. _super.prototype.dispose.call(this);
  75607. this.onButtonDownObservable.clear();
  75608. this.onButtonUpObservable.clear();
  75609. };
  75610. return GenericPad;
  75611. }(Gamepad));
  75612. BABYLON.GenericPad = GenericPad;
  75613. })(BABYLON || (BABYLON = {}));
  75614. //# sourceMappingURL=babylon.gamepad.js.map
  75615. var BABYLON;
  75616. (function (BABYLON) {
  75617. /**
  75618. * Defines supported buttons for XBox360 compatible gamepads
  75619. */
  75620. var Xbox360Button;
  75621. (function (Xbox360Button) {
  75622. /** A */
  75623. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  75624. /** B */
  75625. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  75626. /** X */
  75627. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  75628. /** Y */
  75629. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  75630. /** Start */
  75631. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  75632. /** Back */
  75633. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  75634. /** Left button */
  75635. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  75636. /** Right button */
  75637. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  75638. /** Left stick */
  75639. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  75640. /** Right stick */
  75641. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  75642. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  75643. /** Defines values for XBox360 DPad */
  75644. var Xbox360Dpad;
  75645. (function (Xbox360Dpad) {
  75646. /** Up */
  75647. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  75648. /** Down */
  75649. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  75650. /** Left */
  75651. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  75652. /** Right */
  75653. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  75654. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  75655. /**
  75656. * Defines a XBox360 gamepad
  75657. */
  75658. var Xbox360Pad = /** @class */ (function (_super) {
  75659. __extends(Xbox360Pad, _super);
  75660. /**
  75661. * Creates a new XBox360 gamepad object
  75662. * @param id defines the id of this gamepad
  75663. * @param index defines its index
  75664. * @param gamepad defines the internal HTML gamepad object
  75665. * @param xboxOne defines if it is a XBox One gamepad
  75666. */
  75667. function Xbox360Pad(id, index, gamepad, xboxOne) {
  75668. if (xboxOne === void 0) { xboxOne = false; }
  75669. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  75670. _this._leftTrigger = 0;
  75671. _this._rightTrigger = 0;
  75672. /** Observable raised when a button is pressed */
  75673. _this.onButtonDownObservable = new BABYLON.Observable();
  75674. /** Observable raised when a button is released */
  75675. _this.onButtonUpObservable = new BABYLON.Observable();
  75676. /** Observable raised when a pad is pressed */
  75677. _this.onPadDownObservable = new BABYLON.Observable();
  75678. /** Observable raised when a pad is released */
  75679. _this.onPadUpObservable = new BABYLON.Observable();
  75680. _this._buttonA = 0;
  75681. _this._buttonB = 0;
  75682. _this._buttonX = 0;
  75683. _this._buttonY = 0;
  75684. _this._buttonBack = 0;
  75685. _this._buttonStart = 0;
  75686. _this._buttonLB = 0;
  75687. _this._buttonRB = 0;
  75688. _this._buttonLeftStick = 0;
  75689. _this._buttonRightStick = 0;
  75690. _this._dPadUp = 0;
  75691. _this._dPadDown = 0;
  75692. _this._dPadLeft = 0;
  75693. _this._dPadRight = 0;
  75694. _this._isXboxOnePad = false;
  75695. _this.type = BABYLON.Gamepad.XBOX;
  75696. _this._isXboxOnePad = xboxOne;
  75697. return _this;
  75698. }
  75699. /**
  75700. * Defines the callback to call when left trigger is pressed
  75701. * @param callback defines the callback to use
  75702. */
  75703. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  75704. this._onlefttriggerchanged = callback;
  75705. };
  75706. /**
  75707. * Defines the callback to call when right trigger is pressed
  75708. * @param callback defines the callback to use
  75709. */
  75710. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  75711. this._onrighttriggerchanged = callback;
  75712. };
  75713. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  75714. /**
  75715. * Gets or sets left trigger value
  75716. */
  75717. get: function () {
  75718. return this._leftTrigger;
  75719. },
  75720. set: function (newValue) {
  75721. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  75722. this._onlefttriggerchanged(newValue);
  75723. }
  75724. this._leftTrigger = newValue;
  75725. },
  75726. enumerable: true,
  75727. configurable: true
  75728. });
  75729. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  75730. /**
  75731. * Gets or sets right trigger value
  75732. */
  75733. get: function () {
  75734. return this._rightTrigger;
  75735. },
  75736. set: function (newValue) {
  75737. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  75738. this._onrighttriggerchanged(newValue);
  75739. }
  75740. this._rightTrigger = newValue;
  75741. },
  75742. enumerable: true,
  75743. configurable: true
  75744. });
  75745. /**
  75746. * Defines the callback to call when a button is pressed
  75747. * @param callback defines the callback to use
  75748. */
  75749. Xbox360Pad.prototype.onbuttondown = function (callback) {
  75750. this._onbuttondown = callback;
  75751. };
  75752. /**
  75753. * Defines the callback to call when a button is released
  75754. * @param callback defines the callback to use
  75755. */
  75756. Xbox360Pad.prototype.onbuttonup = function (callback) {
  75757. this._onbuttonup = callback;
  75758. };
  75759. /**
  75760. * Defines the callback to call when a pad is pressed
  75761. * @param callback defines the callback to use
  75762. */
  75763. Xbox360Pad.prototype.ondpaddown = function (callback) {
  75764. this._ondpaddown = callback;
  75765. };
  75766. /**
  75767. * Defines the callback to call when a pad is released
  75768. * @param callback defines the callback to use
  75769. */
  75770. Xbox360Pad.prototype.ondpadup = function (callback) {
  75771. this._ondpadup = callback;
  75772. };
  75773. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  75774. if (newValue !== currentValue) {
  75775. if (newValue === 1) {
  75776. if (this._onbuttondown) {
  75777. this._onbuttondown(buttonType);
  75778. }
  75779. this.onButtonDownObservable.notifyObservers(buttonType);
  75780. }
  75781. if (newValue === 0) {
  75782. if (this._onbuttonup) {
  75783. this._onbuttonup(buttonType);
  75784. }
  75785. this.onButtonUpObservable.notifyObservers(buttonType);
  75786. }
  75787. }
  75788. return newValue;
  75789. };
  75790. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  75791. if (newValue !== currentValue) {
  75792. if (newValue === 1) {
  75793. if (this._ondpaddown) {
  75794. this._ondpaddown(buttonType);
  75795. }
  75796. this.onPadDownObservable.notifyObservers(buttonType);
  75797. }
  75798. if (newValue === 0) {
  75799. if (this._ondpadup) {
  75800. this._ondpadup(buttonType);
  75801. }
  75802. this.onPadUpObservable.notifyObservers(buttonType);
  75803. }
  75804. }
  75805. return newValue;
  75806. };
  75807. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  75808. /** Gets or sets value of A button */
  75809. get: function () {
  75810. return this._buttonA;
  75811. },
  75812. set: function (value) {
  75813. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  75814. },
  75815. enumerable: true,
  75816. configurable: true
  75817. });
  75818. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  75819. /** Gets or sets value of B button */
  75820. get: function () {
  75821. return this._buttonB;
  75822. },
  75823. set: function (value) {
  75824. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  75825. },
  75826. enumerable: true,
  75827. configurable: true
  75828. });
  75829. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  75830. /** Gets or sets value of X button */
  75831. get: function () {
  75832. return this._buttonX;
  75833. },
  75834. set: function (value) {
  75835. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  75836. },
  75837. enumerable: true,
  75838. configurable: true
  75839. });
  75840. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  75841. /** Gets or sets value of Y button */
  75842. get: function () {
  75843. return this._buttonY;
  75844. },
  75845. set: function (value) {
  75846. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  75847. },
  75848. enumerable: true,
  75849. configurable: true
  75850. });
  75851. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  75852. /** Gets or sets value of Start button */
  75853. get: function () {
  75854. return this._buttonStart;
  75855. },
  75856. set: function (value) {
  75857. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  75858. },
  75859. enumerable: true,
  75860. configurable: true
  75861. });
  75862. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  75863. /** Gets or sets value of Back button */
  75864. get: function () {
  75865. return this._buttonBack;
  75866. },
  75867. set: function (value) {
  75868. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  75869. },
  75870. enumerable: true,
  75871. configurable: true
  75872. });
  75873. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  75874. /** Gets or sets value of Left button */
  75875. get: function () {
  75876. return this._buttonLB;
  75877. },
  75878. set: function (value) {
  75879. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  75880. },
  75881. enumerable: true,
  75882. configurable: true
  75883. });
  75884. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  75885. /** Gets or sets value of Right button */
  75886. get: function () {
  75887. return this._buttonRB;
  75888. },
  75889. set: function (value) {
  75890. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  75891. },
  75892. enumerable: true,
  75893. configurable: true
  75894. });
  75895. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  75896. /** Gets or sets value of left stick */
  75897. get: function () {
  75898. return this._buttonLeftStick;
  75899. },
  75900. set: function (value) {
  75901. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  75902. },
  75903. enumerable: true,
  75904. configurable: true
  75905. });
  75906. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  75907. /** Gets or sets value of right stick */
  75908. get: function () {
  75909. return this._buttonRightStick;
  75910. },
  75911. set: function (value) {
  75912. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  75913. },
  75914. enumerable: true,
  75915. configurable: true
  75916. });
  75917. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  75918. /** Gets or sets value of DPad up */
  75919. get: function () {
  75920. return this._dPadUp;
  75921. },
  75922. set: function (value) {
  75923. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  75924. },
  75925. enumerable: true,
  75926. configurable: true
  75927. });
  75928. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  75929. /** Gets or sets value of DPad down */
  75930. get: function () {
  75931. return this._dPadDown;
  75932. },
  75933. set: function (value) {
  75934. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  75935. },
  75936. enumerable: true,
  75937. configurable: true
  75938. });
  75939. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  75940. /** Gets or sets value of DPad left */
  75941. get: function () {
  75942. return this._dPadLeft;
  75943. },
  75944. set: function (value) {
  75945. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  75946. },
  75947. enumerable: true,
  75948. configurable: true
  75949. });
  75950. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  75951. /** Gets or sets value of DPad right */
  75952. get: function () {
  75953. return this._dPadRight;
  75954. },
  75955. set: function (value) {
  75956. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  75957. },
  75958. enumerable: true,
  75959. configurable: true
  75960. });
  75961. /**
  75962. * Force the gamepad to synchronize with device values
  75963. */
  75964. Xbox360Pad.prototype.update = function () {
  75965. _super.prototype.update.call(this);
  75966. if (this._isXboxOnePad) {
  75967. this.buttonA = this.browserGamepad.buttons[0].value;
  75968. this.buttonB = this.browserGamepad.buttons[1].value;
  75969. this.buttonX = this.browserGamepad.buttons[2].value;
  75970. this.buttonY = this.browserGamepad.buttons[3].value;
  75971. this.buttonLB = this.browserGamepad.buttons[4].value;
  75972. this.buttonRB = this.browserGamepad.buttons[5].value;
  75973. this.leftTrigger = this.browserGamepad.axes[2];
  75974. this.rightTrigger = this.browserGamepad.axes[5];
  75975. this.buttonBack = this.browserGamepad.buttons[9].value;
  75976. this.buttonStart = this.browserGamepad.buttons[8].value;
  75977. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  75978. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  75979. this.dPadUp = this.browserGamepad.buttons[11].value;
  75980. this.dPadDown = this.browserGamepad.buttons[12].value;
  75981. this.dPadLeft = this.browserGamepad.buttons[13].value;
  75982. this.dPadRight = this.browserGamepad.buttons[14].value;
  75983. }
  75984. else {
  75985. this.buttonA = this.browserGamepad.buttons[0].value;
  75986. this.buttonB = this.browserGamepad.buttons[1].value;
  75987. this.buttonX = this.browserGamepad.buttons[2].value;
  75988. this.buttonY = this.browserGamepad.buttons[3].value;
  75989. this.buttonLB = this.browserGamepad.buttons[4].value;
  75990. this.buttonRB = this.browserGamepad.buttons[5].value;
  75991. this.leftTrigger = this.browserGamepad.buttons[6].value;
  75992. this.rightTrigger = this.browserGamepad.buttons[7].value;
  75993. this.buttonBack = this.browserGamepad.buttons[8].value;
  75994. this.buttonStart = this.browserGamepad.buttons[9].value;
  75995. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  75996. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  75997. this.dPadUp = this.browserGamepad.buttons[12].value;
  75998. this.dPadDown = this.browserGamepad.buttons[13].value;
  75999. this.dPadLeft = this.browserGamepad.buttons[14].value;
  76000. this.dPadRight = this.browserGamepad.buttons[15].value;
  76001. }
  76002. };
  76003. Xbox360Pad.prototype.dispose = function () {
  76004. _super.prototype.dispose.call(this);
  76005. this.onButtonDownObservable.clear();
  76006. this.onButtonUpObservable.clear();
  76007. this.onPadDownObservable.clear();
  76008. this.onPadUpObservable.clear();
  76009. };
  76010. return Xbox360Pad;
  76011. }(BABYLON.Gamepad));
  76012. BABYLON.Xbox360Pad = Xbox360Pad;
  76013. })(BABYLON || (BABYLON = {}));
  76014. //# sourceMappingURL=babylon.xboxGamepad.js.map
  76015. var BABYLON;
  76016. (function (BABYLON) {
  76017. /**
  76018. * Defines the types of pose enabled controllers that are supported
  76019. */
  76020. var PoseEnabledControllerType;
  76021. (function (PoseEnabledControllerType) {
  76022. /**
  76023. * HTC Vive
  76024. */
  76025. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  76026. /**
  76027. * Oculus Rift
  76028. */
  76029. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  76030. /**
  76031. * Windows mixed reality
  76032. */
  76033. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  76034. /**
  76035. * Samsung gear VR
  76036. */
  76037. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  76038. /**
  76039. * Google Daydream
  76040. */
  76041. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  76042. /**
  76043. * Generic
  76044. */
  76045. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  76046. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  76047. /**
  76048. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  76049. */
  76050. var PoseEnabledControllerHelper = /** @class */ (function () {
  76051. function PoseEnabledControllerHelper() {
  76052. }
  76053. /**
  76054. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  76055. * @param vrGamepad the gamepad to initialized
  76056. * @returns a vr controller of the type the gamepad identified as
  76057. */
  76058. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  76059. // Oculus Touch
  76060. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  76061. return new BABYLON.OculusTouchController(vrGamepad);
  76062. }
  76063. // Windows Mixed Reality controllers
  76064. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  76065. return new BABYLON.WindowsMotionController(vrGamepad);
  76066. }
  76067. // HTC Vive
  76068. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  76069. return new BABYLON.ViveController(vrGamepad);
  76070. }
  76071. // Samsung/Oculus Gear VR or Oculus Go
  76072. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  76073. return new BABYLON.GearVRController(vrGamepad);
  76074. }
  76075. // Google Daydream
  76076. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  76077. return new BABYLON.DaydreamController(vrGamepad);
  76078. }
  76079. // Generic
  76080. else {
  76081. return new BABYLON.GenericController(vrGamepad);
  76082. }
  76083. };
  76084. return PoseEnabledControllerHelper;
  76085. }());
  76086. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  76087. /**
  76088. * Defines the PoseEnabledController object that contains state of a vr capable controller
  76089. */
  76090. var PoseEnabledController = /** @class */ (function (_super) {
  76091. __extends(PoseEnabledController, _super);
  76092. /**
  76093. * Creates a new PoseEnabledController from a gamepad
  76094. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  76095. */
  76096. function PoseEnabledController(browserGamepad) {
  76097. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  76098. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  76099. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  76100. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  76101. /**
  76102. * The device position in babylon space
  76103. */
  76104. _this.devicePosition = BABYLON.Vector3.Zero();
  76105. /**
  76106. * The device rotation in babylon space
  76107. */
  76108. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  76109. /**
  76110. * The scale factor of the device in babylon space
  76111. */
  76112. _this.deviceScaleFactor = 1;
  76113. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  76114. /**
  76115. * Internal, matrix used to convert room space to babylon space
  76116. * @hidden
  76117. */
  76118. _this._deviceToWorld = BABYLON.Matrix.Identity();
  76119. /**
  76120. * Node to be used when casting a ray from the controller
  76121. * @hidden
  76122. */
  76123. _this._pointingPoseNode = null;
  76124. _this._workingMatrix = BABYLON.Matrix.Identity();
  76125. /**
  76126. * @hidden
  76127. */
  76128. _this._meshAttachedObservable = new BABYLON.Observable();
  76129. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  76130. _this.controllerType = PoseEnabledControllerType.GENERIC;
  76131. _this.position = BABYLON.Vector3.Zero();
  76132. _this.rotationQuaternion = new BABYLON.Quaternion();
  76133. _this._calculatedPosition = BABYLON.Vector3.Zero();
  76134. _this._calculatedRotation = new BABYLON.Quaternion();
  76135. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  76136. return _this;
  76137. }
  76138. /**
  76139. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  76140. */
  76141. PoseEnabledController.prototype.update = function () {
  76142. _super.prototype.update.call(this);
  76143. this._updatePoseAndMesh();
  76144. };
  76145. /**
  76146. * Updates only the pose device and mesh without doing any button event checking
  76147. */
  76148. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  76149. var pose = this.browserGamepad.pose;
  76150. this.updateFromDevice(pose);
  76151. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  76152. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  76153. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  76154. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  76155. if (this._mesh) {
  76156. this._mesh.position.copyFrom(this.devicePosition);
  76157. if (this._mesh.rotationQuaternion) {
  76158. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  76159. }
  76160. }
  76161. };
  76162. /**
  76163. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  76164. * @param poseData raw pose fromthe device
  76165. */
  76166. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  76167. if (poseData) {
  76168. this.rawPose = poseData;
  76169. if (poseData.position) {
  76170. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  76171. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  76172. this._deviceRoomPosition.z *= -1;
  76173. }
  76174. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  76175. this._calculatedPosition.addInPlace(this.position);
  76176. }
  76177. var pose = this.rawPose;
  76178. if (poseData.orientation && pose.orientation) {
  76179. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  76180. if (this._mesh) {
  76181. if (this._mesh.getScene().useRightHandedSystem) {
  76182. this._deviceRoomRotationQuaternion.z *= -1;
  76183. this._deviceRoomRotationQuaternion.w *= -1;
  76184. }
  76185. else {
  76186. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  76187. }
  76188. }
  76189. // if the camera is set, rotate to the camera's rotation
  76190. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  76191. }
  76192. }
  76193. };
  76194. /**
  76195. * Attaches a mesh to the controller
  76196. * @param mesh the mesh to be attached
  76197. */
  76198. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  76199. if (this._mesh) {
  76200. this._mesh.parent = null;
  76201. }
  76202. this._mesh = mesh;
  76203. if (this._poseControlledCamera) {
  76204. this._mesh.parent = this._poseControlledCamera;
  76205. }
  76206. if (!this._mesh.rotationQuaternion) {
  76207. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  76208. }
  76209. // 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
  76210. this._updatePoseAndMesh();
  76211. if (this._pointingPoseNode) {
  76212. var parents = [];
  76213. var obj = this._pointingPoseNode;
  76214. while (obj.parent) {
  76215. parents.push(obj.parent);
  76216. obj = obj.parent;
  76217. }
  76218. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  76219. }
  76220. this._meshAttachedObservable.notifyObservers(mesh);
  76221. };
  76222. /**
  76223. * Attaches the controllers mesh to a camera
  76224. * @param camera the camera the mesh should be attached to
  76225. */
  76226. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  76227. this._poseControlledCamera = camera;
  76228. if (this._mesh) {
  76229. this._mesh.parent = this._poseControlledCamera;
  76230. }
  76231. };
  76232. /**
  76233. * Disposes of the controller
  76234. */
  76235. PoseEnabledController.prototype.dispose = function () {
  76236. if (this._mesh) {
  76237. this._mesh.dispose();
  76238. }
  76239. this._mesh = null;
  76240. _super.prototype.dispose.call(this);
  76241. };
  76242. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  76243. /**
  76244. * The mesh that is attached to the controller
  76245. */
  76246. get: function () {
  76247. return this._mesh;
  76248. },
  76249. enumerable: true,
  76250. configurable: true
  76251. });
  76252. /**
  76253. * Gets the ray of the controller in the direction the controller is pointing
  76254. * @param length the length the resulting ray should be
  76255. * @returns a ray in the direction the controller is pointing
  76256. */
  76257. PoseEnabledController.prototype.getForwardRay = function (length) {
  76258. if (length === void 0) { length = 100; }
  76259. if (!this.mesh) {
  76260. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  76261. }
  76262. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  76263. var origin = m.getTranslation();
  76264. var forward = new BABYLON.Vector3(0, 0, -1);
  76265. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  76266. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  76267. return new BABYLON.Ray(origin, direction, length);
  76268. };
  76269. /**
  76270. * Name of the child mesh that can be used to cast a ray from the controller
  76271. */
  76272. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  76273. return PoseEnabledController;
  76274. }(BABYLON.Gamepad));
  76275. BABYLON.PoseEnabledController = PoseEnabledController;
  76276. })(BABYLON || (BABYLON = {}));
  76277. //# sourceMappingURL=babylon.poseEnabledController.js.map
  76278. var BABYLON;
  76279. (function (BABYLON) {
  76280. /**
  76281. * Defines the WebVRController object that represents controllers tracked in 3D space
  76282. */
  76283. var WebVRController = /** @class */ (function (_super) {
  76284. __extends(WebVRController, _super);
  76285. /**
  76286. * Creates a new WebVRController from a gamepad
  76287. * @param vrGamepad the gamepad that the WebVRController should be created from
  76288. */
  76289. function WebVRController(vrGamepad) {
  76290. var _this = _super.call(this, vrGamepad) || this;
  76291. // Observables
  76292. /**
  76293. * Fired when the trigger state has changed
  76294. */
  76295. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  76296. /**
  76297. * Fired when the main button state has changed
  76298. */
  76299. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  76300. /**
  76301. * Fired when the secondary button state has changed
  76302. */
  76303. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  76304. /**
  76305. * Fired when the pad state has changed
  76306. */
  76307. _this.onPadStateChangedObservable = new BABYLON.Observable();
  76308. /**
  76309. * Fired when controllers stick values have changed
  76310. */
  76311. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  76312. /**
  76313. * X and Y axis corrisponding to the controllers joystick
  76314. */
  76315. _this.pad = { x: 0, y: 0 };
  76316. // avoid GC, store state in a tmp object
  76317. _this._changes = {
  76318. pressChanged: false,
  76319. touchChanged: false,
  76320. valueChanged: false,
  76321. changed: false
  76322. };
  76323. _this._buttons = new Array(vrGamepad.buttons.length);
  76324. _this.hand = vrGamepad.hand;
  76325. return _this;
  76326. }
  76327. /**
  76328. * Fired when a controller button's state has changed
  76329. * @param callback the callback containing the button that was modified
  76330. */
  76331. WebVRController.prototype.onButtonStateChange = function (callback) {
  76332. this._onButtonStateChange = callback;
  76333. };
  76334. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  76335. /**
  76336. * The default controller model for the controller
  76337. */
  76338. get: function () {
  76339. return this._defaultModel;
  76340. },
  76341. enumerable: true,
  76342. configurable: true
  76343. });
  76344. /**
  76345. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  76346. */
  76347. WebVRController.prototype.update = function () {
  76348. _super.prototype.update.call(this);
  76349. for (var index = 0; index < this._buttons.length; index++) {
  76350. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  76351. }
  76352. ;
  76353. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  76354. this.pad.x = this.leftStick.x;
  76355. this.pad.y = this.leftStick.y;
  76356. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  76357. }
  76358. };
  76359. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  76360. if (!newState) {
  76361. newState = {
  76362. pressed: false,
  76363. touched: false,
  76364. value: 0
  76365. };
  76366. }
  76367. if (!currentState) {
  76368. this._buttons[buttonIndex] = {
  76369. pressed: newState.pressed,
  76370. touched: newState.touched,
  76371. value: newState.value
  76372. };
  76373. return;
  76374. }
  76375. this._checkChanges(newState, currentState);
  76376. if (this._changes.changed) {
  76377. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  76378. this._handleButtonChange(buttonIndex, newState, this._changes);
  76379. }
  76380. this._buttons[buttonIndex].pressed = newState.pressed;
  76381. this._buttons[buttonIndex].touched = newState.touched;
  76382. // oculus triggers are never 0, thou not touched.
  76383. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  76384. };
  76385. WebVRController.prototype._checkChanges = function (newState, currentState) {
  76386. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  76387. this._changes.touchChanged = newState.touched !== currentState.touched;
  76388. this._changes.valueChanged = newState.value !== currentState.value;
  76389. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  76390. return this._changes;
  76391. };
  76392. /**
  76393. * Disposes of th webVRCOntroller
  76394. */
  76395. WebVRController.prototype.dispose = function () {
  76396. _super.prototype.dispose.call(this);
  76397. this.onTriggerStateChangedObservable.clear();
  76398. this.onMainButtonStateChangedObservable.clear();
  76399. this.onSecondaryButtonStateChangedObservable.clear();
  76400. this.onPadStateChangedObservable.clear();
  76401. this.onPadValuesChangedObservable.clear();
  76402. };
  76403. return WebVRController;
  76404. }(BABYLON.PoseEnabledController));
  76405. BABYLON.WebVRController = WebVRController;
  76406. })(BABYLON || (BABYLON = {}));
  76407. //# sourceMappingURL=babylon.webVRController.js.map
  76408. var BABYLON;
  76409. (function (BABYLON) {
  76410. /**
  76411. * Oculus Touch Controller
  76412. */
  76413. var OculusTouchController = /** @class */ (function (_super) {
  76414. __extends(OculusTouchController, _super);
  76415. /**
  76416. * Creates a new OculusTouchController from a gamepad
  76417. * @param vrGamepad the gamepad that the controller should be created from
  76418. */
  76419. function OculusTouchController(vrGamepad) {
  76420. var _this = _super.call(this, vrGamepad) || this;
  76421. /**
  76422. * Fired when the secondary trigger on this controller is modified
  76423. */
  76424. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  76425. /**
  76426. * Fired when the thumb rest on this controller is modified
  76427. */
  76428. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  76429. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  76430. return _this;
  76431. }
  76432. /**
  76433. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76434. * @param scene scene in which to add meshes
  76435. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76436. */
  76437. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76438. var _this = this;
  76439. var meshName;
  76440. // Hand
  76441. if (this.hand === 'left') {
  76442. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  76443. }
  76444. else { // Right is the default if no hand is specified
  76445. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  76446. }
  76447. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  76448. /*
  76449. Parent Mesh name: oculus_touch_left
  76450. - body
  76451. - trigger
  76452. - thumbstick
  76453. - grip
  76454. - button_y
  76455. - button_x
  76456. - button_enter
  76457. */
  76458. _this._defaultModel = newMeshes[1];
  76459. _this.attachToMesh(_this._defaultModel);
  76460. if (meshLoaded) {
  76461. meshLoaded(_this._defaultModel);
  76462. }
  76463. });
  76464. };
  76465. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  76466. /**
  76467. * Fired when the A button on this controller is modified
  76468. */
  76469. get: function () {
  76470. if (this.hand === 'right') {
  76471. return this.onMainButtonStateChangedObservable;
  76472. }
  76473. else {
  76474. throw new Error('No A button on left hand');
  76475. }
  76476. },
  76477. enumerable: true,
  76478. configurable: true
  76479. });
  76480. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  76481. /**
  76482. * Fired when the B button on this controller is modified
  76483. */
  76484. get: function () {
  76485. if (this.hand === 'right') {
  76486. return this.onSecondaryButtonStateChangedObservable;
  76487. }
  76488. else {
  76489. throw new Error('No B button on left hand');
  76490. }
  76491. },
  76492. enumerable: true,
  76493. configurable: true
  76494. });
  76495. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  76496. /**
  76497. * Fired when the X button on this controller is modified
  76498. */
  76499. get: function () {
  76500. if (this.hand === 'left') {
  76501. return this.onMainButtonStateChangedObservable;
  76502. }
  76503. else {
  76504. throw new Error('No X button on right hand');
  76505. }
  76506. },
  76507. enumerable: true,
  76508. configurable: true
  76509. });
  76510. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  76511. /**
  76512. * Fired when the Y button on this controller is modified
  76513. */
  76514. get: function () {
  76515. if (this.hand === 'left') {
  76516. return this.onSecondaryButtonStateChangedObservable;
  76517. }
  76518. else {
  76519. throw new Error('No Y button on right hand');
  76520. }
  76521. },
  76522. enumerable: true,
  76523. configurable: true
  76524. });
  76525. /**
  76526. * Called once for each button that changed state since the last frame
  76527. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  76528. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  76529. * 2) secondary trigger (same)
  76530. * 3) A (right) X (left), touch, pressed = value
  76531. * 4) B / Y
  76532. * 5) thumb rest
  76533. * @param buttonIdx Which button index changed
  76534. * @param state New state of the button
  76535. * @param changes Which properties on the state changed since last frame
  76536. */
  76537. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76538. var notifyObject = state; //{ state: state, changes: changes };
  76539. var triggerDirection = this.hand === 'right' ? -1 : 1;
  76540. switch (buttonIdx) {
  76541. case 0:
  76542. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76543. return;
  76544. case 1: // index trigger
  76545. if (this._defaultModel) {
  76546. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  76547. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  76548. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  76549. }
  76550. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76551. return;
  76552. case 2: // secondary trigger
  76553. if (this._defaultModel) {
  76554. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  76555. }
  76556. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  76557. return;
  76558. case 3:
  76559. if (this._defaultModel) {
  76560. if (notifyObject.pressed) {
  76561. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  76562. }
  76563. else {
  76564. (this._defaultModel.getChildren()[1]).position.y = 0;
  76565. }
  76566. }
  76567. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76568. return;
  76569. case 4:
  76570. if (this._defaultModel) {
  76571. if (notifyObject.pressed) {
  76572. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76573. }
  76574. else {
  76575. (this._defaultModel.getChildren()[2]).position.y = 0;
  76576. }
  76577. }
  76578. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76579. return;
  76580. case 5:
  76581. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  76582. return;
  76583. }
  76584. };
  76585. /**
  76586. * Base Url for the controller model.
  76587. */
  76588. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  76589. /**
  76590. * File name for the left controller model.
  76591. */
  76592. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  76593. /**
  76594. * File name for the right controller model.
  76595. */
  76596. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  76597. return OculusTouchController;
  76598. }(BABYLON.WebVRController));
  76599. BABYLON.OculusTouchController = OculusTouchController;
  76600. })(BABYLON || (BABYLON = {}));
  76601. //# sourceMappingURL=babylon.oculusTouchController.js.map
  76602. var BABYLON;
  76603. (function (BABYLON) {
  76604. /**
  76605. * Vive Controller
  76606. */
  76607. var ViveController = /** @class */ (function (_super) {
  76608. __extends(ViveController, _super);
  76609. /**
  76610. * Creates a new ViveController from a gamepad
  76611. * @param vrGamepad the gamepad that the controller should be created from
  76612. */
  76613. function ViveController(vrGamepad) {
  76614. var _this = _super.call(this, vrGamepad) || this;
  76615. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  76616. _this._invertLeftStickY = true;
  76617. return _this;
  76618. }
  76619. /**
  76620. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76621. * @param scene scene in which to add meshes
  76622. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76623. */
  76624. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76625. var _this = this;
  76626. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  76627. /*
  76628. Parent Mesh name: ViveWand
  76629. - body
  76630. - r_gripper
  76631. - l_gripper
  76632. - menu_button
  76633. - system_button
  76634. - trackpad
  76635. - trigger
  76636. - LED
  76637. */
  76638. _this._defaultModel = newMeshes[1];
  76639. _this.attachToMesh(_this._defaultModel);
  76640. if (meshLoaded) {
  76641. meshLoaded(_this._defaultModel);
  76642. }
  76643. });
  76644. };
  76645. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  76646. /**
  76647. * Fired when the left button on this controller is modified
  76648. */
  76649. get: function () {
  76650. return this.onMainButtonStateChangedObservable;
  76651. },
  76652. enumerable: true,
  76653. configurable: true
  76654. });
  76655. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  76656. /**
  76657. * Fired when the right button on this controller is modified
  76658. */
  76659. get: function () {
  76660. return this.onMainButtonStateChangedObservable;
  76661. },
  76662. enumerable: true,
  76663. configurable: true
  76664. });
  76665. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  76666. /**
  76667. * Fired when the menu button on this controller is modified
  76668. */
  76669. get: function () {
  76670. return this.onSecondaryButtonStateChangedObservable;
  76671. },
  76672. enumerable: true,
  76673. configurable: true
  76674. });
  76675. /**
  76676. * Called once for each button that changed state since the last frame
  76677. * Vive mapping:
  76678. * 0: touchpad
  76679. * 1: trigger
  76680. * 2: left AND right buttons
  76681. * 3: menu button
  76682. * @param buttonIdx Which button index changed
  76683. * @param state New state of the button
  76684. * @param changes Which properties on the state changed since last frame
  76685. */
  76686. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76687. var notifyObject = state; //{ state: state, changes: changes };
  76688. switch (buttonIdx) {
  76689. case 0:
  76690. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76691. return;
  76692. case 1: // index trigger
  76693. if (this._defaultModel) {
  76694. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  76695. }
  76696. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76697. return;
  76698. case 2: // left AND right button
  76699. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76700. return;
  76701. case 3:
  76702. if (this._defaultModel) {
  76703. if (notifyObject.pressed) {
  76704. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76705. }
  76706. else {
  76707. (this._defaultModel.getChildren()[2]).position.y = 0;
  76708. }
  76709. }
  76710. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76711. return;
  76712. }
  76713. };
  76714. /**
  76715. * Base Url for the controller model.
  76716. */
  76717. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  76718. /**
  76719. * File name for the controller model.
  76720. */
  76721. ViveController.MODEL_FILENAME = 'wand.babylon';
  76722. return ViveController;
  76723. }(BABYLON.WebVRController));
  76724. BABYLON.ViveController = ViveController;
  76725. })(BABYLON || (BABYLON = {}));
  76726. //# sourceMappingURL=babylon.viveController.js.map
  76727. var BABYLON;
  76728. (function (BABYLON) {
  76729. /**
  76730. * Generic Controller
  76731. */
  76732. var GenericController = /** @class */ (function (_super) {
  76733. __extends(GenericController, _super);
  76734. /**
  76735. * Creates a new GenericController from a gamepad
  76736. * @param vrGamepad the gamepad that the controller should be created from
  76737. */
  76738. function GenericController(vrGamepad) {
  76739. return _super.call(this, vrGamepad) || this;
  76740. }
  76741. /**
  76742. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76743. * @param scene scene in which to add meshes
  76744. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76745. */
  76746. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76747. var _this = this;
  76748. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  76749. _this._defaultModel = newMeshes[1];
  76750. _this.attachToMesh(_this._defaultModel);
  76751. if (meshLoaded) {
  76752. meshLoaded(_this._defaultModel);
  76753. }
  76754. });
  76755. };
  76756. /**
  76757. * Called once for each button that changed state since the last frame
  76758. * @param buttonIdx Which button index changed
  76759. * @param state New state of the button
  76760. * @param changes Which properties on the state changed since last frame
  76761. */
  76762. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76763. console.log("Button id: " + buttonIdx + "state: ");
  76764. console.dir(state);
  76765. };
  76766. /**
  76767. * Base Url for the controller model.
  76768. */
  76769. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76770. /**
  76771. * File name for the controller model.
  76772. */
  76773. GenericController.MODEL_FILENAME = 'generic.babylon';
  76774. return GenericController;
  76775. }(BABYLON.WebVRController));
  76776. BABYLON.GenericController = GenericController;
  76777. })(BABYLON || (BABYLON = {}));
  76778. //# sourceMappingURL=babylon.genericController.js.map
  76779. var BABYLON;
  76780. (function (BABYLON) {
  76781. /**
  76782. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  76783. */
  76784. var LoadedMeshInfo = /** @class */ (function () {
  76785. function LoadedMeshInfo() {
  76786. /**
  76787. * Map of the button meshes contained in the controller
  76788. */
  76789. this.buttonMeshes = {};
  76790. /**
  76791. * Map of the axis meshes contained in the controller
  76792. */
  76793. this.axisMeshes = {};
  76794. }
  76795. return LoadedMeshInfo;
  76796. }());
  76797. /**
  76798. * Defines the WindowsMotionController object that the state of the windows motion controller
  76799. */
  76800. var WindowsMotionController = /** @class */ (function (_super) {
  76801. __extends(WindowsMotionController, _super);
  76802. /**
  76803. * Creates a new WindowsMotionController from a gamepad
  76804. * @param vrGamepad the gamepad that the controller should be created from
  76805. */
  76806. function WindowsMotionController(vrGamepad) {
  76807. var _this = _super.call(this, vrGamepad) || this;
  76808. _this._mapping = {
  76809. // Semantic button names
  76810. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  76811. // A mapping of the button name to glTF model node name
  76812. // that should be transformed by button value.
  76813. buttonMeshNames: {
  76814. 'trigger': 'SELECT',
  76815. 'menu': 'MENU',
  76816. 'grip': 'GRASP',
  76817. 'thumbstick': 'THUMBSTICK_PRESS',
  76818. 'trackpad': 'TOUCHPAD_PRESS'
  76819. },
  76820. // This mapping is used to translate from the Motion Controller to Babylon semantics
  76821. buttonObservableNames: {
  76822. 'trigger': 'onTriggerStateChangedObservable',
  76823. 'menu': 'onSecondaryButtonStateChangedObservable',
  76824. 'grip': 'onMainButtonStateChangedObservable',
  76825. 'thumbstick': 'onPadStateChangedObservable',
  76826. 'trackpad': 'onTrackpadChangedObservable'
  76827. },
  76828. // A mapping of the axis name to glTF model node name
  76829. // that should be transformed by axis value.
  76830. // This array mirrors the browserGamepad.axes array, such that
  76831. // the mesh corresponding to axis 0 is in this array index 0.
  76832. axisMeshNames: [
  76833. 'THUMBSTICK_X',
  76834. 'THUMBSTICK_Y',
  76835. 'TOUCHPAD_TOUCH_X',
  76836. 'TOUCHPAD_TOUCH_Y'
  76837. ],
  76838. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  76839. };
  76840. /**
  76841. * Fired when the trackpad on this controller is clicked
  76842. */
  76843. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  76844. /**
  76845. * Fired when the trackpad on this controller is modified
  76846. */
  76847. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  76848. /**
  76849. * The current x and y values of this controller's trackpad
  76850. */
  76851. _this.trackpad = { x: 0, y: 0 };
  76852. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  76853. _this._loadedMeshInfo = null;
  76854. return _this;
  76855. }
  76856. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  76857. /**
  76858. * Fired when the trigger on this controller is modified
  76859. */
  76860. get: function () {
  76861. return this.onTriggerStateChangedObservable;
  76862. },
  76863. enumerable: true,
  76864. configurable: true
  76865. });
  76866. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  76867. /**
  76868. * Fired when the menu button on this controller is modified
  76869. */
  76870. get: function () {
  76871. return this.onSecondaryButtonStateChangedObservable;
  76872. },
  76873. enumerable: true,
  76874. configurable: true
  76875. });
  76876. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  76877. /**
  76878. * Fired when the grip button on this controller is modified
  76879. */
  76880. get: function () {
  76881. return this.onMainButtonStateChangedObservable;
  76882. },
  76883. enumerable: true,
  76884. configurable: true
  76885. });
  76886. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  76887. /**
  76888. * Fired when the thumbstick button on this controller is modified
  76889. */
  76890. get: function () {
  76891. return this.onPadStateChangedObservable;
  76892. },
  76893. enumerable: true,
  76894. configurable: true
  76895. });
  76896. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  76897. /**
  76898. * Fired when the touchpad button on this controller is modified
  76899. */
  76900. get: function () {
  76901. return this.onTrackpadChangedObservable;
  76902. },
  76903. enumerable: true,
  76904. configurable: true
  76905. });
  76906. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  76907. /**
  76908. * Fired when the touchpad values on this controller are modified
  76909. */
  76910. get: function () {
  76911. return this.onTrackpadValuesChangedObservable;
  76912. },
  76913. enumerable: true,
  76914. configurable: true
  76915. });
  76916. WindowsMotionController.prototype._updateTrackpad = function () {
  76917. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  76918. this.trackpad.x = this.browserGamepad["axes"][2];
  76919. this.trackpad.y = this.browserGamepad["axes"][3];
  76920. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  76921. }
  76922. };
  76923. /**
  76924. * Called once per frame by the engine.
  76925. */
  76926. WindowsMotionController.prototype.update = function () {
  76927. _super.prototype.update.call(this);
  76928. if (this.browserGamepad.axes) {
  76929. this._updateTrackpad();
  76930. // Only need to animate axes if there is a loaded mesh
  76931. if (this._loadedMeshInfo) {
  76932. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  76933. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  76934. }
  76935. }
  76936. }
  76937. };
  76938. /**
  76939. * Called once for each button that changed state since the last frame
  76940. * @param buttonIdx Which button index changed
  76941. * @param state New state of the button
  76942. * @param changes Which properties on the state changed since last frame
  76943. */
  76944. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76945. var buttonName = this._mapping.buttons[buttonIdx];
  76946. if (!buttonName) {
  76947. return;
  76948. }
  76949. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  76950. this._updateTrackpad();
  76951. // Only emit events for buttons that we know how to map from index to name
  76952. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  76953. if (observable) {
  76954. observable.notifyObservers(state);
  76955. }
  76956. this._lerpButtonTransform(buttonName, state.value);
  76957. };
  76958. /**
  76959. * Moves the buttons on the controller mesh based on their current state
  76960. * @param buttonName the name of the button to move
  76961. * @param buttonValue the value of the button which determines the buttons new position
  76962. */
  76963. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  76964. // If there is no loaded mesh, there is nothing to transform.
  76965. if (!this._loadedMeshInfo) {
  76966. return;
  76967. }
  76968. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  76969. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76970. return;
  76971. }
  76972. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  76973. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  76974. };
  76975. /**
  76976. * Moves the axis on the controller mesh based on its current state
  76977. * @param axis the index of the axis
  76978. * @param axisValue the value of the axis which determines the meshes new position
  76979. * @hidden
  76980. */
  76981. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  76982. if (!this._loadedMeshInfo) {
  76983. return;
  76984. }
  76985. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  76986. if (!meshInfo) {
  76987. return;
  76988. }
  76989. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76990. return;
  76991. }
  76992. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  76993. var lerpValue = axisValue * 0.5 + 0.5;
  76994. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  76995. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  76996. };
  76997. /**
  76998. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76999. * @param scene scene in which to add meshes
  77000. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77001. */
  77002. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  77003. var _this = this;
  77004. if (forceDefault === void 0) { forceDefault = false; }
  77005. var path;
  77006. var filename;
  77007. // Checking if GLB loader is present
  77008. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  77009. // Determine the device specific folder based on the ID suffix
  77010. var device = 'default';
  77011. if (this.id && !forceDefault) {
  77012. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  77013. device = ((match && match[0]) || device);
  77014. }
  77015. // Hand
  77016. if (this.hand === 'left') {
  77017. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  77018. }
  77019. else { // Right is the default if no hand is specified
  77020. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  77021. }
  77022. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  77023. }
  77024. else {
  77025. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  77026. path = BABYLON.GenericController.MODEL_BASE_URL;
  77027. filename = BABYLON.GenericController.MODEL_FILENAME;
  77028. }
  77029. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  77030. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  77031. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  77032. if (!_this._loadedMeshInfo) {
  77033. return;
  77034. }
  77035. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  77036. _this.attachToMesh(_this._defaultModel);
  77037. if (meshLoaded) {
  77038. meshLoaded(_this._defaultModel);
  77039. }
  77040. }, null, function (scene, message) {
  77041. BABYLON.Tools.Log(message);
  77042. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  77043. if (!forceDefault) {
  77044. _this.initControllerMesh(scene, meshLoaded, true);
  77045. }
  77046. });
  77047. };
  77048. /**
  77049. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  77050. * can be transformed by button presses and axes values, based on this._mapping.
  77051. *
  77052. * @param scene scene in which the meshes exist
  77053. * @param meshes list of meshes that make up the controller model to process
  77054. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  77055. */
  77056. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  77057. var loadedMeshInfo = null;
  77058. // Create a new mesh to contain the glTF hierarchy
  77059. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  77060. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  77061. var childMesh = null;
  77062. for (var i = 0; i < meshes.length; i++) {
  77063. var mesh = meshes[i];
  77064. if (!mesh.parent) {
  77065. // Exclude controller meshes from picking results
  77066. mesh.isPickable = false;
  77067. // Handle root node, attach to the new parentMesh
  77068. childMesh = mesh;
  77069. break;
  77070. }
  77071. }
  77072. if (childMesh) {
  77073. childMesh.setParent(parentMesh);
  77074. // Create our mesh info. Note that this method will always return non-null.
  77075. loadedMeshInfo = this.createMeshInfo(parentMesh);
  77076. }
  77077. else {
  77078. BABYLON.Tools.Warn('Could not find root node in model file.');
  77079. }
  77080. return loadedMeshInfo;
  77081. };
  77082. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  77083. var loadedMeshInfo = new LoadedMeshInfo();
  77084. var i;
  77085. loadedMeshInfo.rootNode = rootNode;
  77086. // Reset the caches
  77087. loadedMeshInfo.buttonMeshes = {};
  77088. loadedMeshInfo.axisMeshes = {};
  77089. // Button Meshes
  77090. for (i = 0; i < this._mapping.buttons.length; i++) {
  77091. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  77092. if (!buttonMeshName) {
  77093. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  77094. continue;
  77095. }
  77096. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  77097. if (!buttonMesh) {
  77098. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  77099. continue;
  77100. }
  77101. var buttonMeshInfo = {
  77102. index: i,
  77103. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  77104. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  77105. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  77106. };
  77107. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  77108. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  77109. }
  77110. else {
  77111. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  77112. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  77113. '(VALUE: ' + !!buttonMeshInfo.value +
  77114. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  77115. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  77116. ')');
  77117. }
  77118. }
  77119. // Axis Meshes
  77120. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  77121. var axisMeshName = this._mapping.axisMeshNames[i];
  77122. if (!axisMeshName) {
  77123. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  77124. continue;
  77125. }
  77126. var axisMesh = getChildByName(rootNode, axisMeshName);
  77127. if (!axisMesh) {
  77128. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  77129. continue;
  77130. }
  77131. var axisMeshInfo = {
  77132. index: i,
  77133. value: getImmediateChildByName(axisMesh, 'VALUE'),
  77134. min: getImmediateChildByName(axisMesh, 'MIN'),
  77135. max: getImmediateChildByName(axisMesh, 'MAX')
  77136. };
  77137. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  77138. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  77139. }
  77140. else {
  77141. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  77142. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  77143. '(VALUE: ' + !!axisMeshInfo.value +
  77144. ', MIN: ' + !!axisMeshInfo.min +
  77145. ', MAX:' + !!axisMeshInfo.max +
  77146. ')');
  77147. }
  77148. }
  77149. // Pointing Ray
  77150. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  77151. if (!loadedMeshInfo.pointingPoseNode) {
  77152. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  77153. }
  77154. else {
  77155. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  77156. }
  77157. return loadedMeshInfo;
  77158. // Look through all children recursively. This will return null if no mesh exists with the given name.
  77159. function getChildByName(node, name) {
  77160. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  77161. }
  77162. // Look through only immediate children. This will return null if no mesh exists with the given name.
  77163. function getImmediateChildByName(node, name) {
  77164. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  77165. }
  77166. };
  77167. /**
  77168. * Gets the ray of the controller in the direction the controller is pointing
  77169. * @param length the length the resulting ray should be
  77170. * @returns a ray in the direction the controller is pointing
  77171. */
  77172. WindowsMotionController.prototype.getForwardRay = function (length) {
  77173. if (length === void 0) { length = 100; }
  77174. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  77175. return _super.prototype.getForwardRay.call(this, length);
  77176. }
  77177. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  77178. var origin = m.getTranslation();
  77179. var forward = new BABYLON.Vector3(0, 0, -1);
  77180. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  77181. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  77182. return new BABYLON.Ray(origin, direction, length);
  77183. };
  77184. /**
  77185. * Disposes of the controller
  77186. */
  77187. WindowsMotionController.prototype.dispose = function () {
  77188. _super.prototype.dispose.call(this);
  77189. this.onTrackpadChangedObservable.clear();
  77190. };
  77191. /**
  77192. * The base url used to load the left and right controller models
  77193. */
  77194. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  77195. /**
  77196. * The name of the left controller model file
  77197. */
  77198. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  77199. /**
  77200. * The name of the right controller model file
  77201. */
  77202. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  77203. /**
  77204. * The controller name prefix for this controller type
  77205. */
  77206. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  77207. /**
  77208. * The controller id pattern for this controller type
  77209. */
  77210. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  77211. return WindowsMotionController;
  77212. }(BABYLON.WebVRController));
  77213. BABYLON.WindowsMotionController = WindowsMotionController;
  77214. })(BABYLON || (BABYLON = {}));
  77215. //# sourceMappingURL=babylon.windowsMotionController.js.map
  77216. var BABYLON;
  77217. (function (BABYLON) {
  77218. /**
  77219. * Gear VR Controller
  77220. */
  77221. var GearVRController = /** @class */ (function (_super) {
  77222. __extends(GearVRController, _super);
  77223. /**
  77224. * Creates a new GearVRController from a gamepad
  77225. * @param vrGamepad the gamepad that the controller should be created from
  77226. */
  77227. function GearVRController(vrGamepad) {
  77228. var _this = _super.call(this, vrGamepad) || this;
  77229. _this._maxRotationDistFromHeadset = Math.PI / 5;
  77230. _this._draggedRoomRotation = 0;
  77231. _this._tmpVector = new BABYLON.Vector3();
  77232. _this._buttonIndexToObservableNameMap = [
  77233. 'onTrackpadChangedObservable',
  77234. 'onTriggerStateChangedObservable' // Trigger
  77235. ];
  77236. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  77237. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  77238. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  77239. return _this;
  77240. }
  77241. /**
  77242. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  77243. * @param poseData raw pose fromthe device
  77244. */
  77245. GearVRController.prototype.updateFromDevice = function (poseData) {
  77246. _super.prototype.updateFromDevice.call(this, poseData);
  77247. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  77248. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  77249. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  77250. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  77251. // Find the radian distance away that the headset is from the controllers rotation
  77252. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  77253. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  77254. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  77255. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  77256. this._draggedRoomRotation += rotationAmount;
  77257. // Rotate controller around headset
  77258. var sin = Math.sin(-rotationAmount);
  77259. var cos = Math.cos(-rotationAmount);
  77260. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  77261. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  77262. }
  77263. }
  77264. }
  77265. };
  77266. /**
  77267. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77268. * @param scene scene in which to add meshes
  77269. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77270. */
  77271. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  77272. var _this = this;
  77273. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  77274. // Offset the controller so it will rotate around the users wrist
  77275. var mesh = new BABYLON.Mesh("", scene);
  77276. newMeshes[1].parent = mesh;
  77277. newMeshes[1].position.z = -0.15;
  77278. _this._defaultModel = mesh;
  77279. _this.attachToMesh(_this._defaultModel);
  77280. if (meshLoaded) {
  77281. meshLoaded(_this._defaultModel);
  77282. }
  77283. });
  77284. };
  77285. /**
  77286. * Called once for each button that changed state since the last frame
  77287. * @param buttonIdx Which button index changed
  77288. * @param state New state of the button
  77289. * @param changes Which properties on the state changed since last frame
  77290. */
  77291. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  77292. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  77293. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  77294. // Only emit events for buttons that we know how to map from index to observable
  77295. var observable = this[observableName];
  77296. if (observable) {
  77297. observable.notifyObservers(state);
  77298. }
  77299. }
  77300. };
  77301. /**
  77302. * Base Url for the controller model.
  77303. */
  77304. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  77305. /**
  77306. * File name for the controller model.
  77307. */
  77308. GearVRController.MODEL_FILENAME = 'generic.babylon';
  77309. /**
  77310. * Gamepad Id prefix used to identify this controller.
  77311. */
  77312. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  77313. return GearVRController;
  77314. }(BABYLON.WebVRController));
  77315. BABYLON.GearVRController = GearVRController;
  77316. })(BABYLON || (BABYLON = {}));
  77317. //# sourceMappingURL=babylon.gearVRController.js.map
  77318. var BABYLON;
  77319. (function (BABYLON) {
  77320. /**
  77321. * Google Daydream controller
  77322. */
  77323. var DaydreamController = /** @class */ (function (_super) {
  77324. __extends(DaydreamController, _super);
  77325. /**
  77326. * Creates a new DaydreamController from a gamepad
  77327. * @param vrGamepad the gamepad that the controller should be created from
  77328. */
  77329. function DaydreamController(vrGamepad) {
  77330. var _this = _super.call(this, vrGamepad) || this;
  77331. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  77332. return _this;
  77333. }
  77334. /**
  77335. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77336. * @param scene scene in which to add meshes
  77337. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77338. */
  77339. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  77340. var _this = this;
  77341. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  77342. _this._defaultModel = newMeshes[1];
  77343. _this.attachToMesh(_this._defaultModel);
  77344. if (meshLoaded) {
  77345. meshLoaded(_this._defaultModel);
  77346. }
  77347. });
  77348. };
  77349. /**
  77350. * Called once for each button that changed state since the last frame
  77351. * @param buttonIdx Which button index changed
  77352. * @param state New state of the button
  77353. * @param changes Which properties on the state changed since last frame
  77354. */
  77355. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  77356. // Daydream controller only has 1 GamepadButton (on the trackpad).
  77357. if (buttonIdx === 0) {
  77358. var observable = this.onTriggerStateChangedObservable;
  77359. if (observable) {
  77360. observable.notifyObservers(state);
  77361. }
  77362. }
  77363. else {
  77364. // If the app or home buttons are ever made available
  77365. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  77366. }
  77367. };
  77368. /**
  77369. * Base Url for the controller model.
  77370. */
  77371. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  77372. /**
  77373. * File name for the controller model.
  77374. */
  77375. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  77376. /**
  77377. * Gamepad Id prefix used to identify Daydream Controller.
  77378. */
  77379. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  77380. return DaydreamController;
  77381. }(BABYLON.WebVRController));
  77382. BABYLON.DaydreamController = DaydreamController;
  77383. })(BABYLON || (BABYLON = {}));
  77384. //# sourceMappingURL=babylon.daydreamController.js.map
  77385. var BABYLON;
  77386. (function (BABYLON) {
  77387. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  77388. get: function () {
  77389. if (!this._gamepadManager) {
  77390. this._gamepadManager = new BABYLON.GamepadManager(this);
  77391. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  77392. if (!component) {
  77393. component = new GamepadSystemSceneComponent(this);
  77394. this._addComponent(component);
  77395. }
  77396. }
  77397. return this._gamepadManager;
  77398. },
  77399. enumerable: true,
  77400. configurable: true
  77401. });
  77402. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  77403. this.add(new BABYLON.FreeCameraGamepadInput());
  77404. return this;
  77405. };
  77406. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  77407. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  77408. return this;
  77409. };
  77410. /**
  77411. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  77412. */
  77413. var GamepadSystemSceneComponent = /** @class */ (function () {
  77414. /**
  77415. * Creates a new instance of the component for the given scene
  77416. * @param scene Defines the scene to register the component in
  77417. */
  77418. function GamepadSystemSceneComponent(scene) {
  77419. /**
  77420. * The component name helpfull to identify the component in the list of scene components.
  77421. */
  77422. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  77423. this.scene = scene;
  77424. }
  77425. /**
  77426. * Registers the component in a given scene
  77427. */
  77428. GamepadSystemSceneComponent.prototype.register = function () {
  77429. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  77430. };
  77431. /**
  77432. * Rebuilds the elements related to this component in case of
  77433. * context lost for instance.
  77434. */
  77435. GamepadSystemSceneComponent.prototype.rebuild = function () {
  77436. // Nothing to do for gamepads
  77437. };
  77438. /**
  77439. * Disposes the component and the associated ressources
  77440. */
  77441. GamepadSystemSceneComponent.prototype.dispose = function () {
  77442. var gamepadManager = this.scene._gamepadManager;
  77443. if (gamepadManager) {
  77444. gamepadManager.dispose();
  77445. this.scene._gamepadManager = null;
  77446. }
  77447. };
  77448. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  77449. var gamepadManager = this.scene._gamepadManager;
  77450. if (gamepadManager && gamepadManager._isMonitoring) {
  77451. gamepadManager._checkGamepadsStatus();
  77452. }
  77453. };
  77454. return GamepadSystemSceneComponent;
  77455. }());
  77456. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  77457. })(BABYLON || (BABYLON = {}));
  77458. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  77459. var BABYLON;
  77460. (function (BABYLON) {
  77461. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  77462. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  77463. });
  77464. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  77465. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  77466. });
  77467. var FollowCamera = /** @class */ (function (_super) {
  77468. __extends(FollowCamera, _super);
  77469. function FollowCamera(name, position, scene, lockedTarget) {
  77470. if (lockedTarget === void 0) { lockedTarget = null; }
  77471. var _this = _super.call(this, name, position, scene) || this;
  77472. _this.radius = 12;
  77473. _this.rotationOffset = 0;
  77474. _this.heightOffset = 4;
  77475. _this.cameraAcceleration = 0.05;
  77476. _this.maxCameraSpeed = 20;
  77477. _this.lockedTarget = lockedTarget;
  77478. return _this;
  77479. }
  77480. FollowCamera.prototype.getRadians = function (degrees) {
  77481. return degrees * Math.PI / 180;
  77482. };
  77483. FollowCamera.prototype.follow = function (cameraTarget) {
  77484. if (!cameraTarget)
  77485. return;
  77486. var yRotation;
  77487. if (cameraTarget.rotationQuaternion) {
  77488. var rotMatrix = new BABYLON.Matrix();
  77489. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  77490. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  77491. }
  77492. else {
  77493. yRotation = cameraTarget.rotation.y;
  77494. }
  77495. var radians = this.getRadians(this.rotationOffset) + yRotation;
  77496. var targetPosition = cameraTarget.getAbsolutePosition();
  77497. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  77498. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  77499. var dx = targetX - this.position.x;
  77500. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  77501. var dz = (targetZ) - this.position.z;
  77502. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  77503. var vy = dy * this.cameraAcceleration;
  77504. var vz = dz * this.cameraAcceleration * 2;
  77505. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  77506. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77507. }
  77508. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  77509. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77510. }
  77511. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  77512. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77513. }
  77514. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  77515. this.setTarget(targetPosition);
  77516. };
  77517. /** @hidden */
  77518. FollowCamera.prototype._checkInputs = function () {
  77519. _super.prototype._checkInputs.call(this);
  77520. if (this.lockedTarget) {
  77521. this.follow(this.lockedTarget);
  77522. }
  77523. };
  77524. FollowCamera.prototype.getClassName = function () {
  77525. return "FollowCamera";
  77526. };
  77527. __decorate([
  77528. BABYLON.serialize()
  77529. ], FollowCamera.prototype, "radius", void 0);
  77530. __decorate([
  77531. BABYLON.serialize()
  77532. ], FollowCamera.prototype, "rotationOffset", void 0);
  77533. __decorate([
  77534. BABYLON.serialize()
  77535. ], FollowCamera.prototype, "heightOffset", void 0);
  77536. __decorate([
  77537. BABYLON.serialize()
  77538. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  77539. __decorate([
  77540. BABYLON.serialize()
  77541. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  77542. __decorate([
  77543. BABYLON.serializeAsMeshReference("lockedTargetId")
  77544. ], FollowCamera.prototype, "lockedTarget", void 0);
  77545. return FollowCamera;
  77546. }(BABYLON.TargetCamera));
  77547. BABYLON.FollowCamera = FollowCamera;
  77548. /**
  77549. * Arc Rotate version of the follow camera.
  77550. * It still follows a defined mesh but in an Arc Rotate Camera fashion.
  77551. */
  77552. var ArcFollowCamera = /** @class */ (function (_super) {
  77553. __extends(ArcFollowCamera, _super);
  77554. /**
  77555. * Instantiates a new ArcFollowCamera
  77556. * @param name Defines the name of the camera
  77557. * @param alpha Defines the rotation angle of the camera around the logitudinal axis
  77558. * @param beta Defines the rotation angle of the camera around the elevation axis
  77559. * @param radius Defines the radius of the camera from its target point
  77560. * @param target Defines the target of the camera
  77561. * @param scene Defines the scene the camera belongs to
  77562. */
  77563. function ArcFollowCamera(name,
  77564. /** The longitudinal angle of the camera */
  77565. alpha,
  77566. /** The latitudinal angle of the camera */
  77567. beta,
  77568. /** The radius of the camera from its target */
  77569. radius,
  77570. /** Defines the camera target (the messh it should follow) */
  77571. target, scene) {
  77572. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  77573. _this.alpha = alpha;
  77574. _this.beta = beta;
  77575. _this.radius = radius;
  77576. _this.target = target;
  77577. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  77578. _this.follow();
  77579. return _this;
  77580. }
  77581. ArcFollowCamera.prototype.follow = function () {
  77582. if (!this.target) {
  77583. return;
  77584. }
  77585. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  77586. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  77587. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  77588. var targetPosition = this.target.getAbsolutePosition();
  77589. this.position = targetPosition.add(this._cartesianCoordinates);
  77590. this.setTarget(targetPosition);
  77591. };
  77592. /** @hidden */
  77593. ArcFollowCamera.prototype._checkInputs = function () {
  77594. _super.prototype._checkInputs.call(this);
  77595. this.follow();
  77596. };
  77597. /**
  77598. * Returns the class name of the object.
  77599. * It is mostly used internally for serialization purposes.
  77600. */
  77601. ArcFollowCamera.prototype.getClassName = function () {
  77602. return "ArcFollowCamera";
  77603. };
  77604. return ArcFollowCamera;
  77605. }(BABYLON.TargetCamera));
  77606. BABYLON.ArcFollowCamera = ArcFollowCamera;
  77607. })(BABYLON || (BABYLON = {}));
  77608. //# sourceMappingURL=babylon.followCamera.js.map
  77609. var BABYLON;
  77610. (function (BABYLON) {
  77611. // We're mainly based on the logic defined into the FreeCamera code
  77612. var UniversalCamera = /** @class */ (function (_super) {
  77613. __extends(UniversalCamera, _super);
  77614. //-- end properties for backward compatibility for inputs
  77615. function UniversalCamera(name, position, scene) {
  77616. var _this = _super.call(this, name, position, scene) || this;
  77617. _this.inputs.addGamepad();
  77618. return _this;
  77619. }
  77620. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  77621. //-- Begin properties for backward compatibility for inputs
  77622. get: function () {
  77623. var gamepad = this.inputs.attached["gamepad"];
  77624. if (gamepad)
  77625. return gamepad.gamepadAngularSensibility;
  77626. return 0;
  77627. },
  77628. set: function (value) {
  77629. var gamepad = this.inputs.attached["gamepad"];
  77630. if (gamepad)
  77631. gamepad.gamepadAngularSensibility = value;
  77632. },
  77633. enumerable: true,
  77634. configurable: true
  77635. });
  77636. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  77637. get: function () {
  77638. var gamepad = this.inputs.attached["gamepad"];
  77639. if (gamepad)
  77640. return gamepad.gamepadMoveSensibility;
  77641. return 0;
  77642. },
  77643. set: function (value) {
  77644. var gamepad = this.inputs.attached["gamepad"];
  77645. if (gamepad)
  77646. gamepad.gamepadMoveSensibility = value;
  77647. },
  77648. enumerable: true,
  77649. configurable: true
  77650. });
  77651. UniversalCamera.prototype.getClassName = function () {
  77652. return "UniversalCamera";
  77653. };
  77654. return UniversalCamera;
  77655. }(BABYLON.TouchCamera));
  77656. BABYLON.UniversalCamera = UniversalCamera;
  77657. })(BABYLON || (BABYLON = {}));
  77658. //# sourceMappingURL=babylon.universalCamera.js.map
  77659. var BABYLON;
  77660. (function (BABYLON) {
  77661. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  77662. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  77663. });
  77664. // We're mainly based on the logic defined into the FreeCamera code
  77665. var GamepadCamera = /** @class */ (function (_super) {
  77666. __extends(GamepadCamera, _super);
  77667. //-- end properties for backward compatibility for inputs
  77668. function GamepadCamera(name, position, scene) {
  77669. return _super.call(this, name, position, scene) || this;
  77670. }
  77671. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  77672. //-- Begin properties for backward compatibility for inputs
  77673. get: function () {
  77674. var gamepad = this.inputs.attached["gamepad"];
  77675. if (gamepad)
  77676. return gamepad.gamepadAngularSensibility;
  77677. return 0;
  77678. },
  77679. set: function (value) {
  77680. var gamepad = this.inputs.attached["gamepad"];
  77681. if (gamepad)
  77682. gamepad.gamepadAngularSensibility = value;
  77683. },
  77684. enumerable: true,
  77685. configurable: true
  77686. });
  77687. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  77688. get: function () {
  77689. var gamepad = this.inputs.attached["gamepad"];
  77690. if (gamepad)
  77691. return gamepad.gamepadMoveSensibility;
  77692. return 0;
  77693. },
  77694. set: function (value) {
  77695. var gamepad = this.inputs.attached["gamepad"];
  77696. if (gamepad)
  77697. gamepad.gamepadMoveSensibility = value;
  77698. },
  77699. enumerable: true,
  77700. configurable: true
  77701. });
  77702. GamepadCamera.prototype.getClassName = function () {
  77703. return "GamepadCamera";
  77704. };
  77705. return GamepadCamera;
  77706. }(BABYLON.UniversalCamera));
  77707. BABYLON.GamepadCamera = GamepadCamera;
  77708. })(BABYLON || (BABYLON = {}));
  77709. //# sourceMappingURL=babylon.gamepadCamera.js.map
  77710. var BABYLON;
  77711. (function (BABYLON) {
  77712. var PostProcessRenderPipelineManager = /** @class */ (function () {
  77713. function PostProcessRenderPipelineManager() {
  77714. this._renderPipelines = {};
  77715. }
  77716. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  77717. this._renderPipelines[renderPipeline._name] = renderPipeline;
  77718. };
  77719. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  77720. if (unique === void 0) { unique = false; }
  77721. var renderPipeline = this._renderPipelines[renderPipelineName];
  77722. if (!renderPipeline) {
  77723. return;
  77724. }
  77725. renderPipeline._attachCameras(cameras, unique);
  77726. };
  77727. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  77728. var renderPipeline = this._renderPipelines[renderPipelineName];
  77729. if (!renderPipeline) {
  77730. return;
  77731. }
  77732. renderPipeline._detachCameras(cameras);
  77733. };
  77734. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77735. var renderPipeline = this._renderPipelines[renderPipelineName];
  77736. if (!renderPipeline) {
  77737. return;
  77738. }
  77739. renderPipeline._enableEffect(renderEffectName, cameras);
  77740. };
  77741. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77742. var renderPipeline = this._renderPipelines[renderPipelineName];
  77743. if (!renderPipeline) {
  77744. return;
  77745. }
  77746. renderPipeline._disableEffect(renderEffectName, cameras);
  77747. };
  77748. PostProcessRenderPipelineManager.prototype.update = function () {
  77749. for (var renderPipelineName in this._renderPipelines) {
  77750. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77751. var pipeline = this._renderPipelines[renderPipelineName];
  77752. if (!pipeline.isSupported) {
  77753. pipeline.dispose();
  77754. delete this._renderPipelines[renderPipelineName];
  77755. }
  77756. else {
  77757. pipeline._update();
  77758. }
  77759. }
  77760. }
  77761. };
  77762. /** @hidden */
  77763. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  77764. for (var renderPipelineName in this._renderPipelines) {
  77765. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77766. var pipeline = this._renderPipelines[renderPipelineName];
  77767. pipeline._rebuild();
  77768. }
  77769. }
  77770. };
  77771. PostProcessRenderPipelineManager.prototype.dispose = function () {
  77772. for (var renderPipelineName in this._renderPipelines) {
  77773. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77774. var pipeline = this._renderPipelines[renderPipelineName];
  77775. pipeline.dispose();
  77776. }
  77777. }
  77778. };
  77779. return PostProcessRenderPipelineManager;
  77780. }());
  77781. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  77782. })(BABYLON || (BABYLON = {}));
  77783. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  77784. var BABYLON;
  77785. (function (BABYLON) {
  77786. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  77787. get: function () {
  77788. if (!this._postProcessRenderPipelineManager) {
  77789. // Register the G Buffer component to the scene.
  77790. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  77791. if (!component) {
  77792. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  77793. this._addComponent(component);
  77794. }
  77795. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  77796. }
  77797. return this._postProcessRenderPipelineManager;
  77798. },
  77799. enumerable: true,
  77800. configurable: true
  77801. });
  77802. /**
  77803. * Defines the Render Pipeline scene component responsible to rendering pipelines
  77804. */
  77805. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  77806. /**
  77807. * Creates a new instance of the component for the given scene
  77808. * @param scene Defines the scene to register the component in
  77809. */
  77810. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  77811. /**
  77812. * The component name helpfull to identify the component in the list of scene components.
  77813. */
  77814. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  77815. this.scene = scene;
  77816. }
  77817. /**
  77818. * Registers the component in a given scene
  77819. */
  77820. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  77821. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  77822. };
  77823. /**
  77824. * Rebuilds the elements related to this component in case of
  77825. * context lost for instance.
  77826. */
  77827. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  77828. if (this.scene._postProcessRenderPipelineManager) {
  77829. this.scene._postProcessRenderPipelineManager._rebuild();
  77830. }
  77831. };
  77832. /**
  77833. * Disposes the component and the associated ressources
  77834. */
  77835. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  77836. if (this.scene._postProcessRenderPipelineManager) {
  77837. this.scene._postProcessRenderPipelineManager.dispose();
  77838. }
  77839. };
  77840. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77841. if (this.scene._postProcessRenderPipelineManager) {
  77842. this.scene._postProcessRenderPipelineManager.update();
  77843. }
  77844. };
  77845. return PostProcessRenderPipelineManagerSceneComponent;
  77846. }());
  77847. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  77848. })(BABYLON || (BABYLON = {}));
  77849. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  77850. var BABYLON;
  77851. (function (BABYLON) {
  77852. /**
  77853. * This represents a set of one or more post processes in Babylon.
  77854. * A post process can be used to apply a shader to a texture after it is rendered.
  77855. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  77856. */
  77857. var PostProcessRenderEffect = /** @class */ (function () {
  77858. /**
  77859. * Instantiates a post process render effect.
  77860. * A post process can be used to apply a shader to a texture after it is rendered.
  77861. * @param engine The engine the effect is tied to
  77862. * @param name The name of the effect
  77863. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  77864. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  77865. */
  77866. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  77867. this._name = name;
  77868. this._singleInstance = singleInstance || true;
  77869. this._getPostProcesses = getPostProcesses;
  77870. this._cameras = {};
  77871. this._indicesForCamera = {};
  77872. this._postProcesses = {};
  77873. }
  77874. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  77875. /**
  77876. * Checks if all the post processes in the effect are supported.
  77877. */
  77878. get: function () {
  77879. for (var index in this._postProcesses) {
  77880. if (this._postProcesses.hasOwnProperty(index)) {
  77881. var pps = this._postProcesses[index];
  77882. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  77883. if (!pps[ppIndex].isSupported) {
  77884. return false;
  77885. }
  77886. }
  77887. }
  77888. }
  77889. return true;
  77890. },
  77891. enumerable: true,
  77892. configurable: true
  77893. });
  77894. /**
  77895. * Updates the current state of the effect
  77896. * @hidden
  77897. */
  77898. PostProcessRenderEffect.prototype._update = function () {
  77899. };
  77900. /**
  77901. * Attaches the effect on cameras
  77902. * @param cameras The camera to attach to.
  77903. * @hidden
  77904. */
  77905. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  77906. var _this = this;
  77907. var cameraKey;
  77908. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77909. if (!cams) {
  77910. return;
  77911. }
  77912. for (var i = 0; i < cams.length; i++) {
  77913. var camera = cams[i];
  77914. var cameraName = camera.name;
  77915. if (this._singleInstance) {
  77916. cameraKey = 0;
  77917. }
  77918. else {
  77919. cameraKey = cameraName;
  77920. }
  77921. if (!this._postProcesses[cameraKey]) {
  77922. var postProcess = this._getPostProcesses();
  77923. if (postProcess) {
  77924. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  77925. }
  77926. }
  77927. if (!this._indicesForCamera[cameraName]) {
  77928. this._indicesForCamera[cameraName] = [];
  77929. }
  77930. this._postProcesses[cameraKey].forEach(function (postProcess) {
  77931. var index = camera.attachPostProcess(postProcess);
  77932. _this._indicesForCamera[cameraName].push(index);
  77933. });
  77934. if (!this._cameras[cameraName]) {
  77935. this._cameras[cameraName] = camera;
  77936. }
  77937. }
  77938. };
  77939. /**
  77940. * Detatches the effect on cameras
  77941. * @param cameras The camera to detatch from.
  77942. * @hidden
  77943. */
  77944. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  77945. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77946. if (!cams) {
  77947. return;
  77948. }
  77949. for (var i = 0; i < cams.length; i++) {
  77950. var camera = cams[i];
  77951. var cameraName = camera.name;
  77952. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77953. camera.detachPostProcess(postProcess);
  77954. });
  77955. if (this._cameras[cameraName]) {
  77956. //this._indicesForCamera.splice(index, 1);
  77957. this._cameras[cameraName] = null;
  77958. }
  77959. }
  77960. };
  77961. /**
  77962. * Enables the effect on given cameras
  77963. * @param cameras The camera to enable.
  77964. * @hidden
  77965. */
  77966. PostProcessRenderEffect.prototype._enable = function (cameras) {
  77967. var _this = this;
  77968. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77969. if (!cams) {
  77970. return;
  77971. }
  77972. for (var i = 0; i < cams.length; i++) {
  77973. var camera = cams[i];
  77974. var cameraName = camera.name;
  77975. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  77976. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  77977. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77978. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  77979. });
  77980. }
  77981. }
  77982. }
  77983. };
  77984. /**
  77985. * Disables the effect on the given cameras
  77986. * @param cameras The camera to disable.
  77987. * @hidden
  77988. */
  77989. PostProcessRenderEffect.prototype._disable = function (cameras) {
  77990. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77991. if (!cams) {
  77992. return;
  77993. }
  77994. for (var i = 0; i < cams.length; i++) {
  77995. var camera = cams[i];
  77996. var cameraName = camera.name;
  77997. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77998. camera.detachPostProcess(postProcess);
  77999. });
  78000. }
  78001. };
  78002. /**
  78003. * Gets a list of the post processes contained in the effect.
  78004. * @param camera The camera to get the post processes on.
  78005. * @returns The list of the post processes in the effect.
  78006. */
  78007. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  78008. if (this._singleInstance) {
  78009. return this._postProcesses[0];
  78010. }
  78011. else {
  78012. if (!camera) {
  78013. return null;
  78014. }
  78015. return this._postProcesses[camera.name];
  78016. }
  78017. };
  78018. return PostProcessRenderEffect;
  78019. }());
  78020. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  78021. })(BABYLON || (BABYLON = {}));
  78022. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  78023. var BABYLON;
  78024. (function (BABYLON) {
  78025. var PostProcessRenderPipeline = /** @class */ (function () {
  78026. function PostProcessRenderPipeline(engine, name) {
  78027. this.engine = engine;
  78028. this._name = name;
  78029. this._renderEffects = {};
  78030. this._renderEffectsForIsolatedPass = new Array();
  78031. this._cameras = [];
  78032. }
  78033. PostProcessRenderPipeline.prototype.getClassName = function () {
  78034. return "PostProcessRenderPipeline";
  78035. };
  78036. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  78037. get: function () {
  78038. for (var renderEffectName in this._renderEffects) {
  78039. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  78040. if (!this._renderEffects[renderEffectName].isSupported) {
  78041. return false;
  78042. }
  78043. }
  78044. }
  78045. return true;
  78046. },
  78047. enumerable: true,
  78048. configurable: true
  78049. });
  78050. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  78051. this._renderEffects[renderEffect._name] = renderEffect;
  78052. };
  78053. // private
  78054. /** @hidden */
  78055. PostProcessRenderPipeline.prototype._rebuild = function () {
  78056. };
  78057. /** @hidden */
  78058. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  78059. var renderEffects = this._renderEffects[renderEffectName];
  78060. if (!renderEffects) {
  78061. return;
  78062. }
  78063. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  78064. };
  78065. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  78066. var renderEffects = this._renderEffects[renderEffectName];
  78067. if (!renderEffects) {
  78068. return;
  78069. }
  78070. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  78071. };
  78072. /** @hidden */
  78073. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  78074. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  78075. if (!cams) {
  78076. return;
  78077. }
  78078. var indicesToDelete = [];
  78079. var i;
  78080. for (i = 0; i < cams.length; i++) {
  78081. var camera = cams[i];
  78082. var cameraName = camera.name;
  78083. if (this._cameras.indexOf(camera) === -1) {
  78084. this._cameras[cameraName] = camera;
  78085. }
  78086. else if (unique) {
  78087. indicesToDelete.push(i);
  78088. }
  78089. }
  78090. for (i = 0; i < indicesToDelete.length; i++) {
  78091. cameras.splice(indicesToDelete[i], 1);
  78092. }
  78093. for (var renderEffectName in this._renderEffects) {
  78094. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  78095. this._renderEffects[renderEffectName]._attachCameras(cams);
  78096. }
  78097. }
  78098. };
  78099. /** @hidden */
  78100. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  78101. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  78102. if (!cams) {
  78103. return;
  78104. }
  78105. for (var renderEffectName in this._renderEffects) {
  78106. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  78107. this._renderEffects[renderEffectName]._detachCameras(cams);
  78108. }
  78109. }
  78110. for (var i = 0; i < cams.length; i++) {
  78111. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  78112. }
  78113. };
  78114. /** @hidden */
  78115. PostProcessRenderPipeline.prototype._update = function () {
  78116. for (var renderEffectName in this._renderEffects) {
  78117. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  78118. this._renderEffects[renderEffectName]._update();
  78119. }
  78120. }
  78121. for (var i = 0; i < this._cameras.length; i++) {
  78122. var cameraName = this._cameras[i].name;
  78123. if (this._renderEffectsForIsolatedPass[cameraName]) {
  78124. this._renderEffectsForIsolatedPass[cameraName]._update();
  78125. }
  78126. }
  78127. };
  78128. /** @hidden */
  78129. PostProcessRenderPipeline.prototype._reset = function () {
  78130. this._renderEffects = {};
  78131. this._renderEffectsForIsolatedPass = new Array();
  78132. };
  78133. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  78134. // 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)
  78135. var effectKeys = Object.keys(this._renderEffects);
  78136. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  78137. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  78138. if (postProcesses) {
  78139. postProcesses[0].samples = sampleCount;
  78140. return true;
  78141. }
  78142. }
  78143. return false;
  78144. };
  78145. PostProcessRenderPipeline.prototype.dispose = function () {
  78146. // Must be implemented by children
  78147. };
  78148. __decorate([
  78149. BABYLON.serialize()
  78150. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  78151. return PostProcessRenderPipeline;
  78152. }());
  78153. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  78154. })(BABYLON || (BABYLON = {}));
  78155. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  78156. var BABYLON;
  78157. (function (BABYLON) {
  78158. /**
  78159. * This represents a depth renderer in Babylon.
  78160. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  78161. */
  78162. var DepthRenderer = /** @class */ (function () {
  78163. /**
  78164. * Instantiates a depth renderer
  78165. * @param scene The scene the renderer belongs to
  78166. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  78167. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  78168. */
  78169. function DepthRenderer(scene, type, camera) {
  78170. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  78171. if (camera === void 0) { camera = null; }
  78172. var _this = this;
  78173. /**
  78174. * Specifiess that the depth renderer will only be used within
  78175. * the camera it is created for.
  78176. * This can help forcing its rendering during the camera processing.
  78177. */
  78178. this.useOnlyInActiveCamera = false;
  78179. this._scene = scene;
  78180. // Register the G Buffer component to the scene.
  78181. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  78182. if (!component) {
  78183. component = new BABYLON.DepthRendererSceneComponent(scene);
  78184. scene._addComponent(component);
  78185. }
  78186. this._camera = camera;
  78187. var engine = scene.getEngine();
  78188. // Render target
  78189. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  78190. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78191. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78192. this._depthMap.refreshRate = 1;
  78193. this._depthMap.renderParticles = false;
  78194. this._depthMap.renderList = null;
  78195. // Camera to get depth map from to support multiple concurrent cameras
  78196. this._depthMap.activeCamera = this._camera;
  78197. this._depthMap.ignoreCameraViewport = true;
  78198. this._depthMap.useCameraPostProcesses = false;
  78199. // set default depth value to 1.0 (far away)
  78200. this._depthMap.onClearObservable.add(function (engine) {
  78201. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  78202. });
  78203. // Custom render function
  78204. var renderSubMesh = function (subMesh) {
  78205. var mesh = subMesh.getRenderingMesh();
  78206. var scene = _this._scene;
  78207. var engine = scene.getEngine();
  78208. var material = subMesh.getMaterial();
  78209. if (!material) {
  78210. return;
  78211. }
  78212. // Culling and reverse (right handed system)
  78213. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78214. // Managing instances
  78215. var batch = mesh._getInstancesRenderList(subMesh._id);
  78216. if (batch.mustReturn) {
  78217. return;
  78218. }
  78219. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78220. var camera = _this._camera || scene.activeCamera;
  78221. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  78222. engine.enableEffect(_this._effect);
  78223. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78224. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78225. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  78226. // Alpha test
  78227. if (material && material.needAlphaTesting()) {
  78228. var alphaTexture = material.getAlphaTestTexture();
  78229. if (alphaTexture) {
  78230. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78231. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78232. }
  78233. }
  78234. // Bones
  78235. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78236. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78237. }
  78238. // Draw
  78239. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78240. }
  78241. };
  78242. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78243. var index;
  78244. if (depthOnlySubMeshes.length) {
  78245. engine.setColorWrite(false);
  78246. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78247. renderSubMesh(depthOnlySubMeshes.data[index]);
  78248. }
  78249. engine.setColorWrite(true);
  78250. }
  78251. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78252. renderSubMesh(opaqueSubMeshes.data[index]);
  78253. }
  78254. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78255. renderSubMesh(alphaTestSubMeshes.data[index]);
  78256. }
  78257. };
  78258. }
  78259. /**
  78260. * Creates the depth rendering effect and checks if the effect is ready.
  78261. * @param subMesh The submesh to be used to render the depth map of
  78262. * @param useInstances If multiple world instances should be used
  78263. * @returns if the depth renderer is ready to render the depth map
  78264. */
  78265. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  78266. var material = subMesh.getMaterial();
  78267. if (material.disableDepthWrite) {
  78268. return false;
  78269. }
  78270. var defines = [];
  78271. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78272. var mesh = subMesh.getMesh();
  78273. // Alpha test
  78274. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  78275. defines.push("#define ALPHATEST");
  78276. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78277. attribs.push(BABYLON.VertexBuffer.UVKind);
  78278. defines.push("#define UV1");
  78279. }
  78280. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78281. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78282. defines.push("#define UV2");
  78283. }
  78284. }
  78285. // Bones
  78286. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78287. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78288. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78289. if (mesh.numBoneInfluencers > 4) {
  78290. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78291. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78292. }
  78293. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78294. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78295. }
  78296. else {
  78297. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78298. }
  78299. // Instances
  78300. if (useInstances) {
  78301. defines.push("#define INSTANCES");
  78302. attribs.push("world0");
  78303. attribs.push("world1");
  78304. attribs.push("world2");
  78305. attribs.push("world3");
  78306. }
  78307. // Get correct effect
  78308. var join = defines.join("\n");
  78309. if (this._cachedDefines !== join) {
  78310. this._cachedDefines = join;
  78311. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  78312. }
  78313. return this._effect.isReady();
  78314. };
  78315. /**
  78316. * Gets the texture which the depth map will be written to.
  78317. * @returns The depth map texture
  78318. */
  78319. DepthRenderer.prototype.getDepthMap = function () {
  78320. return this._depthMap;
  78321. };
  78322. /**
  78323. * Disposes of the depth renderer.
  78324. */
  78325. DepthRenderer.prototype.dispose = function () {
  78326. this._depthMap.dispose();
  78327. };
  78328. return DepthRenderer;
  78329. }());
  78330. BABYLON.DepthRenderer = DepthRenderer;
  78331. })(BABYLON || (BABYLON = {}));
  78332. //# sourceMappingURL=babylon.depthRenderer.js.map
  78333. var BABYLON;
  78334. (function (BABYLON) {
  78335. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  78336. camera = camera || this.activeCamera;
  78337. if (!camera) {
  78338. throw "No camera available to enable depth renderer";
  78339. }
  78340. if (!this._depthRenderer) {
  78341. this._depthRenderer = {};
  78342. }
  78343. if (!this._depthRenderer[camera.id]) {
  78344. var textureType = 0;
  78345. if (this.getEngine().getCaps().textureHalfFloatRender) {
  78346. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78347. }
  78348. else if (this.getEngine().getCaps().textureFloatRender) {
  78349. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78350. }
  78351. else {
  78352. throw "Depth renderer does not support int texture type";
  78353. }
  78354. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  78355. }
  78356. return this._depthRenderer[camera.id];
  78357. };
  78358. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  78359. camera = camera || this.activeCamera;
  78360. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  78361. return;
  78362. }
  78363. this._depthRenderer[camera.id].dispose();
  78364. delete this._depthRenderer[camera.id];
  78365. };
  78366. /**
  78367. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  78368. * in several rendering techniques.
  78369. */
  78370. var DepthRendererSceneComponent = /** @class */ (function () {
  78371. /**
  78372. * Creates a new instance of the component for the given scene
  78373. * @param scene Defines the scene to register the component in
  78374. */
  78375. function DepthRendererSceneComponent(scene) {
  78376. /**
  78377. * The component name helpfull to identify the component in the list of scene components.
  78378. */
  78379. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  78380. this.scene = scene;
  78381. }
  78382. /**
  78383. * Registers the component in a given scene
  78384. */
  78385. DepthRendererSceneComponent.prototype.register = function () {
  78386. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  78387. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  78388. };
  78389. /**
  78390. * Rebuilds the elements related to this component in case of
  78391. * context lost for instance.
  78392. */
  78393. DepthRendererSceneComponent.prototype.rebuild = function () {
  78394. // Nothing to do for this component
  78395. };
  78396. /**
  78397. * Disposes the component and the associated ressources
  78398. */
  78399. DepthRendererSceneComponent.prototype.dispose = function () {
  78400. for (var key in this.scene._depthRenderer) {
  78401. this.scene._depthRenderer[key].dispose();
  78402. }
  78403. };
  78404. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78405. if (this.scene._depthRenderer) {
  78406. for (var key in this.scene._depthRenderer) {
  78407. var depthRenderer = this.scene._depthRenderer[key];
  78408. if (!depthRenderer.useOnlyInActiveCamera) {
  78409. renderTargets.push(depthRenderer.getDepthMap());
  78410. }
  78411. }
  78412. }
  78413. };
  78414. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  78415. if (this.scene._depthRenderer) {
  78416. for (var key in this.scene._depthRenderer) {
  78417. var depthRenderer = this.scene._depthRenderer[key];
  78418. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  78419. renderTargets.push(depthRenderer.getDepthMap());
  78420. }
  78421. }
  78422. }
  78423. };
  78424. return DepthRendererSceneComponent;
  78425. }());
  78426. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  78427. })(BABYLON || (BABYLON = {}));
  78428. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  78429. var BABYLON;
  78430. (function (BABYLON) {
  78431. /**
  78432. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  78433. */
  78434. var GeometryBufferRenderer = /** @class */ (function () {
  78435. /**
  78436. * Creates a new G Buffer for the scene
  78437. * @param scene The scene the buffer belongs to
  78438. * @param ratio How big is the buffer related to the main canvas.
  78439. */
  78440. function GeometryBufferRenderer(scene, ratio) {
  78441. if (ratio === void 0) { ratio = 1; }
  78442. this._enablePosition = false;
  78443. this._scene = scene;
  78444. this._ratio = ratio;
  78445. // Register the G Buffer component to the scene.
  78446. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  78447. if (!component) {
  78448. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  78449. scene._addComponent(component);
  78450. }
  78451. // Render target
  78452. this._createRenderTargets();
  78453. }
  78454. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  78455. /**
  78456. * Set the render list (meshes to be rendered) used in the G buffer.
  78457. */
  78458. set: function (meshes) {
  78459. this._multiRenderTarget.renderList = meshes;
  78460. },
  78461. enumerable: true,
  78462. configurable: true
  78463. });
  78464. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  78465. /**
  78466. * Gets wether or not G buffer are supported by the running hardware.
  78467. * This requires draw buffer supports
  78468. */
  78469. get: function () {
  78470. return this._multiRenderTarget.isSupported;
  78471. },
  78472. enumerable: true,
  78473. configurable: true
  78474. });
  78475. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  78476. /**
  78477. * Gets wether or not position are enabled for the G buffer.
  78478. */
  78479. get: function () {
  78480. return this._enablePosition;
  78481. },
  78482. /**
  78483. * Sets wether or not position are enabled for the G buffer.
  78484. */
  78485. set: function (enable) {
  78486. this._enablePosition = enable;
  78487. this.dispose();
  78488. this._createRenderTargets();
  78489. },
  78490. enumerable: true,
  78491. configurable: true
  78492. });
  78493. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  78494. /**
  78495. * Gets the scene associated with the buffer.
  78496. */
  78497. get: function () {
  78498. return this._scene;
  78499. },
  78500. enumerable: true,
  78501. configurable: true
  78502. });
  78503. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  78504. /**
  78505. * Gets the ratio used by the buffer during its creation.
  78506. * How big is the buffer related to the main canvas.
  78507. */
  78508. get: function () {
  78509. return this._ratio;
  78510. },
  78511. enumerable: true,
  78512. configurable: true
  78513. });
  78514. /**
  78515. * Checks wether everything is ready to render a submesh to the G buffer.
  78516. * @param subMesh the submesh to check readiness for
  78517. * @param useInstances is the mesh drawn using instance or not
  78518. * @returns true if ready otherwise false
  78519. */
  78520. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  78521. var material = subMesh.getMaterial();
  78522. if (material && material.disableDepthWrite) {
  78523. return false;
  78524. }
  78525. var defines = [];
  78526. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78527. var mesh = subMesh.getMesh();
  78528. // Alpha test
  78529. if (material && material.needAlphaTesting()) {
  78530. defines.push("#define ALPHATEST");
  78531. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78532. attribs.push(BABYLON.VertexBuffer.UVKind);
  78533. defines.push("#define UV1");
  78534. }
  78535. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78536. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78537. defines.push("#define UV2");
  78538. }
  78539. }
  78540. // Buffers
  78541. if (this._enablePosition) {
  78542. defines.push("#define POSITION");
  78543. }
  78544. // Bones
  78545. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78546. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78547. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78548. if (mesh.numBoneInfluencers > 4) {
  78549. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78550. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78551. }
  78552. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78553. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78554. }
  78555. else {
  78556. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78557. }
  78558. // Instances
  78559. if (useInstances) {
  78560. defines.push("#define INSTANCES");
  78561. attribs.push("world0");
  78562. attribs.push("world1");
  78563. attribs.push("world2");
  78564. attribs.push("world3");
  78565. }
  78566. // Get correct effect
  78567. var join = defines.join("\n");
  78568. if (this._cachedDefines !== join) {
  78569. this._cachedDefines = join;
  78570. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  78571. }
  78572. return this._effect.isReady();
  78573. };
  78574. /**
  78575. * Gets the current underlying G Buffer.
  78576. * @returns the buffer
  78577. */
  78578. GeometryBufferRenderer.prototype.getGBuffer = function () {
  78579. return this._multiRenderTarget;
  78580. };
  78581. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  78582. /**
  78583. * Gets the number of samples used to render the buffer (anti aliasing).
  78584. */
  78585. get: function () {
  78586. return this._multiRenderTarget.samples;
  78587. },
  78588. /**
  78589. * Sets the number of samples used to render the buffer (anti aliasing).
  78590. */
  78591. set: function (value) {
  78592. this._multiRenderTarget.samples = value;
  78593. },
  78594. enumerable: true,
  78595. configurable: true
  78596. });
  78597. /**
  78598. * Disposes the renderer and frees up associated resources.
  78599. */
  78600. GeometryBufferRenderer.prototype.dispose = function () {
  78601. this.getGBuffer().dispose();
  78602. };
  78603. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  78604. var _this = this;
  78605. var engine = this._scene.getEngine();
  78606. var count = this._enablePosition ? 3 : 2;
  78607. 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 });
  78608. if (!this.isSupported) {
  78609. return;
  78610. }
  78611. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78612. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78613. this._multiRenderTarget.refreshRate = 1;
  78614. this._multiRenderTarget.renderParticles = false;
  78615. this._multiRenderTarget.renderList = null;
  78616. // set default depth value to 1.0 (far away)
  78617. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78618. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78619. });
  78620. // Custom render function
  78621. var renderSubMesh = function (subMesh) {
  78622. var mesh = subMesh.getRenderingMesh();
  78623. var scene = _this._scene;
  78624. var engine = scene.getEngine();
  78625. var material = subMesh.getMaterial();
  78626. if (!material) {
  78627. return;
  78628. }
  78629. // Culling
  78630. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78631. // Managing instances
  78632. var batch = mesh._getInstancesRenderList(subMesh._id);
  78633. if (batch.mustReturn) {
  78634. return;
  78635. }
  78636. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78637. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78638. engine.enableEffect(_this._effect);
  78639. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78640. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78641. _this._effect.setMatrix("view", scene.getViewMatrix());
  78642. // Alpha test
  78643. if (material && material.needAlphaTesting()) {
  78644. var alphaTexture = material.getAlphaTestTexture();
  78645. if (alphaTexture) {
  78646. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78647. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78648. }
  78649. }
  78650. // Bones
  78651. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78652. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78653. }
  78654. // Draw
  78655. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78656. }
  78657. };
  78658. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78659. var index;
  78660. if (depthOnlySubMeshes.length) {
  78661. engine.setColorWrite(false);
  78662. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78663. renderSubMesh(depthOnlySubMeshes.data[index]);
  78664. }
  78665. engine.setColorWrite(true);
  78666. }
  78667. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78668. renderSubMesh(opaqueSubMeshes.data[index]);
  78669. }
  78670. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78671. renderSubMesh(alphaTestSubMeshes.data[index]);
  78672. }
  78673. };
  78674. };
  78675. return GeometryBufferRenderer;
  78676. }());
  78677. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78678. })(BABYLON || (BABYLON = {}));
  78679. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78680. var BABYLON;
  78681. (function (BABYLON) {
  78682. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  78683. get: function () {
  78684. this._geometryBufferRenderer;
  78685. },
  78686. set: function (value) {
  78687. if (value && value.isSupported) {
  78688. this._geometryBufferRenderer = value;
  78689. }
  78690. ;
  78691. },
  78692. enumerable: true,
  78693. configurable: true
  78694. });
  78695. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  78696. if (ratio === void 0) { ratio = 1; }
  78697. if (this._geometryBufferRenderer) {
  78698. return this._geometryBufferRenderer;
  78699. }
  78700. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  78701. if (!this._geometryBufferRenderer.isSupported) {
  78702. this._geometryBufferRenderer = null;
  78703. }
  78704. return this._geometryBufferRenderer;
  78705. };
  78706. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  78707. if (!this._geometryBufferRenderer) {
  78708. return;
  78709. }
  78710. this._geometryBufferRenderer.dispose();
  78711. this._geometryBufferRenderer = null;
  78712. };
  78713. /**
  78714. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  78715. * in several rendering techniques.
  78716. */
  78717. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  78718. /**
  78719. * Creates a new instance of the component for the given scene
  78720. * @param scene Defines the scene to register the component in
  78721. */
  78722. function GeometryBufferRendererSceneComponent(scene) {
  78723. /**
  78724. * The component name helpful to identify the component in the list of scene components.
  78725. */
  78726. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  78727. this.scene = scene;
  78728. }
  78729. /**
  78730. * Registers the component in a given scene
  78731. */
  78732. GeometryBufferRendererSceneComponent.prototype.register = function () {
  78733. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  78734. };
  78735. /**
  78736. * Rebuilds the elements related to this component in case of
  78737. * context lost for instance.
  78738. */
  78739. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  78740. // Nothing to do for this component
  78741. };
  78742. /**
  78743. * Disposes the component and the associated ressources
  78744. */
  78745. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  78746. // Nothing to do for this component
  78747. };
  78748. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78749. if (this.scene._geometryBufferRenderer) {
  78750. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  78751. }
  78752. };
  78753. return GeometryBufferRendererSceneComponent;
  78754. }());
  78755. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  78756. })(BABYLON || (BABYLON = {}));
  78757. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  78758. var BABYLON;
  78759. (function (BABYLON) {
  78760. var SSAORenderingPipeline = /** @class */ (function (_super) {
  78761. __extends(SSAORenderingPipeline, _super);
  78762. /**
  78763. * @constructor
  78764. * @param {string} name - The rendering pipeline name
  78765. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78766. * @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 }
  78767. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78768. */
  78769. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  78770. var _this = _super.call(this, scene.getEngine(), name) || this;
  78771. // Members
  78772. /**
  78773. * The PassPostProcess id in the pipeline that contains the original scene color
  78774. */
  78775. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78776. /**
  78777. * The SSAO PostProcess id in the pipeline
  78778. */
  78779. _this.SSAORenderEffect = "SSAORenderEffect";
  78780. /**
  78781. * The horizontal blur PostProcess id in the pipeline
  78782. */
  78783. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78784. /**
  78785. * The vertical blur PostProcess id in the pipeline
  78786. */
  78787. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78788. /**
  78789. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78790. */
  78791. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78792. /**
  78793. * The output strength of the SSAO post-process. Default value is 1.0.
  78794. */
  78795. _this.totalStrength = 1.0;
  78796. /**
  78797. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  78798. */
  78799. _this.radius = 0.0001;
  78800. /**
  78801. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  78802. * Must not be equal to fallOff and superior to fallOff.
  78803. * Default value is 0.975
  78804. */
  78805. _this.area = 0.0075;
  78806. /**
  78807. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  78808. * Must not be equal to area and inferior to area.
  78809. * Default value is 0.0
  78810. */
  78811. _this.fallOff = 0.000001;
  78812. /**
  78813. * The base color of the SSAO post-process
  78814. * The final result is "base + ssao" between [0, 1]
  78815. */
  78816. _this.base = 0.5;
  78817. _this._firstUpdate = true;
  78818. _this._scene = scene;
  78819. // Set up assets
  78820. _this._createRandomTexture();
  78821. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78822. var ssaoRatio = ratio.ssaoRatio || ratio;
  78823. var combineRatio = ratio.combineRatio || ratio;
  78824. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78825. _this._createSSAOPostProcess(ssaoRatio);
  78826. _this._createBlurPostProcess(ssaoRatio);
  78827. _this._createSSAOCombinePostProcess(combineRatio);
  78828. // Set up pipeline
  78829. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78830. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78831. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78832. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78833. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78834. // Finish
  78835. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78836. if (cameras)
  78837. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78838. return _this;
  78839. }
  78840. // Public Methods
  78841. /**
  78842. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78843. */
  78844. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78845. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78846. for (var i = 0; i < this._scene.cameras.length; i++) {
  78847. var camera = this._scene.cameras[i];
  78848. this._originalColorPostProcess.dispose(camera);
  78849. this._ssaoPostProcess.dispose(camera);
  78850. this._blurHPostProcess.dispose(camera);
  78851. this._blurVPostProcess.dispose(camera);
  78852. this._ssaoCombinePostProcess.dispose(camera);
  78853. }
  78854. this._randomTexture.dispose();
  78855. if (disableDepthRender)
  78856. this._scene.disableDepthRenderer();
  78857. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78858. _super.prototype.dispose.call(this);
  78859. };
  78860. // Private Methods
  78861. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  78862. var _this = this;
  78863. var size = 16;
  78864. 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);
  78865. 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);
  78866. this._blurHPostProcess.onActivateObservable.add(function () {
  78867. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  78868. _this._blurHPostProcess.kernel = size * dw;
  78869. });
  78870. this._blurVPostProcess.onActivateObservable.add(function () {
  78871. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  78872. _this._blurVPostProcess.kernel = size * dw;
  78873. });
  78874. };
  78875. /** @hidden */
  78876. SSAORenderingPipeline.prototype._rebuild = function () {
  78877. this._firstUpdate = true;
  78878. _super.prototype._rebuild.call(this);
  78879. };
  78880. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78881. var _this = this;
  78882. var numSamples = 16;
  78883. var sampleSphere = [
  78884. 0.5381, 0.1856, -0.4319,
  78885. 0.1379, 0.2486, 0.4430,
  78886. 0.3371, 0.5679, -0.0057,
  78887. -0.6999, -0.0451, -0.0019,
  78888. 0.0689, -0.1598, -0.8547,
  78889. 0.0560, 0.0069, -0.1843,
  78890. -0.0146, 0.1402, 0.0762,
  78891. 0.0100, -0.1924, -0.0344,
  78892. -0.3577, -0.5301, -0.4358,
  78893. -0.3169, 0.1063, 0.0158,
  78894. 0.0103, -0.5869, 0.0046,
  78895. -0.0897, -0.4940, 0.3287,
  78896. 0.7119, -0.0154, -0.0918,
  78897. -0.0533, 0.0596, -0.5411,
  78898. 0.0352, -0.0631, 0.5460,
  78899. -0.4776, 0.2847, -0.0271
  78900. ];
  78901. var samplesFactor = 1.0 / numSamples;
  78902. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  78903. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78904. "area", "fallOff", "base", "range", "viewport"
  78905. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78906. this._ssaoPostProcess.onApply = function (effect) {
  78907. if (_this._firstUpdate) {
  78908. effect.setArray3("sampleSphere", sampleSphere);
  78909. effect.setFloat("samplesFactor", samplesFactor);
  78910. effect.setFloat("randTextureTiles", 4.0);
  78911. }
  78912. effect.setFloat("totalStrength", _this.totalStrength);
  78913. effect.setFloat("radius", _this.radius);
  78914. effect.setFloat("area", _this.area);
  78915. effect.setFloat("fallOff", _this.fallOff);
  78916. effect.setFloat("base", _this.base);
  78917. effect.setTexture("textureSampler", _this._depthTexture);
  78918. effect.setTexture("randomSampler", _this._randomTexture);
  78919. };
  78920. };
  78921. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78922. var _this = this;
  78923. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78924. this._ssaoCombinePostProcess.onApply = function (effect) {
  78925. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  78926. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78927. };
  78928. };
  78929. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  78930. var size = 512;
  78931. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78932. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78933. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78934. var context = this._randomTexture.getContext();
  78935. var rand = function (min, max) {
  78936. return Math.random() * (max - min) + min;
  78937. };
  78938. var randVector = BABYLON.Vector3.Zero();
  78939. for (var x = 0; x < size; x++) {
  78940. for (var y = 0; y < size; y++) {
  78941. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  78942. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  78943. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  78944. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78945. context.fillRect(x, y, 1, 1);
  78946. }
  78947. }
  78948. this._randomTexture.update(false);
  78949. };
  78950. __decorate([
  78951. BABYLON.serialize()
  78952. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  78953. __decorate([
  78954. BABYLON.serialize()
  78955. ], SSAORenderingPipeline.prototype, "radius", void 0);
  78956. __decorate([
  78957. BABYLON.serialize()
  78958. ], SSAORenderingPipeline.prototype, "area", void 0);
  78959. __decorate([
  78960. BABYLON.serialize()
  78961. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  78962. __decorate([
  78963. BABYLON.serialize()
  78964. ], SSAORenderingPipeline.prototype, "base", void 0);
  78965. return SSAORenderingPipeline;
  78966. }(BABYLON.PostProcessRenderPipeline));
  78967. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  78968. })(BABYLON || (BABYLON = {}));
  78969. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  78970. var BABYLON;
  78971. (function (BABYLON) {
  78972. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  78973. __extends(SSAO2RenderingPipeline, _super);
  78974. /**
  78975. * @constructor
  78976. * @param {string} name - The rendering pipeline name
  78977. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78978. * @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 }
  78979. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78980. */
  78981. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  78982. var _this = _super.call(this, scene.getEngine(), name) || this;
  78983. // Members
  78984. /**
  78985. * The PassPostProcess id in the pipeline that contains the original scene color
  78986. */
  78987. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78988. /**
  78989. * The SSAO PostProcess id in the pipeline
  78990. */
  78991. _this.SSAORenderEffect = "SSAORenderEffect";
  78992. /**
  78993. * The horizontal blur PostProcess id in the pipeline
  78994. */
  78995. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78996. /**
  78997. * The vertical blur PostProcess id in the pipeline
  78998. */
  78999. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  79000. /**
  79001. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  79002. */
  79003. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  79004. /**
  79005. * The output strength of the SSAO post-process. Default value is 1.0.
  79006. */
  79007. _this.totalStrength = 1.0;
  79008. /**
  79009. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  79010. */
  79011. _this.maxZ = 100.0;
  79012. /**
  79013. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  79014. */
  79015. _this.minZAspect = 0.2;
  79016. _this._samples = 8;
  79017. _this._textureSamples = 1;
  79018. /**
  79019. * Are we using bilateral blur ?
  79020. */
  79021. _this._expensiveBlur = true;
  79022. /**
  79023. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  79024. */
  79025. _this.radius = 2.0;
  79026. /**
  79027. * The base color of the SSAO post-process
  79028. * The final result is "base + ssao" between [0, 1]
  79029. */
  79030. _this.base = 0;
  79031. _this._firstUpdate = true;
  79032. _this._bits = new Uint32Array(1);
  79033. _this._scene = scene;
  79034. _this._ratio = ratio;
  79035. if (!_this.isSupported) {
  79036. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  79037. return _this;
  79038. }
  79039. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  79040. var blurRatio = _this._ratio.blurRatio || ratio;
  79041. // Set up assets
  79042. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  79043. _this._createRandomTexture();
  79044. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  79045. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  79046. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  79047. _this._originalColorPostProcess.samples = _this.textureSamples;
  79048. _this._createSSAOPostProcess(1.0);
  79049. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  79050. _this._createSSAOCombinePostProcess(blurRatio);
  79051. // Set up pipeline
  79052. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  79053. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  79054. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  79055. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  79056. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  79057. // Finish
  79058. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79059. if (cameras)
  79060. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  79061. return _this;
  79062. }
  79063. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  79064. get: function () {
  79065. return this._samples;
  79066. },
  79067. /**
  79068. * Number of samples used for the SSAO calculations. Default value is 8
  79069. */
  79070. set: function (n) {
  79071. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  79072. this._samples = n;
  79073. this._sampleSphere = this._generateHemisphere();
  79074. this._firstUpdate = true;
  79075. },
  79076. enumerable: true,
  79077. configurable: true
  79078. });
  79079. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  79080. get: function () {
  79081. return this._textureSamples;
  79082. },
  79083. /**
  79084. * Number of samples to use for antialiasing
  79085. */
  79086. set: function (n) {
  79087. this._textureSamples = n;
  79088. this._originalColorPostProcess.samples = n;
  79089. this._blurHPostProcess.samples = n;
  79090. this._blurVPostProcess.samples = n;
  79091. this._ssaoPostProcess.samples = n;
  79092. this._ssaoCombinePostProcess.samples = n;
  79093. },
  79094. enumerable: true,
  79095. configurable: true
  79096. });
  79097. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  79098. get: function () {
  79099. return this._expensiveBlur;
  79100. },
  79101. set: function (b) {
  79102. 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"]);
  79103. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  79104. this._expensiveBlur = b;
  79105. this._firstUpdate = true;
  79106. },
  79107. enumerable: true,
  79108. configurable: true
  79109. });
  79110. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  79111. /**
  79112. * Support test.
  79113. */
  79114. get: function () {
  79115. var engine = BABYLON.Engine.LastCreatedEngine;
  79116. if (!engine) {
  79117. return false;
  79118. }
  79119. return engine.getCaps().drawBuffersExtension;
  79120. },
  79121. enumerable: true,
  79122. configurable: true
  79123. });
  79124. // Public Methods
  79125. /**
  79126. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  79127. */
  79128. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  79129. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  79130. for (var i = 0; i < this._scene.cameras.length; i++) {
  79131. var camera = this._scene.cameras[i];
  79132. this._originalColorPostProcess.dispose(camera);
  79133. this._ssaoPostProcess.dispose(camera);
  79134. this._blurHPostProcess.dispose(camera);
  79135. this._blurVPostProcess.dispose(camera);
  79136. this._ssaoCombinePostProcess.dispose(camera);
  79137. }
  79138. this._randomTexture.dispose();
  79139. if (disableGeometryBufferRenderer)
  79140. this._scene.disableGeometryBufferRenderer();
  79141. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  79142. _super.prototype.dispose.call(this);
  79143. };
  79144. // Private Methods
  79145. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  79146. var _this = this;
  79147. this._samplerOffsets = [];
  79148. var expensive = this.expensiveBlur;
  79149. for (var i = -8; i < 8; i++) {
  79150. this._samplerOffsets.push(i * 2 + 0.5);
  79151. }
  79152. 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");
  79153. this._blurHPostProcess.onApply = function (effect) {
  79154. if (!_this._scene.activeCamera) {
  79155. return;
  79156. }
  79157. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  79158. effect.setFloat("near", _this._scene.activeCamera.minZ);
  79159. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  79160. effect.setFloat("radius", _this.radius);
  79161. effect.setTexture("depthSampler", _this._depthTexture);
  79162. if (_this._firstUpdate) {
  79163. effect.setArray("samplerOffsets", _this._samplerOffsets);
  79164. }
  79165. };
  79166. 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");
  79167. this._blurVPostProcess.onApply = function (effect) {
  79168. if (!_this._scene.activeCamera) {
  79169. return;
  79170. }
  79171. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  79172. effect.setFloat("near", _this._scene.activeCamera.minZ);
  79173. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  79174. effect.setFloat("radius", _this.radius);
  79175. effect.setTexture("depthSampler", _this._depthTexture);
  79176. if (_this._firstUpdate) {
  79177. effect.setArray("samplerOffsets", _this._samplerOffsets);
  79178. _this._firstUpdate = false;
  79179. }
  79180. };
  79181. this._blurHPostProcess.samples = this.textureSamples;
  79182. this._blurVPostProcess.samples = this.textureSamples;
  79183. };
  79184. /** @hidden */
  79185. SSAO2RenderingPipeline.prototype._rebuild = function () {
  79186. this._firstUpdate = true;
  79187. _super.prototype._rebuild.call(this);
  79188. };
  79189. //Van der Corput radical inverse
  79190. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  79191. this._bits[0] = i;
  79192. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  79193. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  79194. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  79195. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  79196. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  79197. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  79198. };
  79199. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  79200. return [i / n, this._radicalInverse_VdC(i)];
  79201. };
  79202. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  79203. var phi = v * 2.0 * Math.PI;
  79204. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  79205. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  79206. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  79207. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  79208. };
  79209. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  79210. var numSamples = this.samples;
  79211. var result = [];
  79212. var vector;
  79213. var i = 0;
  79214. while (i < numSamples) {
  79215. if (numSamples < 16) {
  79216. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  79217. }
  79218. else {
  79219. var rand = this._hammersley(i, numSamples);
  79220. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  79221. }
  79222. result.push(vector.x, vector.y, vector.z);
  79223. i++;
  79224. }
  79225. return result;
  79226. };
  79227. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  79228. var _this = this;
  79229. var numSamples = this.samples;
  79230. this._sampleSphere = this._generateHemisphere();
  79231. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  79232. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  79233. "base", "range", "projection", "near", "far", "texelSize",
  79234. "xViewport", "yViewport", "maxZ", "minZAspect"
  79235. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  79236. this._ssaoPostProcess.onApply = function (effect) {
  79237. if (_this._firstUpdate) {
  79238. effect.setArray3("sampleSphere", _this._sampleSphere);
  79239. effect.setFloat("randTextureTiles", 32.0);
  79240. }
  79241. if (!_this._scene.activeCamera) {
  79242. return;
  79243. }
  79244. effect.setFloat("samplesFactor", 1 / _this.samples);
  79245. effect.setFloat("totalStrength", _this.totalStrength);
  79246. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  79247. effect.setFloat("radius", _this.radius);
  79248. effect.setFloat("maxZ", _this.maxZ);
  79249. effect.setFloat("minZAspect", _this.minZAspect);
  79250. effect.setFloat("base", _this.base);
  79251. effect.setFloat("near", _this._scene.activeCamera.minZ);
  79252. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  79253. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  79254. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  79255. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  79256. effect.setTexture("textureSampler", _this._depthTexture);
  79257. effect.setTexture("normalSampler", _this._normalTexture);
  79258. effect.setTexture("randomSampler", _this._randomTexture);
  79259. };
  79260. this._ssaoPostProcess.samples = this.textureSamples;
  79261. };
  79262. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  79263. var _this = this;
  79264. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  79265. this._ssaoCombinePostProcess.onApply = function (effect) {
  79266. var viewport = _this._scene.activeCamera.viewport;
  79267. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  79268. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  79269. };
  79270. this._ssaoCombinePostProcess.samples = this.textureSamples;
  79271. };
  79272. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  79273. var size = 128;
  79274. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79275. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  79276. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  79277. var context = this._randomTexture.getContext();
  79278. var rand = function (min, max) {
  79279. return Math.random() * (max - min) + min;
  79280. };
  79281. var randVector = BABYLON.Vector3.Zero();
  79282. for (var x = 0; x < size; x++) {
  79283. for (var y = 0; y < size; y++) {
  79284. randVector.x = rand(0.0, 1.0);
  79285. randVector.y = rand(0.0, 1.0);
  79286. randVector.z = 0.0;
  79287. randVector.normalize();
  79288. randVector.scaleInPlace(255);
  79289. randVector.x = Math.floor(randVector.x);
  79290. randVector.y = Math.floor(randVector.y);
  79291. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  79292. context.fillRect(x, y, 1, 1);
  79293. }
  79294. }
  79295. this._randomTexture.update(false);
  79296. };
  79297. /**
  79298. * Serialize the rendering pipeline (Used when exporting)
  79299. * @returns the serialized object
  79300. */
  79301. SSAO2RenderingPipeline.prototype.serialize = function () {
  79302. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79303. serializationObject.customType = "SSAO2RenderingPipeline";
  79304. return serializationObject;
  79305. };
  79306. /**
  79307. * Parse the serialized pipeline
  79308. * @param source Source pipeline.
  79309. * @param scene The scene to load the pipeline to.
  79310. * @param rootUrl The URL of the serialized pipeline.
  79311. * @returns An instantiated pipeline from the serialized object.
  79312. */
  79313. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  79314. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  79315. };
  79316. __decorate([
  79317. BABYLON.serialize()
  79318. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  79319. __decorate([
  79320. BABYLON.serialize()
  79321. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  79322. __decorate([
  79323. BABYLON.serialize()
  79324. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  79325. __decorate([
  79326. BABYLON.serialize("samples")
  79327. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  79328. __decorate([
  79329. BABYLON.serialize("textureSamples")
  79330. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  79331. __decorate([
  79332. BABYLON.serialize()
  79333. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  79334. __decorate([
  79335. BABYLON.serialize("expensiveBlur")
  79336. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  79337. __decorate([
  79338. BABYLON.serialize()
  79339. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  79340. __decorate([
  79341. BABYLON.serialize()
  79342. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  79343. return SSAO2RenderingPipeline;
  79344. }(BABYLON.PostProcessRenderPipeline));
  79345. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  79346. })(BABYLON || (BABYLON = {}));
  79347. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  79348. // BABYLON.JS Chromatic Aberration GLSL Shader
  79349. // Author: Olivier Guyot
  79350. // Separates very slightly R, G and B colors on the edges of the screen
  79351. // Inspired by Francois Tarlier & Martins Upitis
  79352. var BABYLON;
  79353. (function (BABYLON) {
  79354. var LensRenderingPipeline = /** @class */ (function (_super) {
  79355. __extends(LensRenderingPipeline, _super);
  79356. /**
  79357. * @constructor
  79358. *
  79359. * Effect parameters are as follow:
  79360. * {
  79361. * chromatic_aberration: number; // from 0 to x (1 for realism)
  79362. * edge_blur: number; // from 0 to x (1 for realism)
  79363. * distortion: number; // from 0 to x (1 for realism)
  79364. * grain_amount: number; // from 0 to 1
  79365. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  79366. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  79367. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  79368. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  79369. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  79370. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  79371. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  79372. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  79373. * }
  79374. * Note: if an effect parameter is unset, effect is disabled
  79375. *
  79376. * @param {string} name - The rendering pipeline name
  79377. * @param {object} parameters - An object containing all parameters (see above)
  79378. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  79379. * @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)
  79380. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  79381. */
  79382. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  79383. if (ratio === void 0) { ratio = 1.0; }
  79384. var _this = _super.call(this, scene.getEngine(), name) || this;
  79385. // Lens effects can be of the following:
  79386. // - chromatic aberration (slight shift of RGB colors)
  79387. // - blur on the edge of the lens
  79388. // - lens distortion
  79389. // - depth-of-field blur & highlights enhancing
  79390. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  79391. // - grain effect (noise or custom texture)
  79392. // Two additional texture samplers are needed:
  79393. // - depth map (for depth-of-field)
  79394. // - grain texture
  79395. /**
  79396. * The chromatic aberration PostProcess id in the pipeline
  79397. */
  79398. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  79399. /**
  79400. * The highlights enhancing PostProcess id in the pipeline
  79401. */
  79402. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  79403. /**
  79404. * The depth-of-field PostProcess id in the pipeline
  79405. */
  79406. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  79407. _this._scene = scene;
  79408. // Fetch texture samplers
  79409. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  79410. if (parameters.grain_texture) {
  79411. _this._grainTexture = parameters.grain_texture;
  79412. }
  79413. else {
  79414. _this._createGrainTexture();
  79415. }
  79416. // save parameters
  79417. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  79418. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  79419. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  79420. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  79421. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  79422. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  79423. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  79424. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  79425. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  79426. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  79427. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  79428. // Create effects
  79429. _this._createChromaticAberrationPostProcess(ratio);
  79430. _this._createHighlightsPostProcess(ratio);
  79431. _this._createDepthOfFieldPostProcess(ratio / 4);
  79432. // Set up pipeline
  79433. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  79434. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  79435. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  79436. if (_this._highlightsGain === -1) {
  79437. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  79438. }
  79439. // Finish
  79440. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79441. if (cameras) {
  79442. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  79443. }
  79444. return _this;
  79445. }
  79446. // public methods (self explanatory)
  79447. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  79448. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  79449. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  79450. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  79451. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  79452. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  79453. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  79454. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  79455. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  79456. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  79457. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  79458. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  79459. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  79460. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  79461. };
  79462. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  79463. this._highlightsPostProcess.updateEffect();
  79464. };
  79465. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  79466. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  79467. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  79468. this._highlightsGain = amount;
  79469. };
  79470. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  79471. if (this._highlightsGain === -1) {
  79472. this._highlightsGain = 1.0;
  79473. }
  79474. this._highlightsThreshold = amount;
  79475. };
  79476. LensRenderingPipeline.prototype.disableHighlights = function () {
  79477. this._highlightsGain = -1;
  79478. };
  79479. /**
  79480. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  79481. */
  79482. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  79483. if (disableDepthRender === void 0) { disableDepthRender = false; }
  79484. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  79485. this._chromaticAberrationPostProcess = null;
  79486. this._highlightsPostProcess = null;
  79487. this._depthOfFieldPostProcess = null;
  79488. this._grainTexture.dispose();
  79489. if (disableDepthRender)
  79490. this._scene.disableDepthRenderer();
  79491. };
  79492. // colors shifting and distortion
  79493. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  79494. var _this = this;
  79495. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  79496. [], // samplers
  79497. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  79498. this._chromaticAberrationPostProcess.onApply = function (effect) {
  79499. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  79500. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79501. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79502. effect.setFloat('radialIntensity', 1);
  79503. effect.setFloat2('direction', 17, 17);
  79504. effect.setFloat2('centerPosition', 0.5, 0.5);
  79505. };
  79506. };
  79507. // highlights enhancing
  79508. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  79509. var _this = this;
  79510. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  79511. [], // samplers
  79512. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  79513. this._highlightsPostProcess.onApply = function (effect) {
  79514. effect.setFloat('gain', _this._highlightsGain);
  79515. effect.setFloat('threshold', _this._highlightsThreshold);
  79516. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  79517. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79518. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79519. };
  79520. };
  79521. // colors shifting and distortion
  79522. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  79523. var _this = this;
  79524. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  79525. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  79526. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  79527. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  79528. this._depthOfFieldPostProcess.onApply = function (effect) {
  79529. effect.setTexture("depthSampler", _this._depthTexture);
  79530. effect.setTexture("grainSampler", _this._grainTexture);
  79531. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  79532. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  79533. effect.setFloat('grain_amount', _this._grainAmount);
  79534. effect.setBool('blur_noise', _this._blurNoise);
  79535. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79536. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79537. effect.setFloat('distortion', _this._distortion);
  79538. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  79539. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  79540. effect.setFloat('aperture', _this._dofAperture);
  79541. effect.setFloat('darken', _this._dofDarken);
  79542. effect.setFloat('edge_blur', _this._edgeBlur);
  79543. effect.setBool('highlights', (_this._highlightsGain !== -1));
  79544. if (_this._scene.activeCamera) {
  79545. effect.setFloat('near', _this._scene.activeCamera.minZ);
  79546. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  79547. }
  79548. };
  79549. };
  79550. // creates a black and white random noise texture, 512x512
  79551. LensRenderingPipeline.prototype._createGrainTexture = function () {
  79552. var size = 512;
  79553. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79554. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  79555. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  79556. var context = this._grainTexture.getContext();
  79557. var rand = function (min, max) {
  79558. return Math.random() * (max - min) + min;
  79559. };
  79560. var value;
  79561. for (var x = 0; x < size; x++) {
  79562. for (var y = 0; y < size; y++) {
  79563. value = Math.floor(rand(0.42, 0.58) * 255);
  79564. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  79565. context.fillRect(x, y, 1, 1);
  79566. }
  79567. }
  79568. this._grainTexture.update(false);
  79569. };
  79570. return LensRenderingPipeline;
  79571. }(BABYLON.PostProcessRenderPipeline));
  79572. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  79573. })(BABYLON || (BABYLON = {}));
  79574. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  79575. var BABYLON;
  79576. (function (BABYLON) {
  79577. var StandardRenderingPipeline = /** @class */ (function (_super) {
  79578. __extends(StandardRenderingPipeline, _super);
  79579. /**
  79580. * @constructor
  79581. * @param {string} name - The rendering pipeline name
  79582. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  79583. * @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)
  79584. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  79585. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  79586. */
  79587. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  79588. if (originalPostProcess === void 0) { originalPostProcess = null; }
  79589. var _this = _super.call(this, scene.getEngine(), name) || this;
  79590. /**
  79591. * Post-process used to down scale an image x4
  79592. */
  79593. _this.downSampleX4PostProcess = null;
  79594. /**
  79595. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  79596. */
  79597. _this.brightPassPostProcess = null;
  79598. /**
  79599. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  79600. */
  79601. _this.blurHPostProcesses = [];
  79602. /**
  79603. * Post-process array storing all the vertical blur post-processes used by the pipeline
  79604. */
  79605. _this.blurVPostProcesses = [];
  79606. /**
  79607. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  79608. */
  79609. _this.textureAdderPostProcess = null;
  79610. /**
  79611. * Post-process used to create volumetric lighting effect
  79612. */
  79613. _this.volumetricLightPostProcess = null;
  79614. /**
  79615. * Post-process used to smooth the previous volumetric light post-process on the X axis
  79616. */
  79617. _this.volumetricLightSmoothXPostProcess = null;
  79618. /**
  79619. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  79620. */
  79621. _this.volumetricLightSmoothYPostProcess = null;
  79622. /**
  79623. * Post-process used to merge the volumetric light effect and the real scene color
  79624. */
  79625. _this.volumetricLightMergePostProces = null;
  79626. /**
  79627. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  79628. */
  79629. _this.volumetricLightFinalPostProcess = null;
  79630. /**
  79631. * Base post-process used to calculate the average luminance of the final image for HDR
  79632. */
  79633. _this.luminancePostProcess = null;
  79634. /**
  79635. * Post-processes used to create down sample post-processes in order to get
  79636. * the average luminance of the final image for HDR
  79637. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  79638. */
  79639. _this.luminanceDownSamplePostProcesses = [];
  79640. /**
  79641. * Post-process used to create a HDR effect (light adaptation)
  79642. */
  79643. _this.hdrPostProcess = null;
  79644. /**
  79645. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  79646. */
  79647. _this.textureAdderFinalPostProcess = null;
  79648. /**
  79649. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  79650. */
  79651. _this.lensFlareFinalPostProcess = null;
  79652. /**
  79653. * Post-process used to merge the final HDR post-process and the real scene color
  79654. */
  79655. _this.hdrFinalPostProcess = null;
  79656. /**
  79657. * Post-process used to create a lens flare effect
  79658. */
  79659. _this.lensFlarePostProcess = null;
  79660. /**
  79661. * Post-process that merges the result of the lens flare post-process and the real scene color
  79662. */
  79663. _this.lensFlareComposePostProcess = null;
  79664. /**
  79665. * Post-process used to create a motion blur effect
  79666. */
  79667. _this.motionBlurPostProcess = null;
  79668. /**
  79669. * Post-process used to create a depth of field effect
  79670. */
  79671. _this.depthOfFieldPostProcess = null;
  79672. /**
  79673. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  79674. */
  79675. _this.fxaaPostProcess = null;
  79676. // Values
  79677. /**
  79678. * Represents the brightness threshold in order to configure the illuminated surfaces
  79679. */
  79680. _this.brightThreshold = 1.0;
  79681. /**
  79682. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  79683. */
  79684. _this.blurWidth = 512.0;
  79685. /**
  79686. * Sets if the blur for highlighted surfaces must be only horizontal
  79687. */
  79688. _this.horizontalBlur = false;
  79689. /**
  79690. * Sets the overall exposure used by the pipeline
  79691. */
  79692. _this.exposure = 1.0;
  79693. /**
  79694. * Texture used typically to simulate "dirty" on camera lens
  79695. */
  79696. _this.lensTexture = null;
  79697. /**
  79698. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  79699. */
  79700. _this.volumetricLightCoefficient = 0.2;
  79701. /**
  79702. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  79703. */
  79704. _this.volumetricLightPower = 4.0;
  79705. /**
  79706. * Used the set the blur intensity to smooth the volumetric lights
  79707. */
  79708. _this.volumetricLightBlurScale = 64.0;
  79709. /**
  79710. * Light (spot or directional) used to generate the volumetric lights rays
  79711. * The source light must have a shadow generate so the pipeline can get its
  79712. * depth map
  79713. */
  79714. _this.sourceLight = null;
  79715. /**
  79716. * For eye adaptation, represents the minimum luminance the eye can see
  79717. */
  79718. _this.hdrMinimumLuminance = 1.0;
  79719. /**
  79720. * For eye adaptation, represents the decrease luminance speed
  79721. */
  79722. _this.hdrDecreaseRate = 0.5;
  79723. /**
  79724. * For eye adaptation, represents the increase luminance speed
  79725. */
  79726. _this.hdrIncreaseRate = 0.5;
  79727. /**
  79728. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  79729. */
  79730. _this.lensColorTexture = null;
  79731. /**
  79732. * The overall strengh for the lens flare effect
  79733. */
  79734. _this.lensFlareStrength = 20.0;
  79735. /**
  79736. * Dispersion coefficient for lens flare ghosts
  79737. */
  79738. _this.lensFlareGhostDispersal = 1.4;
  79739. /**
  79740. * Main lens flare halo width
  79741. */
  79742. _this.lensFlareHaloWidth = 0.7;
  79743. /**
  79744. * Based on the lens distortion effect, defines how much the lens flare result
  79745. * is distorted
  79746. */
  79747. _this.lensFlareDistortionStrength = 16.0;
  79748. /**
  79749. * Lens star texture must be used to simulate rays on the flares and is available
  79750. * in the documentation
  79751. */
  79752. _this.lensStarTexture = null;
  79753. /**
  79754. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  79755. * flare effect by taking account of the dirt texture
  79756. */
  79757. _this.lensFlareDirtTexture = null;
  79758. /**
  79759. * Represents the focal length for the depth of field effect
  79760. */
  79761. _this.depthOfFieldDistance = 10.0;
  79762. /**
  79763. * Represents the blur intensity for the blurred part of the depth of field effect
  79764. */
  79765. _this.depthOfFieldBlurWidth = 64.0;
  79766. /**
  79767. * For motion blur, defines how much the image is blurred by the movement
  79768. */
  79769. _this.motionStrength = 1.0;
  79770. /**
  79771. * List of animations for the pipeline (IAnimatable implementation)
  79772. */
  79773. _this.animations = [];
  79774. _this._currentDepthOfFieldSource = null;
  79775. _this._hdrCurrentLuminance = 1.0;
  79776. // Getters and setters
  79777. _this._bloomEnabled = false;
  79778. _this._depthOfFieldEnabled = false;
  79779. _this._vlsEnabled = false;
  79780. _this._lensFlareEnabled = false;
  79781. _this._hdrEnabled = false;
  79782. _this._motionBlurEnabled = false;
  79783. _this._fxaaEnabled = false;
  79784. _this._motionBlurSamples = 64.0;
  79785. _this._volumetricLightStepsCount = 50.0;
  79786. _this._samples = 1;
  79787. _this._cameras = cameras || [];
  79788. // Initialize
  79789. _this._scene = scene;
  79790. _this._basePostProcess = originalPostProcess;
  79791. _this._ratio = ratio;
  79792. // Misc
  79793. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79794. // Finish
  79795. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79796. _this._buildPipeline();
  79797. return _this;
  79798. }
  79799. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  79800. /**
  79801. * Specifies if the bloom pipeline is enabled
  79802. */
  79803. get: function () {
  79804. return this._bloomEnabled;
  79805. },
  79806. set: function (enabled) {
  79807. if (this._bloomEnabled === enabled) {
  79808. return;
  79809. }
  79810. this._bloomEnabled = enabled;
  79811. this._buildPipeline();
  79812. },
  79813. enumerable: true,
  79814. configurable: true
  79815. });
  79816. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  79817. /**
  79818. * Specifies if the depth of field pipeline is enabed
  79819. */
  79820. get: function () {
  79821. return this._depthOfFieldEnabled;
  79822. },
  79823. set: function (enabled) {
  79824. if (this._depthOfFieldEnabled === enabled) {
  79825. return;
  79826. }
  79827. this._depthOfFieldEnabled = enabled;
  79828. this._buildPipeline();
  79829. },
  79830. enumerable: true,
  79831. configurable: true
  79832. });
  79833. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  79834. /**
  79835. * Specifies if the lens flare pipeline is enabed
  79836. */
  79837. get: function () {
  79838. return this._lensFlareEnabled;
  79839. },
  79840. set: function (enabled) {
  79841. if (this._lensFlareEnabled === enabled) {
  79842. return;
  79843. }
  79844. this._lensFlareEnabled = enabled;
  79845. this._buildPipeline();
  79846. },
  79847. enumerable: true,
  79848. configurable: true
  79849. });
  79850. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  79851. /**
  79852. * Specifies if the HDR pipeline is enabled
  79853. */
  79854. get: function () {
  79855. return this._hdrEnabled;
  79856. },
  79857. set: function (enabled) {
  79858. if (this._hdrEnabled === enabled) {
  79859. return;
  79860. }
  79861. this._hdrEnabled = enabled;
  79862. this._buildPipeline();
  79863. },
  79864. enumerable: true,
  79865. configurable: true
  79866. });
  79867. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  79868. /**
  79869. * Specifies if the volumetric lights scattering effect is enabled
  79870. */
  79871. get: function () {
  79872. return this._vlsEnabled;
  79873. },
  79874. set: function (enabled) {
  79875. if (this._vlsEnabled === enabled) {
  79876. return;
  79877. }
  79878. if (enabled) {
  79879. var geometry = this._scene.enableGeometryBufferRenderer();
  79880. if (!geometry) {
  79881. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  79882. return;
  79883. }
  79884. }
  79885. this._vlsEnabled = enabled;
  79886. this._buildPipeline();
  79887. },
  79888. enumerable: true,
  79889. configurable: true
  79890. });
  79891. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  79892. /**
  79893. * Specifies if the motion blur effect is enabled
  79894. */
  79895. get: function () {
  79896. return this._motionBlurEnabled;
  79897. },
  79898. set: function (enabled) {
  79899. if (this._motionBlurEnabled === enabled) {
  79900. return;
  79901. }
  79902. this._motionBlurEnabled = enabled;
  79903. this._buildPipeline();
  79904. },
  79905. enumerable: true,
  79906. configurable: true
  79907. });
  79908. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  79909. /**
  79910. * Specifies if anti-aliasing is enabled
  79911. */
  79912. get: function () {
  79913. return this._fxaaEnabled;
  79914. },
  79915. set: function (enabled) {
  79916. if (this._fxaaEnabled === enabled) {
  79917. return;
  79918. }
  79919. this._fxaaEnabled = enabled;
  79920. this._buildPipeline();
  79921. },
  79922. enumerable: true,
  79923. configurable: true
  79924. });
  79925. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  79926. /**
  79927. * Specifies the number of steps used to calculate the volumetric lights
  79928. * Typically in interval [50, 200]
  79929. */
  79930. get: function () {
  79931. return this._volumetricLightStepsCount;
  79932. },
  79933. set: function (count) {
  79934. if (this.volumetricLightPostProcess) {
  79935. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  79936. }
  79937. this._volumetricLightStepsCount = count;
  79938. },
  79939. enumerable: true,
  79940. configurable: true
  79941. });
  79942. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  79943. /**
  79944. * Specifies the number of samples used for the motion blur effect
  79945. * Typically in interval [16, 64]
  79946. */
  79947. get: function () {
  79948. return this._motionBlurSamples;
  79949. },
  79950. set: function (samples) {
  79951. if (this.motionBlurPostProcess) {
  79952. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  79953. }
  79954. this._motionBlurSamples = samples;
  79955. },
  79956. enumerable: true,
  79957. configurable: true
  79958. });
  79959. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  79960. /**
  79961. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  79962. */
  79963. get: function () {
  79964. return this._samples;
  79965. },
  79966. set: function (sampleCount) {
  79967. if (this._samples === sampleCount) {
  79968. return;
  79969. }
  79970. this._samples = sampleCount;
  79971. this._buildPipeline();
  79972. },
  79973. enumerable: true,
  79974. configurable: true
  79975. });
  79976. StandardRenderingPipeline.prototype._buildPipeline = function () {
  79977. var _this = this;
  79978. var ratio = this._ratio;
  79979. var scene = this._scene;
  79980. this._disposePostProcesses();
  79981. this._reset();
  79982. // Create pass post-process
  79983. if (!this._basePostProcess) {
  79984. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  79985. this.originalPostProcess.onApply = function (effect) {
  79986. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  79987. };
  79988. }
  79989. else {
  79990. this.originalPostProcess = this._basePostProcess;
  79991. }
  79992. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  79993. this._currentDepthOfFieldSource = this.originalPostProcess;
  79994. if (this._bloomEnabled) {
  79995. // Create down sample X4 post-process
  79996. this._createDownSampleX4PostProcess(scene, ratio / 2);
  79997. // Create bright pass post-process
  79998. this._createBrightPassPostProcess(scene, ratio / 2);
  79999. // Create gaussian blur post-processes (down sampling blurs)
  80000. this._createBlurPostProcesses(scene, ratio / 4, 1);
  80001. // Create texture adder post-process
  80002. this._createTextureAdderPostProcess(scene, ratio);
  80003. // Create depth-of-field source post-process
  80004. 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);
  80005. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  80006. }
  80007. if (this._vlsEnabled) {
  80008. // Create volumetric light
  80009. this._createVolumetricLightPostProcess(scene, ratio);
  80010. // Create volumetric light final post-process
  80011. 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);
  80012. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  80013. }
  80014. if (this._lensFlareEnabled) {
  80015. // Create lens flare post-process
  80016. this._createLensFlarePostProcess(scene, ratio);
  80017. // Create depth-of-field source post-process post lens-flare and disable it now
  80018. 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);
  80019. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  80020. }
  80021. if (this._hdrEnabled) {
  80022. // Create luminance
  80023. this._createLuminancePostProcesses(scene, this._floatTextureType);
  80024. // Create HDR
  80025. this._createHdrPostProcess(scene, ratio);
  80026. // Create depth-of-field source post-process post hdr and disable it now
  80027. 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);
  80028. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  80029. }
  80030. if (this._depthOfFieldEnabled) {
  80031. // Create gaussian blur used by depth-of-field
  80032. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  80033. // Create depth-of-field post-process
  80034. this._createDepthOfFieldPostProcess(scene, ratio);
  80035. }
  80036. if (this._motionBlurEnabled) {
  80037. // Create motion blur post-process
  80038. this._createMotionBlurPostProcess(scene, ratio);
  80039. }
  80040. if (this._fxaaEnabled) {
  80041. // Create fxaa post-process
  80042. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80043. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  80044. }
  80045. if (this._cameras !== null) {
  80046. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  80047. }
  80048. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  80049. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  80050. }
  80051. };
  80052. // Down Sample X4 Post-Processs
  80053. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  80054. var _this = this;
  80055. var downSampleX4Offsets = new Array(32);
  80056. 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);
  80057. this.downSampleX4PostProcess.onApply = function (effect) {
  80058. var id = 0;
  80059. var width = _this.downSampleX4PostProcess.width;
  80060. var height = _this.downSampleX4PostProcess.height;
  80061. for (var i = -2; i < 2; i++) {
  80062. for (var j = -2; j < 2; j++) {
  80063. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  80064. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  80065. id += 2;
  80066. }
  80067. }
  80068. effect.setArray2("dsOffsets", downSampleX4Offsets);
  80069. };
  80070. // Add to pipeline
  80071. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  80072. };
  80073. // Brightpass Post-Process
  80074. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  80075. var _this = this;
  80076. var brightOffsets = new Array(8);
  80077. 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);
  80078. this.brightPassPostProcess.onApply = function (effect) {
  80079. var sU = (1.0 / _this.brightPassPostProcess.width);
  80080. var sV = (1.0 / _this.brightPassPostProcess.height);
  80081. brightOffsets[0] = -0.5 * sU;
  80082. brightOffsets[1] = 0.5 * sV;
  80083. brightOffsets[2] = 0.5 * sU;
  80084. brightOffsets[3] = 0.5 * sV;
  80085. brightOffsets[4] = -0.5 * sU;
  80086. brightOffsets[5] = -0.5 * sV;
  80087. brightOffsets[6] = 0.5 * sU;
  80088. brightOffsets[7] = -0.5 * sV;
  80089. effect.setArray2("dsOffsets", brightOffsets);
  80090. effect.setFloat("brightThreshold", _this.brightThreshold);
  80091. };
  80092. // Add to pipeline
  80093. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  80094. };
  80095. // Create blur H&V post-processes
  80096. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  80097. var _this = this;
  80098. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  80099. var engine = scene.getEngine();
  80100. 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);
  80101. 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);
  80102. blurX.onActivateObservable.add(function () {
  80103. var dw = blurX.width / engine.getRenderWidth();
  80104. blurX.kernel = _this[blurWidthKey] * dw;
  80105. });
  80106. blurY.onActivateObservable.add(function () {
  80107. var dw = blurY.height / engine.getRenderHeight();
  80108. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  80109. });
  80110. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  80111. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  80112. this.blurHPostProcesses.push(blurX);
  80113. this.blurVPostProcesses.push(blurY);
  80114. };
  80115. // Create texture adder post-process
  80116. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  80117. var _this = this;
  80118. 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);
  80119. this.textureAdderPostProcess.onApply = function (effect) {
  80120. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  80121. effect.setTexture("lensSampler", _this.lensTexture);
  80122. effect.setFloat("exposure", _this.exposure);
  80123. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  80124. };
  80125. // Add to pipeline
  80126. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  80127. };
  80128. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  80129. var _this = this;
  80130. var geometryRenderer = scene.enableGeometryBufferRenderer();
  80131. geometryRenderer.enablePosition = true;
  80132. var geometry = geometryRenderer.getGBuffer();
  80133. // Base post-process
  80134. 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));
  80135. var depthValues = BABYLON.Vector2.Zero();
  80136. this.volumetricLightPostProcess.onApply = function (effect) {
  80137. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  80138. var generator = _this.sourceLight.getShadowGenerator();
  80139. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  80140. effect.setTexture("positionSampler", geometry.textures[2]);
  80141. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  80142. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  80143. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  80144. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  80145. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  80146. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  80147. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  80148. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  80149. effect.setVector2("depthValues", depthValues);
  80150. }
  80151. };
  80152. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  80153. // Smooth
  80154. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  80155. // Merge
  80156. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  80157. this.volumetricLightMergePostProces.onApply = function (effect) {
  80158. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  80159. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  80160. };
  80161. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  80162. };
  80163. // Create luminance
  80164. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  80165. var _this = this;
  80166. // Create luminance
  80167. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  80168. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  80169. var offsets = [];
  80170. this.luminancePostProcess.onApply = function (effect) {
  80171. var sU = (1.0 / _this.luminancePostProcess.width);
  80172. var sV = (1.0 / _this.luminancePostProcess.height);
  80173. offsets[0] = -0.5 * sU;
  80174. offsets[1] = 0.5 * sV;
  80175. offsets[2] = 0.5 * sU;
  80176. offsets[3] = 0.5 * sV;
  80177. offsets[4] = -0.5 * sU;
  80178. offsets[5] = -0.5 * sV;
  80179. offsets[6] = 0.5 * sU;
  80180. offsets[7] = -0.5 * sV;
  80181. effect.setArray2("lumOffsets", offsets);
  80182. };
  80183. // Add to pipeline
  80184. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  80185. // Create down sample luminance
  80186. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  80187. var size = Math.pow(3, i);
  80188. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  80189. if (i === 0) {
  80190. defines += "#define FINAL_DOWN_SAMPLER";
  80191. }
  80192. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  80193. this.luminanceDownSamplePostProcesses.push(postProcess);
  80194. }
  80195. // Create callbacks and add effects
  80196. var lastLuminance = this.luminancePostProcess;
  80197. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  80198. var downSampleOffsets = new Array(18);
  80199. pp.onApply = function (effect) {
  80200. if (!lastLuminance) {
  80201. return;
  80202. }
  80203. var id = 0;
  80204. for (var x = -1; x < 2; x++) {
  80205. for (var y = -1; y < 2; y++) {
  80206. downSampleOffsets[id] = x / lastLuminance.width;
  80207. downSampleOffsets[id + 1] = y / lastLuminance.height;
  80208. id += 2;
  80209. }
  80210. }
  80211. effect.setArray2("dsOffsets", downSampleOffsets);
  80212. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  80213. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  80214. lastLuminance = _this.luminancePostProcess;
  80215. }
  80216. else {
  80217. lastLuminance = pp;
  80218. }
  80219. };
  80220. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  80221. pp.onAfterRender = function (effect) {
  80222. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  80223. 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);
  80224. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  80225. };
  80226. }
  80227. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  80228. });
  80229. };
  80230. // Create HDR post-process
  80231. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  80232. var _this = this;
  80233. 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);
  80234. var outputLiminance = 1;
  80235. var time = 0;
  80236. var lastTime = 0;
  80237. this.hdrPostProcess.onApply = function (effect) {
  80238. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  80239. time += scene.getEngine().getDeltaTime();
  80240. if (outputLiminance < 0) {
  80241. outputLiminance = _this._hdrCurrentLuminance;
  80242. }
  80243. else {
  80244. var dt = (lastTime - time) / 1000.0;
  80245. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  80246. outputLiminance += _this.hdrDecreaseRate * dt;
  80247. }
  80248. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  80249. outputLiminance -= _this.hdrIncreaseRate * dt;
  80250. }
  80251. else {
  80252. outputLiminance = _this._hdrCurrentLuminance;
  80253. }
  80254. }
  80255. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  80256. effect.setFloat("averageLuminance", outputLiminance);
  80257. lastTime = time;
  80258. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  80259. };
  80260. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  80261. };
  80262. // Create lens flare post-process
  80263. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  80264. var _this = this;
  80265. 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);
  80266. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  80267. this._createBlurPostProcesses(scene, ratio / 4, 2);
  80268. 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);
  80269. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  80270. var resolution = new BABYLON.Vector2(0, 0);
  80271. // Lens flare
  80272. this.lensFlarePostProcess.onApply = function (effect) {
  80273. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  80274. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  80275. effect.setFloat("strength", _this.lensFlareStrength);
  80276. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  80277. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  80278. // Shift
  80279. resolution.x = _this.lensFlarePostProcess.width;
  80280. resolution.y = _this.lensFlarePostProcess.height;
  80281. effect.setVector2("resolution", resolution);
  80282. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  80283. };
  80284. // Compose
  80285. 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);
  80286. 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);
  80287. this.lensFlareComposePostProcess.onApply = function (effect) {
  80288. if (!_this._scene.activeCamera) {
  80289. return;
  80290. }
  80291. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  80292. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  80293. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  80294. // Lens start rotation matrix
  80295. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  80296. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  80297. 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));
  80298. camRot *= 4.0;
  80299. 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);
  80300. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  80301. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  80302. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  80303. };
  80304. };
  80305. // Create depth-of-field post-process
  80306. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  80307. var _this = this;
  80308. 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);
  80309. this.depthOfFieldPostProcess.onApply = function (effect) {
  80310. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  80311. effect.setTexture("depthSampler", _this._getDepthTexture());
  80312. effect.setFloat("distance", _this.depthOfFieldDistance);
  80313. };
  80314. // Add to pipeline
  80315. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  80316. };
  80317. // Create motion blur post-process
  80318. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  80319. var _this = this;
  80320. 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);
  80321. var motionScale = 0;
  80322. var prevViewProjection = BABYLON.Matrix.Identity();
  80323. var invViewProjection = BABYLON.Matrix.Identity();
  80324. var viewProjection = BABYLON.Matrix.Identity();
  80325. var screenSize = BABYLON.Vector2.Zero();
  80326. this.motionBlurPostProcess.onApply = function (effect) {
  80327. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  80328. viewProjection.invertToRef(invViewProjection);
  80329. effect.setMatrix("inverseViewProjection", invViewProjection);
  80330. effect.setMatrix("prevViewProjection", prevViewProjection);
  80331. prevViewProjection = viewProjection;
  80332. screenSize.x = _this.motionBlurPostProcess.width;
  80333. screenSize.y = _this.motionBlurPostProcess.height;
  80334. effect.setVector2("screenSize", screenSize);
  80335. motionScale = scene.getEngine().getFps() / 60.0;
  80336. effect.setFloat("motionScale", motionScale);
  80337. effect.setFloat("motionStrength", _this.motionStrength);
  80338. effect.setTexture("depthSampler", _this._getDepthTexture());
  80339. };
  80340. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  80341. };
  80342. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  80343. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  80344. var renderer = this._scene.enableGeometryBufferRenderer();
  80345. return renderer.getGBuffer().textures[0];
  80346. }
  80347. return this._scene.enableDepthRenderer().getDepthMap();
  80348. };
  80349. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  80350. for (var i = 0; i < this._cameras.length; i++) {
  80351. var camera = this._cameras[i];
  80352. if (this.originalPostProcess) {
  80353. this.originalPostProcess.dispose(camera);
  80354. }
  80355. if (this.downSampleX4PostProcess) {
  80356. this.downSampleX4PostProcess.dispose(camera);
  80357. }
  80358. if (this.brightPassPostProcess) {
  80359. this.brightPassPostProcess.dispose(camera);
  80360. }
  80361. if (this.textureAdderPostProcess) {
  80362. this.textureAdderPostProcess.dispose(camera);
  80363. }
  80364. if (this.textureAdderFinalPostProcess) {
  80365. this.textureAdderFinalPostProcess.dispose(camera);
  80366. }
  80367. if (this.volumetricLightPostProcess) {
  80368. this.volumetricLightPostProcess.dispose(camera);
  80369. }
  80370. if (this.volumetricLightSmoothXPostProcess) {
  80371. this.volumetricLightSmoothXPostProcess.dispose(camera);
  80372. }
  80373. if (this.volumetricLightSmoothYPostProcess) {
  80374. this.volumetricLightSmoothYPostProcess.dispose(camera);
  80375. }
  80376. if (this.volumetricLightMergePostProces) {
  80377. this.volumetricLightMergePostProces.dispose(camera);
  80378. }
  80379. if (this.volumetricLightFinalPostProcess) {
  80380. this.volumetricLightFinalPostProcess.dispose(camera);
  80381. }
  80382. if (this.lensFlarePostProcess) {
  80383. this.lensFlarePostProcess.dispose(camera);
  80384. }
  80385. if (this.lensFlareComposePostProcess) {
  80386. this.lensFlareComposePostProcess.dispose(camera);
  80387. }
  80388. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  80389. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  80390. }
  80391. if (this.luminancePostProcess) {
  80392. this.luminancePostProcess.dispose(camera);
  80393. }
  80394. if (this.hdrPostProcess) {
  80395. this.hdrPostProcess.dispose(camera);
  80396. }
  80397. if (this.hdrFinalPostProcess) {
  80398. this.hdrFinalPostProcess.dispose(camera);
  80399. }
  80400. if (this.depthOfFieldPostProcess) {
  80401. this.depthOfFieldPostProcess.dispose(camera);
  80402. }
  80403. if (this.motionBlurPostProcess) {
  80404. this.motionBlurPostProcess.dispose(camera);
  80405. }
  80406. if (this.fxaaPostProcess) {
  80407. this.fxaaPostProcess.dispose(camera);
  80408. }
  80409. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  80410. this.blurHPostProcesses[j].dispose(camera);
  80411. }
  80412. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  80413. this.blurVPostProcesses[j].dispose(camera);
  80414. }
  80415. }
  80416. this.originalPostProcess = null;
  80417. this.downSampleX4PostProcess = null;
  80418. this.brightPassPostProcess = null;
  80419. this.textureAdderPostProcess = null;
  80420. this.textureAdderFinalPostProcess = null;
  80421. this.volumetricLightPostProcess = null;
  80422. this.volumetricLightSmoothXPostProcess = null;
  80423. this.volumetricLightSmoothYPostProcess = null;
  80424. this.volumetricLightMergePostProces = null;
  80425. this.volumetricLightFinalPostProcess = null;
  80426. this.lensFlarePostProcess = null;
  80427. this.lensFlareComposePostProcess = null;
  80428. this.luminancePostProcess = null;
  80429. this.hdrPostProcess = null;
  80430. this.hdrFinalPostProcess = null;
  80431. this.depthOfFieldPostProcess = null;
  80432. this.motionBlurPostProcess = null;
  80433. this.fxaaPostProcess = null;
  80434. this.luminanceDownSamplePostProcesses = [];
  80435. this.blurHPostProcesses = [];
  80436. this.blurVPostProcesses = [];
  80437. };
  80438. /**
  80439. * Dispose of the pipeline and stop all post processes
  80440. */
  80441. StandardRenderingPipeline.prototype.dispose = function () {
  80442. this._disposePostProcesses();
  80443. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80444. _super.prototype.dispose.call(this);
  80445. };
  80446. /**
  80447. * Serialize the rendering pipeline (Used when exporting)
  80448. * @returns the serialized object
  80449. */
  80450. StandardRenderingPipeline.prototype.serialize = function () {
  80451. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80452. if (this.sourceLight) {
  80453. serializationObject.sourceLightId = this.sourceLight.id;
  80454. }
  80455. serializationObject.customType = "StandardRenderingPipeline";
  80456. return serializationObject;
  80457. };
  80458. /**
  80459. * Parse the serialized pipeline
  80460. * @param source Source pipeline.
  80461. * @param scene The scene to load the pipeline to.
  80462. * @param rootUrl The URL of the serialized pipeline.
  80463. * @returns An instantiated pipeline from the serialized object.
  80464. */
  80465. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  80466. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  80467. if (source.sourceLightId) {
  80468. p.sourceLight = scene.getLightByID(source.sourceLightId);
  80469. }
  80470. return p;
  80471. };
  80472. // Luminance steps
  80473. StandardRenderingPipeline.LuminanceSteps = 6;
  80474. __decorate([
  80475. BABYLON.serialize()
  80476. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  80477. __decorate([
  80478. BABYLON.serialize()
  80479. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  80480. __decorate([
  80481. BABYLON.serialize()
  80482. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  80483. __decorate([
  80484. BABYLON.serialize()
  80485. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  80486. __decorate([
  80487. BABYLON.serializeAsTexture("lensTexture")
  80488. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  80489. __decorate([
  80490. BABYLON.serialize()
  80491. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  80492. __decorate([
  80493. BABYLON.serialize()
  80494. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  80495. __decorate([
  80496. BABYLON.serialize()
  80497. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  80498. __decorate([
  80499. BABYLON.serialize()
  80500. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  80501. __decorate([
  80502. BABYLON.serialize()
  80503. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  80504. __decorate([
  80505. BABYLON.serialize()
  80506. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  80507. __decorate([
  80508. BABYLON.serializeAsTexture("lensColorTexture")
  80509. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  80510. __decorate([
  80511. BABYLON.serialize()
  80512. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  80513. __decorate([
  80514. BABYLON.serialize()
  80515. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  80516. __decorate([
  80517. BABYLON.serialize()
  80518. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  80519. __decorate([
  80520. BABYLON.serialize()
  80521. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  80522. __decorate([
  80523. BABYLON.serializeAsTexture("lensStarTexture")
  80524. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  80525. __decorate([
  80526. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  80527. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  80528. __decorate([
  80529. BABYLON.serialize()
  80530. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  80531. __decorate([
  80532. BABYLON.serialize()
  80533. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  80534. __decorate([
  80535. BABYLON.serialize()
  80536. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  80537. __decorate([
  80538. BABYLON.serialize()
  80539. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  80540. __decorate([
  80541. BABYLON.serialize()
  80542. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  80543. __decorate([
  80544. BABYLON.serialize()
  80545. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  80546. __decorate([
  80547. BABYLON.serialize()
  80548. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  80549. __decorate([
  80550. BABYLON.serialize()
  80551. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  80552. __decorate([
  80553. BABYLON.serialize()
  80554. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  80555. __decorate([
  80556. BABYLON.serialize()
  80557. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  80558. __decorate([
  80559. BABYLON.serialize()
  80560. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  80561. __decorate([
  80562. BABYLON.serialize()
  80563. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  80564. __decorate([
  80565. BABYLON.serialize()
  80566. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  80567. __decorate([
  80568. BABYLON.serialize()
  80569. ], StandardRenderingPipeline.prototype, "samples", null);
  80570. return StandardRenderingPipeline;
  80571. }(BABYLON.PostProcessRenderPipeline));
  80572. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  80573. })(BABYLON || (BABYLON = {}));
  80574. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  80575. var BABYLON;
  80576. (function (BABYLON) {
  80577. var FxaaPostProcess = /** @class */ (function (_super) {
  80578. __extends(FxaaPostProcess, _super);
  80579. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  80580. if (camera === void 0) { camera = null; }
  80581. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80582. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  80583. var defines = _this._getDefines();
  80584. _this.updateEffect(defines);
  80585. _this.onApplyObservable.add(function (effect) {
  80586. var texelSize = _this.texelSize;
  80587. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  80588. });
  80589. return _this;
  80590. }
  80591. FxaaPostProcess.prototype._getDefines = function () {
  80592. var engine = this.getEngine();
  80593. if (!engine) {
  80594. return null;
  80595. }
  80596. var glInfo = engine.getGlInfo();
  80597. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  80598. return "#define MALI 1\n";
  80599. }
  80600. return null;
  80601. };
  80602. return FxaaPostProcess;
  80603. }(BABYLON.PostProcess));
  80604. BABYLON.FxaaPostProcess = FxaaPostProcess;
  80605. })(BABYLON || (BABYLON = {}));
  80606. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  80607. var BABYLON;
  80608. (function (BABYLON) {
  80609. /**
  80610. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  80611. */
  80612. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  80613. __extends(ChromaticAberrationPostProcess, _super);
  80614. /**
  80615. * Creates a new instance ChromaticAberrationPostProcess
  80616. * @param name The name of the effect.
  80617. * @param screenWidth The width of the screen to apply the effect on.
  80618. * @param screenHeight The height of the screen to apply the effect on.
  80619. * @param options The required width/height ratio to downsize to before computing the render pass.
  80620. * @param camera The camera to apply the render pass to.
  80621. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80622. * @param engine The engine which the post process will be applied. (default: current engine)
  80623. * @param reusable If the post process can be reused on the same frame. (default: false)
  80624. * @param textureType Type of textures used when performing the post process. (default: 0)
  80625. * @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)
  80626. */
  80627. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80628. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80629. if (blockCompilation === void 0) { blockCompilation = false; }
  80630. 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;
  80631. /**
  80632. * The amount of seperation of rgb channels (default: 30)
  80633. */
  80634. _this.aberrationAmount = 30;
  80635. /**
  80636. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  80637. */
  80638. _this.radialIntensity = 0;
  80639. /**
  80640. * 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))
  80641. */
  80642. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  80643. /**
  80644. * 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))
  80645. */
  80646. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  80647. _this.onApplyObservable.add(function (effect) {
  80648. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  80649. effect.setFloat('screen_width', screenWidth);
  80650. effect.setFloat('screen_height', screenHeight);
  80651. effect.setFloat('radialIntensity', _this.radialIntensity);
  80652. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  80653. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  80654. });
  80655. return _this;
  80656. }
  80657. return ChromaticAberrationPostProcess;
  80658. }(BABYLON.PostProcess));
  80659. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  80660. })(BABYLON || (BABYLON = {}));
  80661. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  80662. var BABYLON;
  80663. (function (BABYLON) {
  80664. /**
  80665. * The GrainPostProcess adds noise to the image at mid luminance levels
  80666. */
  80667. var GrainPostProcess = /** @class */ (function (_super) {
  80668. __extends(GrainPostProcess, _super);
  80669. /**
  80670. * Creates a new instance of @see GrainPostProcess
  80671. * @param name The name of the effect.
  80672. * @param options The required width/height ratio to downsize to before computing the render pass.
  80673. * @param camera The camera to apply the render pass to.
  80674. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80675. * @param engine The engine which the post process will be applied. (default: current engine)
  80676. * @param reusable If the post process can be reused on the same frame. (default: false)
  80677. * @param textureType Type of textures used when performing the post process. (default: 0)
  80678. * @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)
  80679. */
  80680. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80681. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80682. if (blockCompilation === void 0) { blockCompilation = false; }
  80683. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80684. /**
  80685. * The intensity of the grain added (default: 30)
  80686. */
  80687. _this.intensity = 30;
  80688. /**
  80689. * If the grain should be randomized on every frame
  80690. */
  80691. _this.animated = false;
  80692. _this.onApplyObservable.add(function (effect) {
  80693. effect.setFloat('intensity', _this.intensity);
  80694. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  80695. });
  80696. return _this;
  80697. }
  80698. return GrainPostProcess;
  80699. }(BABYLON.PostProcess));
  80700. BABYLON.GrainPostProcess = GrainPostProcess;
  80701. })(BABYLON || (BABYLON = {}));
  80702. //# sourceMappingURL=babylon.grainPostProcess.js.map
  80703. var BABYLON;
  80704. (function (BABYLON) {
  80705. /**
  80706. * The SharpenPostProcess applies a sharpen kernel to every pixel
  80707. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  80708. */
  80709. var SharpenPostProcess = /** @class */ (function (_super) {
  80710. __extends(SharpenPostProcess, _super);
  80711. /**
  80712. * Creates a new instance ConvolutionPostProcess
  80713. * @param name The name of the effect.
  80714. * @param options The required width/height ratio to downsize to before computing the render pass.
  80715. * @param camera The camera to apply the render pass to.
  80716. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80717. * @param engine The engine which the post process will be applied. (default: current engine)
  80718. * @param reusable If the post process can be reused on the same frame. (default: false)
  80719. * @param textureType Type of textures used when performing the post process. (default: 0)
  80720. * @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)
  80721. */
  80722. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80723. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80724. if (blockCompilation === void 0) { blockCompilation = false; }
  80725. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80726. /**
  80727. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  80728. */
  80729. _this.colorAmount = 1.0;
  80730. /**
  80731. * How much sharpness should be applied (default: 0.3)
  80732. */
  80733. _this.edgeAmount = 0.3;
  80734. _this.onApply = function (effect) {
  80735. effect.setFloat2("screenSize", _this.width, _this.height);
  80736. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  80737. };
  80738. return _this;
  80739. }
  80740. return SharpenPostProcess;
  80741. }(BABYLON.PostProcess));
  80742. BABYLON.SharpenPostProcess = SharpenPostProcess;
  80743. })(BABYLON || (BABYLON = {}));
  80744. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  80745. var BABYLON;
  80746. (function (BABYLON) {
  80747. /**
  80748. * The Blur Post Process which blurs an image based on a kernel and direction.
  80749. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  80750. */
  80751. var BlurPostProcess = /** @class */ (function (_super) {
  80752. __extends(BlurPostProcess, _super);
  80753. /**
  80754. * Creates a new instance BlurPostProcess
  80755. * @param name The name of the effect.
  80756. * @param direction The direction in which to blur the image.
  80757. * @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.
  80758. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  80759. * @param camera The camera to apply the render pass to.
  80760. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80761. * @param engine The engine which the post process will be applied. (default: current engine)
  80762. * @param reusable If the post process can be reused on the same frame. (default: false)
  80763. * @param textureType Type of textures used when performing the post process. (default: 0)
  80764. * @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)
  80765. */
  80766. function BlurPostProcess(name,
  80767. /** The direction in which to blur the image. */
  80768. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  80769. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80770. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80771. if (defines === void 0) { defines = ""; }
  80772. if (blockCompilation === void 0) { blockCompilation = false; }
  80773. 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;
  80774. _this.direction = direction;
  80775. _this.blockCompilation = blockCompilation;
  80776. _this._packedFloat = false;
  80777. _this._staticDefines = "";
  80778. _this._staticDefines = defines;
  80779. _this.onApplyObservable.add(function (effect) {
  80780. if (_this._outputTexture) {
  80781. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  80782. }
  80783. else {
  80784. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  80785. }
  80786. });
  80787. _this.kernel = kernel;
  80788. return _this;
  80789. }
  80790. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  80791. /**
  80792. * Gets the length in pixels of the blur sample region
  80793. */
  80794. get: function () {
  80795. return this._idealKernel;
  80796. },
  80797. /**
  80798. * Sets the length in pixels of the blur sample region
  80799. */
  80800. set: function (v) {
  80801. if (this._idealKernel === v) {
  80802. return;
  80803. }
  80804. v = Math.max(v, 1);
  80805. this._idealKernel = v;
  80806. this._kernel = this._nearestBestKernel(v);
  80807. if (!this.blockCompilation) {
  80808. this._updateParameters();
  80809. }
  80810. },
  80811. enumerable: true,
  80812. configurable: true
  80813. });
  80814. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  80815. /**
  80816. * Gets wether or not the blur is unpacking/repacking floats
  80817. */
  80818. get: function () {
  80819. return this._packedFloat;
  80820. },
  80821. /**
  80822. * Sets wether or not the blur needs to unpack/repack floats
  80823. */
  80824. set: function (v) {
  80825. if (this._packedFloat === v) {
  80826. return;
  80827. }
  80828. this._packedFloat = v;
  80829. if (!this.blockCompilation) {
  80830. this._updateParameters();
  80831. }
  80832. },
  80833. enumerable: true,
  80834. configurable: true
  80835. });
  80836. /**
  80837. * Updates the effect with the current post process compile time values and recompiles the shader.
  80838. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80839. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80840. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80841. * @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
  80842. * @param onCompiled Called when the shader has been compiled.
  80843. * @param onError Called if there is an error when compiling a shader.
  80844. */
  80845. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80846. if (defines === void 0) { defines = null; }
  80847. if (uniforms === void 0) { uniforms = null; }
  80848. if (samplers === void 0) { samplers = null; }
  80849. this._updateParameters(onCompiled, onError);
  80850. };
  80851. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  80852. // Generate sampling offsets and weights
  80853. var N = this._kernel;
  80854. var centerIndex = (N - 1) / 2;
  80855. // Generate Gaussian sampling weights over kernel
  80856. var offsets = [];
  80857. var weights = [];
  80858. var totalWeight = 0;
  80859. for (var i = 0; i < N; i++) {
  80860. var u = i / (N - 1);
  80861. var w = this._gaussianWeight(u * 2.0 - 1);
  80862. offsets[i] = (i - centerIndex);
  80863. weights[i] = w;
  80864. totalWeight += w;
  80865. }
  80866. // Normalize weights
  80867. for (var i = 0; i < weights.length; i++) {
  80868. weights[i] /= totalWeight;
  80869. }
  80870. // Optimize: combine samples to take advantage of hardware linear sampling
  80871. // Walk from left to center, combining pairs (symmetrically)
  80872. var linearSamplingWeights = [];
  80873. var linearSamplingOffsets = [];
  80874. var linearSamplingMap = [];
  80875. for (var i = 0; i <= centerIndex; i += 2) {
  80876. var j = Math.min(i + 1, Math.floor(centerIndex));
  80877. var singleCenterSample = i === j;
  80878. if (singleCenterSample) {
  80879. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80880. }
  80881. else {
  80882. var sharedCell = j === centerIndex;
  80883. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  80884. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  80885. if (offsetLinear === 0) {
  80886. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80887. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  80888. }
  80889. else {
  80890. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  80891. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  80892. }
  80893. }
  80894. }
  80895. for (var i = 0; i < linearSamplingMap.length; i++) {
  80896. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  80897. linearSamplingWeights[i] = linearSamplingMap[i].w;
  80898. }
  80899. // Replace with optimized
  80900. offsets = linearSamplingOffsets;
  80901. weights = linearSamplingWeights;
  80902. // Generate shaders
  80903. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  80904. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  80905. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  80906. var defines = "";
  80907. defines += this._staticDefines;
  80908. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  80909. if (this._staticDefines.indexOf("DOF") != -1) {
  80910. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  80911. varyingCount--;
  80912. }
  80913. for (var i = 0; i < varyingCount; i++) {
  80914. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  80915. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  80916. }
  80917. var depCount = 0;
  80918. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  80919. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  80920. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  80921. depCount++;
  80922. }
  80923. if (this.packedFloat) {
  80924. defines += "#define PACKEDFLOAT 1";
  80925. }
  80926. this.blockCompilation = false;
  80927. _super.prototype.updateEffect.call(this, defines, null, null, {
  80928. varyingCount: varyingCount,
  80929. depCount: depCount
  80930. }, onCompiled, onError);
  80931. };
  80932. /**
  80933. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  80934. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  80935. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  80936. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  80937. * The gaps between physical kernels are compensated for in the weighting of the samples
  80938. * @param idealKernel Ideal blur kernel.
  80939. * @return Nearest best kernel.
  80940. */
  80941. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  80942. var v = Math.round(idealKernel);
  80943. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  80944. var k = _a[_i];
  80945. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  80946. return Math.max(k, 3);
  80947. }
  80948. }
  80949. return Math.max(v, 3);
  80950. };
  80951. /**
  80952. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  80953. * @param x The point on the Gaussian distribution to sample.
  80954. * @return the value of the Gaussian function at x.
  80955. */
  80956. BlurPostProcess.prototype._gaussianWeight = function (x) {
  80957. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  80958. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  80959. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  80960. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  80961. // truncated at around 1.3% of peak strength.
  80962. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  80963. var sigma = (1 / 3);
  80964. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  80965. var exponent = -((x * x) / (2.0 * sigma * sigma));
  80966. var weight = (1.0 / denominator) * Math.exp(exponent);
  80967. return weight;
  80968. };
  80969. /**
  80970. * Generates a string that can be used as a floating point number in GLSL.
  80971. * @param x Value to print.
  80972. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  80973. * @return GLSL float string.
  80974. */
  80975. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  80976. if (decimalFigures === void 0) { decimalFigures = 8; }
  80977. return x.toFixed(decimalFigures).replace(/0+$/, '');
  80978. };
  80979. return BlurPostProcess;
  80980. }(BABYLON.PostProcess));
  80981. BABYLON.BlurPostProcess = BlurPostProcess;
  80982. })(BABYLON || (BABYLON = {}));
  80983. //# sourceMappingURL=babylon.blurPostProcess.js.map
  80984. var BABYLON;
  80985. (function (BABYLON) {
  80986. /**
  80987. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  80988. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  80989. * based on samples that have a large difference in distance than the center pixel.
  80990. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80991. */
  80992. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  80993. __extends(DepthOfFieldBlurPostProcess, _super);
  80994. /**
  80995. * Creates a new instance CircleOfConfusionPostProcess
  80996. * @param name The name of the effect.
  80997. * @param scene The scene the effect belongs to.
  80998. * @param direction The direction the blur should be applied.
  80999. * @param kernel The size of the kernel used to blur.
  81000. * @param options The required width/height ratio to downsize to before computing the render pass.
  81001. * @param camera The camera to apply the render pass to.
  81002. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  81003. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  81004. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81005. * @param engine The engine which the post process will be applied. (default: current engine)
  81006. * @param reusable If the post process can be reused on the same frame. (default: false)
  81007. * @param textureType Type of textures used when performing the post process. (default: 0)
  81008. * @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)
  81009. */
  81010. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  81011. if (imageToBlur === void 0) { imageToBlur = null; }
  81012. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81013. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81014. if (blockCompilation === void 0) { blockCompilation = false; }
  81015. 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;
  81016. _this.direction = direction;
  81017. _this.onApplyObservable.add(function (effect) {
  81018. if (imageToBlur != null) {
  81019. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  81020. }
  81021. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  81022. if (scene.activeCamera) {
  81023. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  81024. }
  81025. });
  81026. return _this;
  81027. }
  81028. return DepthOfFieldBlurPostProcess;
  81029. }(BABYLON.BlurPostProcess));
  81030. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  81031. })(BABYLON || (BABYLON = {}));
  81032. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  81033. var BABYLON;
  81034. (function (BABYLON) {
  81035. /**
  81036. * Options to be set when merging outputs from the default pipeline.
  81037. */
  81038. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  81039. function DepthOfFieldMergePostProcessOptions() {
  81040. }
  81041. return DepthOfFieldMergePostProcessOptions;
  81042. }());
  81043. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  81044. /**
  81045. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  81046. */
  81047. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  81048. __extends(DepthOfFieldMergePostProcess, _super);
  81049. /**
  81050. * Creates a new instance of DepthOfFieldMergePostProcess
  81051. * @param name The name of the effect.
  81052. * @param originalFromInput Post process which's input will be used for the merge.
  81053. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  81054. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  81055. * @param options The required width/height ratio to downsize to before computing the render pass.
  81056. * @param camera The camera to apply the render pass to.
  81057. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81058. * @param engine The engine which the post process will be applied. (default: current engine)
  81059. * @param reusable If the post process can be reused on the same frame. (default: false)
  81060. * @param textureType Type of textures used when performing the post process. (default: 0)
  81061. * @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)
  81062. */
  81063. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81064. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81065. if (blockCompilation === void 0) { blockCompilation = false; }
  81066. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  81067. _this.blurSteps = blurSteps;
  81068. _this.onApplyObservable.add(function (effect) {
  81069. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  81070. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  81071. blurSteps.forEach(function (step, index) {
  81072. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  81073. });
  81074. });
  81075. if (!blockCompilation) {
  81076. _this.updateEffect();
  81077. }
  81078. return _this;
  81079. }
  81080. /**
  81081. * Updates the effect with the current post process compile time values and recompiles the shader.
  81082. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  81083. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  81084. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  81085. * @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
  81086. * @param onCompiled Called when the shader has been compiled.
  81087. * @param onError Called if there is an error when compiling a shader.
  81088. */
  81089. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  81090. if (defines === void 0) { defines = null; }
  81091. if (uniforms === void 0) { uniforms = null; }
  81092. if (samplers === void 0) { samplers = null; }
  81093. if (!defines) {
  81094. defines = "";
  81095. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  81096. }
  81097. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  81098. };
  81099. return DepthOfFieldMergePostProcess;
  81100. }(BABYLON.PostProcess));
  81101. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  81102. })(BABYLON || (BABYLON = {}));
  81103. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  81104. var BABYLON;
  81105. (function (BABYLON) {
  81106. /**
  81107. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  81108. */
  81109. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  81110. __extends(CircleOfConfusionPostProcess, _super);
  81111. /**
  81112. * Creates a new instance CircleOfConfusionPostProcess
  81113. * @param name The name of the effect.
  81114. * @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.
  81115. * @param options The required width/height ratio to downsize to before computing the render pass.
  81116. * @param camera The camera to apply the render pass to.
  81117. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81118. * @param engine The engine which the post process will be applied. (default: current engine)
  81119. * @param reusable If the post process can be reused on the same frame. (default: false)
  81120. * @param textureType Type of textures used when performing the post process. (default: 0)
  81121. * @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)
  81122. */
  81123. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81124. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81125. if (blockCompilation === void 0) { blockCompilation = false; }
  81126. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  81127. /**
  81128. * 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.
  81129. */
  81130. _this.lensSize = 50;
  81131. /**
  81132. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  81133. */
  81134. _this.fStop = 1.4;
  81135. /**
  81136. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  81137. */
  81138. _this.focusDistance = 2000;
  81139. /**
  81140. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  81141. */
  81142. _this.focalLength = 50;
  81143. _this._depthTexture = null;
  81144. _this._depthTexture = depthTexture;
  81145. _this.onApplyObservable.add(function (effect) {
  81146. if (!_this._depthTexture) {
  81147. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  81148. return;
  81149. }
  81150. effect.setTexture("depthSampler", _this._depthTexture);
  81151. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  81152. var aperture = _this.lensSize / _this.fStop;
  81153. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  81154. effect.setFloat('focusDistance', _this.focusDistance);
  81155. effect.setFloat('cocPrecalculation', cocPrecalculation);
  81156. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  81157. });
  81158. return _this;
  81159. }
  81160. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  81161. /**
  81162. * 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.
  81163. */
  81164. set: function (value) {
  81165. this._depthTexture = value;
  81166. },
  81167. enumerable: true,
  81168. configurable: true
  81169. });
  81170. return CircleOfConfusionPostProcess;
  81171. }(BABYLON.PostProcess));
  81172. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  81173. })(BABYLON || (BABYLON = {}));
  81174. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  81175. var BABYLON;
  81176. (function (BABYLON) {
  81177. /**
  81178. * Specifies the level of max blur that should be applied when using the depth of field effect
  81179. */
  81180. var DepthOfFieldEffectBlurLevel;
  81181. (function (DepthOfFieldEffectBlurLevel) {
  81182. /**
  81183. * Subtle blur
  81184. */
  81185. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  81186. /**
  81187. * Medium blur
  81188. */
  81189. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  81190. /**
  81191. * Large blur
  81192. */
  81193. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  81194. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  81195. ;
  81196. /**
  81197. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  81198. */
  81199. var DepthOfFieldEffect = /** @class */ (function (_super) {
  81200. __extends(DepthOfFieldEffect, _super);
  81201. /**
  81202. * Creates a new instance DepthOfFieldEffect
  81203. * @param scene The scene the effect belongs to.
  81204. * @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.
  81205. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  81206. * @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)
  81207. */
  81208. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  81209. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  81210. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  81211. if (blockCompilation === void 0) { blockCompilation = false; }
  81212. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  81213. return _this._effects;
  81214. }, true) || this;
  81215. /**
  81216. * @hidden Internal post processes in depth of field effect
  81217. */
  81218. _this._effects = [];
  81219. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  81220. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  81221. // 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)
  81222. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  81223. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  81224. _this._depthOfFieldBlurY = [];
  81225. _this._depthOfFieldBlurX = [];
  81226. var blurCount = 1;
  81227. var kernelSize = 15;
  81228. switch (blurLevel) {
  81229. case DepthOfFieldEffectBlurLevel.High: {
  81230. blurCount = 3;
  81231. kernelSize = 51;
  81232. break;
  81233. }
  81234. case DepthOfFieldEffectBlurLevel.Medium: {
  81235. blurCount = 2;
  81236. kernelSize = 31;
  81237. break;
  81238. }
  81239. default: {
  81240. kernelSize = 15;
  81241. blurCount = 1;
  81242. break;
  81243. }
  81244. }
  81245. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  81246. var ratio = 1.0;
  81247. for (var i = 0; i < blurCount; i++) {
  81248. 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);
  81249. blurY.autoClear = false;
  81250. ratio = 0.75 / Math.pow(2, i);
  81251. 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);
  81252. blurX.autoClear = false;
  81253. _this._depthOfFieldBlurY.push(blurY);
  81254. _this._depthOfFieldBlurX.push(blurX);
  81255. }
  81256. // Set all post processes on the effect.
  81257. _this._effects = [_this._circleOfConfusion];
  81258. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  81259. _this._effects.push(_this._depthOfFieldBlurY[i]);
  81260. _this._effects.push(_this._depthOfFieldBlurX[i]);
  81261. }
  81262. // Merge blurred images with original image based on circleOfConfusion
  81263. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  81264. _this._dofMerge.autoClear = false;
  81265. _this._effects.push(_this._dofMerge);
  81266. return _this;
  81267. }
  81268. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  81269. get: function () {
  81270. return this._circleOfConfusion.focalLength;
  81271. },
  81272. /**
  81273. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  81274. */
  81275. set: function (value) {
  81276. this._circleOfConfusion.focalLength = value;
  81277. },
  81278. enumerable: true,
  81279. configurable: true
  81280. });
  81281. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  81282. get: function () {
  81283. return this._circleOfConfusion.fStop;
  81284. },
  81285. /**
  81286. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  81287. */
  81288. set: function (value) {
  81289. this._circleOfConfusion.fStop = value;
  81290. },
  81291. enumerable: true,
  81292. configurable: true
  81293. });
  81294. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  81295. get: function () {
  81296. return this._circleOfConfusion.focusDistance;
  81297. },
  81298. /**
  81299. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  81300. */
  81301. set: function (value) {
  81302. this._circleOfConfusion.focusDistance = value;
  81303. },
  81304. enumerable: true,
  81305. configurable: true
  81306. });
  81307. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  81308. get: function () {
  81309. return this._circleOfConfusion.lensSize;
  81310. },
  81311. /**
  81312. * 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.
  81313. */
  81314. set: function (value) {
  81315. this._circleOfConfusion.lensSize = value;
  81316. },
  81317. enumerable: true,
  81318. configurable: true
  81319. });
  81320. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  81321. /**
  81322. * 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.
  81323. */
  81324. set: function (value) {
  81325. this._circleOfConfusion.depthTexture = value;
  81326. },
  81327. enumerable: true,
  81328. configurable: true
  81329. });
  81330. /**
  81331. * Disposes each of the internal effects for a given camera.
  81332. * @param camera The camera to dispose the effect on.
  81333. */
  81334. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  81335. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81336. this._effects[effectIndex].dispose(camera);
  81337. }
  81338. };
  81339. /**
  81340. * @hidden Internal
  81341. */
  81342. DepthOfFieldEffect.prototype._updateEffects = function () {
  81343. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81344. this._effects[effectIndex].updateEffect();
  81345. }
  81346. };
  81347. /**
  81348. * Internal
  81349. * @returns if all the contained post processes are ready.
  81350. * @hidden
  81351. */
  81352. DepthOfFieldEffect.prototype._isReady = function () {
  81353. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81354. if (!this._effects[effectIndex].isReady()) {
  81355. return false;
  81356. }
  81357. }
  81358. return true;
  81359. };
  81360. return DepthOfFieldEffect;
  81361. }(BABYLON.PostProcessRenderEffect));
  81362. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  81363. })(BABYLON || (BABYLON = {}));
  81364. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  81365. var BABYLON;
  81366. (function (BABYLON) {
  81367. /**
  81368. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  81369. */
  81370. var BloomMergePostProcess = /** @class */ (function (_super) {
  81371. __extends(BloomMergePostProcess, _super);
  81372. /**
  81373. * Creates a new instance of @see BloomMergePostProcess
  81374. * @param name The name of the effect.
  81375. * @param originalFromInput Post process which's input will be used for the merge.
  81376. * @param blurred Blurred highlights post process which's output will be used.
  81377. * @param weight Weight of the bloom to be added to the original input.
  81378. * @param options The required width/height ratio to downsize to before computing the render pass.
  81379. * @param camera The camera to apply the render pass to.
  81380. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81381. * @param engine The engine which the post process will be applied. (default: current engine)
  81382. * @param reusable If the post process can be reused on the same frame. (default: false)
  81383. * @param textureType Type of textures used when performing the post process. (default: 0)
  81384. * @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)
  81385. */
  81386. function BloomMergePostProcess(name, originalFromInput, blurred,
  81387. /** Weight of the bloom to be added to the original input. */
  81388. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81389. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81390. if (blockCompilation === void 0) { blockCompilation = false; }
  81391. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  81392. _this.weight = weight;
  81393. _this.onApplyObservable.add(function (effect) {
  81394. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  81395. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  81396. effect.setFloat("bloomWeight", _this.weight);
  81397. });
  81398. if (!blockCompilation) {
  81399. _this.updateEffect();
  81400. }
  81401. return _this;
  81402. }
  81403. return BloomMergePostProcess;
  81404. }(BABYLON.PostProcess));
  81405. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  81406. })(BABYLON || (BABYLON = {}));
  81407. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  81408. var BABYLON;
  81409. (function (BABYLON) {
  81410. /**
  81411. * 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.
  81412. */
  81413. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  81414. __extends(ExtractHighlightsPostProcess, _super);
  81415. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81416. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81417. if (blockCompilation === void 0) { blockCompilation = false; }
  81418. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  81419. /**
  81420. * The luminance threshold, pixels below this value will be set to black.
  81421. */
  81422. _this.threshold = 0.9;
  81423. /** @hidden */
  81424. _this._exposure = 1;
  81425. /**
  81426. * Post process which has the input texture to be used when performing highlight extraction
  81427. * @hidden
  81428. */
  81429. _this._inputPostProcess = null;
  81430. _this.onApplyObservable.add(function (effect) {
  81431. if (_this._inputPostProcess) {
  81432. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  81433. }
  81434. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  81435. effect.setFloat('exposure', _this._exposure);
  81436. });
  81437. return _this;
  81438. }
  81439. return ExtractHighlightsPostProcess;
  81440. }(BABYLON.PostProcess));
  81441. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  81442. })(BABYLON || (BABYLON = {}));
  81443. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  81444. var BABYLON;
  81445. (function (BABYLON) {
  81446. /**
  81447. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  81448. */
  81449. var BloomEffect = /** @class */ (function (_super) {
  81450. __extends(BloomEffect, _super);
  81451. /**
  81452. * Creates a new instance of @see BloomEffect
  81453. * @param scene The scene the effect belongs to.
  81454. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  81455. * @param bloomKernel The size of the kernel to be used when applying the blur.
  81456. * @param bloomWeight The the strength of bloom.
  81457. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  81458. * @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)
  81459. */
  81460. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  81461. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  81462. if (blockCompilation === void 0) { blockCompilation = false; }
  81463. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  81464. return _this._effects;
  81465. }, true) || this;
  81466. _this.bloomScale = bloomScale;
  81467. /**
  81468. * @hidden Internal
  81469. */
  81470. _this._effects = [];
  81471. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  81472. _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);
  81473. _this._blurX.alwaysForcePOT = true;
  81474. _this._blurX.autoClear = false;
  81475. _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);
  81476. _this._blurY.alwaysForcePOT = true;
  81477. _this._blurY.autoClear = false;
  81478. _this.kernel = bloomKernel;
  81479. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  81480. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  81481. _this._merge.autoClear = false;
  81482. _this._effects.push(_this._merge);
  81483. return _this;
  81484. }
  81485. Object.defineProperty(BloomEffect.prototype, "threshold", {
  81486. /**
  81487. * The luminance threshold to find bright areas of the image to bloom.
  81488. */
  81489. get: function () {
  81490. return this._downscale.threshold;
  81491. },
  81492. set: function (value) {
  81493. this._downscale.threshold = value;
  81494. },
  81495. enumerable: true,
  81496. configurable: true
  81497. });
  81498. Object.defineProperty(BloomEffect.prototype, "weight", {
  81499. /**
  81500. * The strength of the bloom.
  81501. */
  81502. get: function () {
  81503. return this._merge.weight;
  81504. },
  81505. set: function (value) {
  81506. this._merge.weight = value;
  81507. },
  81508. enumerable: true,
  81509. configurable: true
  81510. });
  81511. Object.defineProperty(BloomEffect.prototype, "kernel", {
  81512. /**
  81513. * Specifies the size of the bloom blur kernel, relative to the final output size
  81514. */
  81515. get: function () {
  81516. return this._blurX.kernel / this.bloomScale;
  81517. },
  81518. set: function (value) {
  81519. this._blurX.kernel = value * this.bloomScale;
  81520. this._blurY.kernel = value * this.bloomScale;
  81521. },
  81522. enumerable: true,
  81523. configurable: true
  81524. });
  81525. /**
  81526. * Disposes each of the internal effects for a given camera.
  81527. * @param camera The camera to dispose the effect on.
  81528. */
  81529. BloomEffect.prototype.disposeEffects = function (camera) {
  81530. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81531. this._effects[effectIndex].dispose(camera);
  81532. }
  81533. };
  81534. /**
  81535. * @hidden Internal
  81536. */
  81537. BloomEffect.prototype._updateEffects = function () {
  81538. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81539. this._effects[effectIndex].updateEffect();
  81540. }
  81541. };
  81542. /**
  81543. * Internal
  81544. * @returns if all the contained post processes are ready.
  81545. * @hidden
  81546. */
  81547. BloomEffect.prototype._isReady = function () {
  81548. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81549. if (!this._effects[effectIndex].isReady()) {
  81550. return false;
  81551. }
  81552. }
  81553. return true;
  81554. };
  81555. return BloomEffect;
  81556. }(BABYLON.PostProcessRenderEffect));
  81557. BABYLON.BloomEffect = BloomEffect;
  81558. })(BABYLON || (BABYLON = {}));
  81559. //# sourceMappingURL=babylon.bloomEffect.js.map
  81560. var BABYLON;
  81561. (function (BABYLON) {
  81562. /**
  81563. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  81564. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  81565. */
  81566. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  81567. __extends(DefaultRenderingPipeline, _super);
  81568. /**
  81569. * @constructor
  81570. * @param {string} name - The rendering pipeline name (default: "")
  81571. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  81572. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  81573. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  81574. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  81575. */
  81576. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  81577. if (name === void 0) { name = ""; }
  81578. if (hdr === void 0) { hdr = true; }
  81579. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  81580. if (automaticBuild === void 0) { automaticBuild = true; }
  81581. var _this = _super.call(this, scene.getEngine(), name) || this;
  81582. _this._camerasToBeAttached = [];
  81583. /**
  81584. * ID of the sharpen post process,
  81585. */
  81586. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  81587. /**
  81588. * ID of the image processing post process;
  81589. */
  81590. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  81591. /**
  81592. * ID of the Fast Approximate Anti-Aliasing post process;
  81593. */
  81594. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  81595. /**
  81596. * ID of the chromatic aberration post process,
  81597. */
  81598. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  81599. /**
  81600. * ID of the grain post process
  81601. */
  81602. _this.GrainPostProcessId = "GrainPostProcessEffect";
  81603. /**
  81604. * Glow post process which adds a glow to emmisive areas of the image
  81605. */
  81606. _this._glowLayer = null;
  81607. /**
  81608. * Animations which can be used to tweak settings over a period of time
  81609. */
  81610. _this.animations = [];
  81611. _this._imageProcessingConfigurationObserver = null;
  81612. // Values
  81613. _this._sharpenEnabled = false;
  81614. _this._bloomEnabled = false;
  81615. _this._depthOfFieldEnabled = false;
  81616. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  81617. _this._fxaaEnabled = false;
  81618. _this._imageProcessingEnabled = true;
  81619. _this._bloomScale = 0.5;
  81620. _this._chromaticAberrationEnabled = false;
  81621. _this._grainEnabled = false;
  81622. _this._buildAllowed = true;
  81623. _this._resizeObserver = null;
  81624. _this._hardwareScaleLevel = 1.0;
  81625. _this._bloomKernel = 64;
  81626. /**
  81627. * Specifies the weight of the bloom in the final rendering
  81628. */
  81629. _this._bloomWeight = 0.15;
  81630. /**
  81631. * Specifies the luma threshold for the area that will be blurred by the bloom
  81632. */
  81633. _this._bloomThreshold = 0.9;
  81634. _this._samples = 1;
  81635. _this._hasCleared = false;
  81636. _this._prevPostProcess = null;
  81637. _this._prevPrevPostProcess = null;
  81638. _this._depthOfFieldSceneObserver = null;
  81639. _this._cameras = cameras || scene.cameras;
  81640. _this._cameras = _this._cameras.slice();
  81641. _this._camerasToBeAttached = _this._cameras.slice();
  81642. _this._buildAllowed = automaticBuild;
  81643. // Initialize
  81644. _this._scene = scene;
  81645. var caps = _this._scene.getEngine().getCaps();
  81646. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  81647. // Misc
  81648. if (_this._hdr) {
  81649. if (caps.textureHalfFloatRender) {
  81650. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81651. }
  81652. else if (caps.textureFloatRender) {
  81653. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81654. }
  81655. }
  81656. else {
  81657. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81658. }
  81659. // Attach
  81660. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81661. var engine = _this._scene.getEngine();
  81662. // Create post processes before hand so they can be modified before enabled.
  81663. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  81664. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81665. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  81666. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  81667. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  81668. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81669. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  81670. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81671. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  81672. _this._resizeObserver = engine.onResizeObservable.add(function () {
  81673. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  81674. _this.bloomKernel = _this.bloomKernel;
  81675. });
  81676. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  81677. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  81678. });
  81679. _this._buildPipeline();
  81680. return _this;
  81681. }
  81682. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  81683. get: function () {
  81684. return this._sharpenEnabled;
  81685. },
  81686. /**
  81687. * Enable or disable the sharpen process from the pipeline
  81688. */
  81689. set: function (enabled) {
  81690. if (this._sharpenEnabled === enabled) {
  81691. return;
  81692. }
  81693. this._sharpenEnabled = enabled;
  81694. this._buildPipeline();
  81695. },
  81696. enumerable: true,
  81697. configurable: true
  81698. });
  81699. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  81700. /**
  81701. * Specifies the size of the bloom blur kernel, relative to the final output size
  81702. */
  81703. get: function () {
  81704. return this._bloomKernel;
  81705. },
  81706. set: function (value) {
  81707. this._bloomKernel = value;
  81708. this.bloom.kernel = value / this._hardwareScaleLevel;
  81709. },
  81710. enumerable: true,
  81711. configurable: true
  81712. });
  81713. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  81714. get: function () {
  81715. return this._bloomWeight;
  81716. },
  81717. /**
  81718. * The strength of the bloom.
  81719. */
  81720. set: function (value) {
  81721. if (this._bloomWeight === value) {
  81722. return;
  81723. }
  81724. this.bloom.weight = value;
  81725. this._bloomWeight = value;
  81726. },
  81727. enumerable: true,
  81728. configurable: true
  81729. });
  81730. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  81731. get: function () {
  81732. return this._bloomThreshold;
  81733. },
  81734. /**
  81735. * The strength of the bloom.
  81736. */
  81737. set: function (value) {
  81738. if (this._bloomThreshold === value) {
  81739. return;
  81740. }
  81741. this.bloom.threshold = value;
  81742. this._bloomThreshold = value;
  81743. },
  81744. enumerable: true,
  81745. configurable: true
  81746. });
  81747. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  81748. get: function () {
  81749. return this._bloomScale;
  81750. },
  81751. /**
  81752. * The scale of the bloom, lower value will provide better performance.
  81753. */
  81754. set: function (value) {
  81755. if (this._bloomScale === value) {
  81756. return;
  81757. }
  81758. this._bloomScale = value;
  81759. // recreate bloom and dispose old as this setting is not dynamic
  81760. this._rebuildBloom();
  81761. this._buildPipeline();
  81762. },
  81763. enumerable: true,
  81764. configurable: true
  81765. });
  81766. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  81767. get: function () {
  81768. return this._bloomEnabled;
  81769. },
  81770. /**
  81771. * Enable or disable the bloom from the pipeline
  81772. */
  81773. set: function (enabled) {
  81774. if (this._bloomEnabled === enabled) {
  81775. return;
  81776. }
  81777. this._bloomEnabled = enabled;
  81778. this._buildPipeline();
  81779. },
  81780. enumerable: true,
  81781. configurable: true
  81782. });
  81783. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  81784. // recreate bloom and dispose old as this setting is not dynamic
  81785. var oldBloom = this.bloom;
  81786. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  81787. this.bloom.threshold = oldBloom.threshold;
  81788. for (var i = 0; i < this._cameras.length; i++) {
  81789. oldBloom.disposeEffects(this._cameras[i]);
  81790. }
  81791. };
  81792. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  81793. /**
  81794. * If the depth of field is enabled.
  81795. */
  81796. get: function () {
  81797. return this._depthOfFieldEnabled;
  81798. },
  81799. set: function (enabled) {
  81800. if (this._depthOfFieldEnabled === enabled) {
  81801. return;
  81802. }
  81803. this._depthOfFieldEnabled = enabled;
  81804. this._buildPipeline();
  81805. },
  81806. enumerable: true,
  81807. configurable: true
  81808. });
  81809. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  81810. /**
  81811. * Blur level of the depth of field effect. (Higher blur will effect performance)
  81812. */
  81813. get: function () {
  81814. return this._depthOfFieldBlurLevel;
  81815. },
  81816. set: function (value) {
  81817. if (this._depthOfFieldBlurLevel === value) {
  81818. return;
  81819. }
  81820. this._depthOfFieldBlurLevel = value;
  81821. // recreate dof and dispose old as this setting is not dynamic
  81822. var oldDof = this.depthOfField;
  81823. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  81824. this.depthOfField.focalLength = oldDof.focalLength;
  81825. this.depthOfField.focusDistance = oldDof.focusDistance;
  81826. this.depthOfField.fStop = oldDof.fStop;
  81827. this.depthOfField.lensSize = oldDof.lensSize;
  81828. for (var i = 0; i < this._cameras.length; i++) {
  81829. oldDof.disposeEffects(this._cameras[i]);
  81830. }
  81831. this._buildPipeline();
  81832. },
  81833. enumerable: true,
  81834. configurable: true
  81835. });
  81836. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  81837. get: function () {
  81838. return this._fxaaEnabled;
  81839. },
  81840. /**
  81841. * If the anti aliasing is enabled.
  81842. */
  81843. set: function (enabled) {
  81844. if (this._fxaaEnabled === enabled) {
  81845. return;
  81846. }
  81847. this._fxaaEnabled = enabled;
  81848. this._buildPipeline();
  81849. },
  81850. enumerable: true,
  81851. configurable: true
  81852. });
  81853. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  81854. get: function () {
  81855. return this._samples;
  81856. },
  81857. /**
  81858. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  81859. */
  81860. set: function (sampleCount) {
  81861. if (this._samples === sampleCount) {
  81862. return;
  81863. }
  81864. this._samples = sampleCount;
  81865. this._buildPipeline();
  81866. },
  81867. enumerable: true,
  81868. configurable: true
  81869. });
  81870. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  81871. get: function () {
  81872. return this._imageProcessingEnabled;
  81873. },
  81874. /**
  81875. * If image processing is enabled.
  81876. */
  81877. set: function (enabled) {
  81878. if (this._imageProcessingEnabled === enabled) {
  81879. return;
  81880. }
  81881. this._imageProcessingEnabled = enabled;
  81882. this._buildPipeline();
  81883. },
  81884. enumerable: true,
  81885. configurable: true
  81886. });
  81887. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  81888. get: function () {
  81889. return this._glowLayer == null;
  81890. },
  81891. /**
  81892. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  81893. */
  81894. set: function (enabled) {
  81895. if (enabled && !this._glowLayer) {
  81896. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  81897. }
  81898. else if (!enabled && this._glowLayer) {
  81899. this._glowLayer.dispose();
  81900. this._glowLayer = null;
  81901. }
  81902. },
  81903. enumerable: true,
  81904. configurable: true
  81905. });
  81906. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  81907. get: function () {
  81908. return this._chromaticAberrationEnabled;
  81909. },
  81910. /**
  81911. * Enable or disable the chromaticAberration process from the pipeline
  81912. */
  81913. set: function (enabled) {
  81914. if (this._chromaticAberrationEnabled === enabled) {
  81915. return;
  81916. }
  81917. this._chromaticAberrationEnabled = enabled;
  81918. this._buildPipeline();
  81919. },
  81920. enumerable: true,
  81921. configurable: true
  81922. });
  81923. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  81924. get: function () {
  81925. return this._grainEnabled;
  81926. },
  81927. /**
  81928. * Enable or disable the grain process from the pipeline
  81929. */
  81930. set: function (enabled) {
  81931. if (this._grainEnabled === enabled) {
  81932. return;
  81933. }
  81934. this._grainEnabled = enabled;
  81935. this._buildPipeline();
  81936. },
  81937. enumerable: true,
  81938. configurable: true
  81939. });
  81940. /**
  81941. * Force the compilation of the entire pipeline.
  81942. */
  81943. DefaultRenderingPipeline.prototype.prepare = function () {
  81944. var previousState = this._buildAllowed;
  81945. this._buildAllowed = true;
  81946. this._buildPipeline();
  81947. this._buildAllowed = previousState;
  81948. };
  81949. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  81950. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  81951. if (this._hasCleared) {
  81952. postProcess.autoClear = false;
  81953. }
  81954. else {
  81955. postProcess.autoClear = true;
  81956. this._scene.autoClear = false;
  81957. this._hasCleared = true;
  81958. }
  81959. if (!skipTextureSharing) {
  81960. if (this._prevPrevPostProcess) {
  81961. postProcess.shareOutputWith(this._prevPrevPostProcess);
  81962. }
  81963. else {
  81964. postProcess.useOwnOutput();
  81965. }
  81966. if (this._prevPostProcess) {
  81967. this._prevPrevPostProcess = this._prevPostProcess;
  81968. }
  81969. this._prevPostProcess = postProcess;
  81970. }
  81971. };
  81972. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  81973. var _this = this;
  81974. if (!this._buildAllowed) {
  81975. return;
  81976. }
  81977. this._scene.autoClear = true;
  81978. var engine = this._scene.getEngine();
  81979. this._disposePostProcesses();
  81980. if (this._cameras !== null) {
  81981. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81982. // get back cameras to be used to reattach pipeline
  81983. this._cameras = this._camerasToBeAttached.slice();
  81984. }
  81985. this._reset();
  81986. this._prevPostProcess = null;
  81987. this._prevPrevPostProcess = null;
  81988. this._hasCleared = false;
  81989. if (this.depthOfFieldEnabled) {
  81990. // Multi camera suport
  81991. if (this._cameras.length > 1) {
  81992. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  81993. var camera = _a[_i];
  81994. var depthRenderer = this._scene.enableDepthRenderer(camera);
  81995. depthRenderer.useOnlyInActiveCamera = true;
  81996. }
  81997. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  81998. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  81999. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  82000. }
  82001. });
  82002. }
  82003. else {
  82004. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  82005. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  82006. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  82007. }
  82008. if (!this.depthOfField._isReady()) {
  82009. this.depthOfField._updateEffects();
  82010. }
  82011. this.addEffect(this.depthOfField);
  82012. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  82013. }
  82014. else {
  82015. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  82016. }
  82017. if (this.bloomEnabled) {
  82018. if (!this.bloom._isReady()) {
  82019. this.bloom._updateEffects();
  82020. }
  82021. this.addEffect(this.bloom);
  82022. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  82023. }
  82024. if (this._imageProcessingEnabled) {
  82025. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  82026. if (this._hdr) {
  82027. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  82028. this._setAutoClearAndTextureSharing(this.imageProcessing);
  82029. }
  82030. else {
  82031. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  82032. }
  82033. }
  82034. if (this.sharpenEnabled) {
  82035. if (!this.sharpen.isReady()) {
  82036. this.sharpen.updateEffect();
  82037. }
  82038. this.addEffect(this._sharpenEffect);
  82039. this._setAutoClearAndTextureSharing(this.sharpen);
  82040. }
  82041. if (this.grainEnabled) {
  82042. if (!this.grain.isReady()) {
  82043. this.grain.updateEffect();
  82044. }
  82045. this.addEffect(this._grainEffect);
  82046. this._setAutoClearAndTextureSharing(this.grain);
  82047. }
  82048. if (this.chromaticAberrationEnabled) {
  82049. if (!this.chromaticAberration.isReady()) {
  82050. this.chromaticAberration.updateEffect();
  82051. }
  82052. this.addEffect(this._chromaticAberrationEffect);
  82053. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  82054. }
  82055. if (this.fxaaEnabled) {
  82056. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  82057. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  82058. this._setAutoClearAndTextureSharing(this.fxaa, true);
  82059. }
  82060. if (this._cameras !== null) {
  82061. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  82062. }
  82063. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  82064. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  82065. }
  82066. };
  82067. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  82068. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  82069. for (var i = 0; i < this._cameras.length; i++) {
  82070. var camera = this._cameras[i];
  82071. if (this.imageProcessing) {
  82072. this.imageProcessing.dispose(camera);
  82073. }
  82074. if (this.fxaa) {
  82075. this.fxaa.dispose(camera);
  82076. }
  82077. // These are created in the constructor and should not be disposed on every pipeline change
  82078. if (disposeNonRecreated) {
  82079. if (this.sharpen) {
  82080. this.sharpen.dispose(camera);
  82081. }
  82082. if (this.depthOfField) {
  82083. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  82084. this.depthOfField.disposeEffects(camera);
  82085. }
  82086. if (this.bloom) {
  82087. this.bloom.disposeEffects(camera);
  82088. }
  82089. if (this.chromaticAberration) {
  82090. this.chromaticAberration.dispose(camera);
  82091. }
  82092. if (this.grain) {
  82093. this.grain.dispose(camera);
  82094. }
  82095. if (this._glowLayer) {
  82096. this._glowLayer.dispose();
  82097. }
  82098. }
  82099. }
  82100. this.imageProcessing = null;
  82101. this.fxaa = null;
  82102. if (disposeNonRecreated) {
  82103. this.sharpen = null;
  82104. this._sharpenEffect = null;
  82105. this.depthOfField = null;
  82106. this.bloom = null;
  82107. this.chromaticAberration = null;
  82108. this._chromaticAberrationEffect = null;
  82109. this.grain = null;
  82110. this._grainEffect = null;
  82111. this._glowLayer = null;
  82112. }
  82113. };
  82114. /**
  82115. * Adds a camera to the pipeline
  82116. * @param camera the camera to be added
  82117. */
  82118. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  82119. this._camerasToBeAttached.push(camera);
  82120. this._buildPipeline();
  82121. };
  82122. /**
  82123. * Removes a camera from the pipeline
  82124. * @param camera the camera to remove
  82125. */
  82126. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  82127. var index = this._camerasToBeAttached.indexOf(camera);
  82128. this._camerasToBeAttached.splice(index, 1);
  82129. this._buildPipeline();
  82130. };
  82131. /**
  82132. * Dispose of the pipeline and stop all post processes
  82133. */
  82134. DefaultRenderingPipeline.prototype.dispose = function () {
  82135. this._disposePostProcesses(true);
  82136. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  82137. this._scene.autoClear = true;
  82138. if (this._resizeObserver) {
  82139. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  82140. this._resizeObserver = null;
  82141. }
  82142. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  82143. _super.prototype.dispose.call(this);
  82144. };
  82145. /**
  82146. * Serialize the rendering pipeline (Used when exporting)
  82147. * @returns the serialized object
  82148. */
  82149. DefaultRenderingPipeline.prototype.serialize = function () {
  82150. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  82151. serializationObject.customType = "DefaultRenderingPipeline";
  82152. return serializationObject;
  82153. };
  82154. /**
  82155. * Parse the serialized pipeline
  82156. * @param source Source pipeline.
  82157. * @param scene The scene to load the pipeline to.
  82158. * @param rootUrl The URL of the serialized pipeline.
  82159. * @returns An instantiated pipeline from the serialized object.
  82160. */
  82161. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  82162. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  82163. };
  82164. __decorate([
  82165. BABYLON.serialize()
  82166. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  82167. __decorate([
  82168. BABYLON.serialize()
  82169. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  82170. __decorate([
  82171. BABYLON.serialize()
  82172. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  82173. __decorate([
  82174. BABYLON.serialize()
  82175. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  82176. __decorate([
  82177. BABYLON.serialize()
  82178. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  82179. __decorate([
  82180. BABYLON.serialize()
  82181. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  82182. __decorate([
  82183. BABYLON.serialize()
  82184. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  82185. __decorate([
  82186. BABYLON.serialize()
  82187. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  82188. __decorate([
  82189. BABYLON.serialize()
  82190. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  82191. __decorate([
  82192. BABYLON.serialize()
  82193. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  82194. __decorate([
  82195. BABYLON.serialize()
  82196. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  82197. __decorate([
  82198. BABYLON.serialize()
  82199. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  82200. __decorate([
  82201. BABYLON.serialize()
  82202. ], DefaultRenderingPipeline.prototype, "samples", null);
  82203. __decorate([
  82204. BABYLON.serialize()
  82205. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  82206. __decorate([
  82207. BABYLON.serialize()
  82208. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  82209. __decorate([
  82210. BABYLON.serialize()
  82211. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  82212. __decorate([
  82213. BABYLON.serialize()
  82214. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  82215. return DefaultRenderingPipeline;
  82216. }(BABYLON.PostProcessRenderPipeline));
  82217. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  82218. })(BABYLON || (BABYLON = {}));
  82219. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  82220. var BABYLON;
  82221. (function (BABYLON) {
  82222. /**
  82223. * @hidden
  82224. */
  82225. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  82226. __extends(ImageProcessingConfigurationDefines, _super);
  82227. function ImageProcessingConfigurationDefines() {
  82228. var _this = _super.call(this) || this;
  82229. _this.IMAGEPROCESSING = false;
  82230. _this.VIGNETTE = false;
  82231. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  82232. _this.VIGNETTEBLENDMODEOPAQUE = false;
  82233. _this.TONEMAPPING = false;
  82234. _this.TONEMAPPING_ACES = false;
  82235. _this.CONTRAST = false;
  82236. _this.COLORCURVES = false;
  82237. _this.COLORGRADING = false;
  82238. _this.COLORGRADING3D = false;
  82239. _this.SAMPLER3DGREENDEPTH = false;
  82240. _this.SAMPLER3DBGRMAP = false;
  82241. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  82242. _this.EXPOSURE = false;
  82243. _this.rebuild();
  82244. return _this;
  82245. }
  82246. return ImageProcessingConfigurationDefines;
  82247. }(BABYLON.MaterialDefines));
  82248. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  82249. /**
  82250. * This groups together the common properties used for image processing either in direct forward pass
  82251. * or through post processing effect depending on the use of the image processing pipeline in your scene
  82252. * or not.
  82253. */
  82254. var ImageProcessingConfiguration = /** @class */ (function () {
  82255. function ImageProcessingConfiguration() {
  82256. /**
  82257. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  82258. */
  82259. this.colorCurves = new BABYLON.ColorCurves();
  82260. this._colorCurvesEnabled = false;
  82261. this._colorGradingEnabled = false;
  82262. this._colorGradingWithGreenDepth = true;
  82263. this._colorGradingBGR = true;
  82264. /** @hidden */
  82265. this._exposure = 1.0;
  82266. this._toneMappingEnabled = false;
  82267. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  82268. this._contrast = 1.0;
  82269. /**
  82270. * Vignette stretch size.
  82271. */
  82272. this.vignetteStretch = 0;
  82273. /**
  82274. * Vignette centre X Offset.
  82275. */
  82276. this.vignetteCentreX = 0;
  82277. /**
  82278. * Vignette centre Y Offset.
  82279. */
  82280. this.vignetteCentreY = 0;
  82281. /**
  82282. * Vignette weight or intensity of the vignette effect.
  82283. */
  82284. this.vignetteWeight = 1.5;
  82285. /**
  82286. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82287. * if vignetteEnabled is set to true.
  82288. */
  82289. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82290. /**
  82291. * Camera field of view used by the Vignette effect.
  82292. */
  82293. this.vignetteCameraFov = 0.5;
  82294. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  82295. this._vignetteEnabled = false;
  82296. this._applyByPostProcess = false;
  82297. this._isEnabled = true;
  82298. /**
  82299. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  82300. */
  82301. this.onUpdateParameters = new BABYLON.Observable();
  82302. }
  82303. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  82304. /**
  82305. * Gets wether the color curves effect is enabled.
  82306. */
  82307. get: function () {
  82308. return this._colorCurvesEnabled;
  82309. },
  82310. /**
  82311. * Sets wether the color curves effect is enabled.
  82312. */
  82313. set: function (value) {
  82314. if (this._colorCurvesEnabled === value) {
  82315. return;
  82316. }
  82317. this._colorCurvesEnabled = value;
  82318. this._updateParameters();
  82319. },
  82320. enumerable: true,
  82321. configurable: true
  82322. });
  82323. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  82324. /**
  82325. * Gets wether the color grading effect is enabled.
  82326. */
  82327. get: function () {
  82328. return this._colorGradingEnabled;
  82329. },
  82330. /**
  82331. * Sets wether the color grading effect is enabled.
  82332. */
  82333. set: function (value) {
  82334. if (this._colorGradingEnabled === value) {
  82335. return;
  82336. }
  82337. this._colorGradingEnabled = value;
  82338. this._updateParameters();
  82339. },
  82340. enumerable: true,
  82341. configurable: true
  82342. });
  82343. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  82344. /**
  82345. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  82346. */
  82347. get: function () {
  82348. return this._colorGradingWithGreenDepth;
  82349. },
  82350. /**
  82351. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  82352. */
  82353. set: function (value) {
  82354. if (this._colorGradingWithGreenDepth === value) {
  82355. return;
  82356. }
  82357. this._colorGradingWithGreenDepth = value;
  82358. this._updateParameters();
  82359. },
  82360. enumerable: true,
  82361. configurable: true
  82362. });
  82363. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  82364. /**
  82365. * Gets wether the color grading texture contains BGR values.
  82366. */
  82367. get: function () {
  82368. return this._colorGradingBGR;
  82369. },
  82370. /**
  82371. * Sets wether the color grading texture contains BGR values.
  82372. */
  82373. set: function (value) {
  82374. if (this._colorGradingBGR === value) {
  82375. return;
  82376. }
  82377. this._colorGradingBGR = value;
  82378. this._updateParameters();
  82379. },
  82380. enumerable: true,
  82381. configurable: true
  82382. });
  82383. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  82384. /**
  82385. * Gets the Exposure used in the effect.
  82386. */
  82387. get: function () {
  82388. return this._exposure;
  82389. },
  82390. /**
  82391. * Sets the Exposure used in the effect.
  82392. */
  82393. set: function (value) {
  82394. if (this._exposure === value) {
  82395. return;
  82396. }
  82397. this._exposure = value;
  82398. this._updateParameters();
  82399. },
  82400. enumerable: true,
  82401. configurable: true
  82402. });
  82403. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  82404. /**
  82405. * Gets wether the tone mapping effect is enabled.
  82406. */
  82407. get: function () {
  82408. return this._toneMappingEnabled;
  82409. },
  82410. /**
  82411. * Sets wether the tone mapping effect is enabled.
  82412. */
  82413. set: function (value) {
  82414. if (this._toneMappingEnabled === value) {
  82415. return;
  82416. }
  82417. this._toneMappingEnabled = value;
  82418. this._updateParameters();
  82419. },
  82420. enumerable: true,
  82421. configurable: true
  82422. });
  82423. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  82424. /**
  82425. * Gets the type of tone mapping effect.
  82426. */
  82427. get: function () {
  82428. return this._toneMappingType;
  82429. },
  82430. /**
  82431. * Sets the type of tone mapping effect used in BabylonJS.
  82432. */
  82433. set: function (value) {
  82434. if (this._toneMappingType === value) {
  82435. return;
  82436. }
  82437. this._toneMappingType = value;
  82438. this._updateParameters();
  82439. },
  82440. enumerable: true,
  82441. configurable: true
  82442. });
  82443. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  82444. /**
  82445. * Gets the contrast used in the effect.
  82446. */
  82447. get: function () {
  82448. return this._contrast;
  82449. },
  82450. /**
  82451. * Sets the contrast used in the effect.
  82452. */
  82453. set: function (value) {
  82454. if (this._contrast === value) {
  82455. return;
  82456. }
  82457. this._contrast = value;
  82458. this._updateParameters();
  82459. },
  82460. enumerable: true,
  82461. configurable: true
  82462. });
  82463. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  82464. /**
  82465. * Gets the vignette blend mode allowing different kind of effect.
  82466. */
  82467. get: function () {
  82468. return this._vignetteBlendMode;
  82469. },
  82470. /**
  82471. * Sets the vignette blend mode allowing different kind of effect.
  82472. */
  82473. set: function (value) {
  82474. if (this._vignetteBlendMode === value) {
  82475. return;
  82476. }
  82477. this._vignetteBlendMode = value;
  82478. this._updateParameters();
  82479. },
  82480. enumerable: true,
  82481. configurable: true
  82482. });
  82483. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  82484. /**
  82485. * Gets wether the vignette effect is enabled.
  82486. */
  82487. get: function () {
  82488. return this._vignetteEnabled;
  82489. },
  82490. /**
  82491. * Sets wether the vignette effect is enabled.
  82492. */
  82493. set: function (value) {
  82494. if (this._vignetteEnabled === value) {
  82495. return;
  82496. }
  82497. this._vignetteEnabled = value;
  82498. this._updateParameters();
  82499. },
  82500. enumerable: true,
  82501. configurable: true
  82502. });
  82503. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  82504. /**
  82505. * Gets wether the image processing is applied through a post process or not.
  82506. */
  82507. get: function () {
  82508. return this._applyByPostProcess;
  82509. },
  82510. /**
  82511. * Sets wether the image processing is applied through a post process or not.
  82512. */
  82513. set: function (value) {
  82514. if (this._applyByPostProcess === value) {
  82515. return;
  82516. }
  82517. this._applyByPostProcess = value;
  82518. this._updateParameters();
  82519. },
  82520. enumerable: true,
  82521. configurable: true
  82522. });
  82523. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  82524. /**
  82525. * Gets wether the image processing is enabled or not.
  82526. */
  82527. get: function () {
  82528. return this._isEnabled;
  82529. },
  82530. /**
  82531. * Sets wether the image processing is enabled or not.
  82532. */
  82533. set: function (value) {
  82534. if (this._isEnabled === value) {
  82535. return;
  82536. }
  82537. this._isEnabled = value;
  82538. this._updateParameters();
  82539. },
  82540. enumerable: true,
  82541. configurable: true
  82542. });
  82543. /**
  82544. * Method called each time the image processing information changes requires to recompile the effect.
  82545. */
  82546. ImageProcessingConfiguration.prototype._updateParameters = function () {
  82547. this.onUpdateParameters.notifyObservers(this);
  82548. };
  82549. ImageProcessingConfiguration.prototype.getClassName = function () {
  82550. return "ImageProcessingConfiguration";
  82551. };
  82552. /**
  82553. * Prepare the list of uniforms associated with the Image Processing effects.
  82554. * @param uniformsList The list of uniforms used in the effect
  82555. * @param defines the list of defines currently in use
  82556. */
  82557. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  82558. if (defines.EXPOSURE) {
  82559. uniforms.push("exposureLinear");
  82560. }
  82561. if (defines.CONTRAST) {
  82562. uniforms.push("contrast");
  82563. }
  82564. if (defines.COLORGRADING) {
  82565. uniforms.push("colorTransformSettings");
  82566. }
  82567. if (defines.VIGNETTE) {
  82568. uniforms.push("vInverseScreenSize");
  82569. uniforms.push("vignetteSettings1");
  82570. uniforms.push("vignetteSettings2");
  82571. }
  82572. if (defines.COLORCURVES) {
  82573. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  82574. }
  82575. };
  82576. /**
  82577. * Prepare the list of samplers associated with the Image Processing effects.
  82578. * @param uniformsList The list of uniforms used in the effect
  82579. * @param defines the list of defines currently in use
  82580. */
  82581. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  82582. if (defines.COLORGRADING) {
  82583. samplersList.push("txColorTransform");
  82584. }
  82585. };
  82586. /**
  82587. * Prepare the list of defines associated to the shader.
  82588. * @param defines the list of defines to complete
  82589. */
  82590. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  82591. if (forPostProcess === void 0) { forPostProcess = false; }
  82592. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  82593. defines.VIGNETTE = false;
  82594. defines.TONEMAPPING = false;
  82595. defines.TONEMAPPING_ACES = false;
  82596. defines.CONTRAST = false;
  82597. defines.EXPOSURE = false;
  82598. defines.COLORCURVES = false;
  82599. defines.COLORGRADING = false;
  82600. defines.COLORGRADING3D = false;
  82601. defines.IMAGEPROCESSING = false;
  82602. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  82603. return;
  82604. }
  82605. defines.VIGNETTE = this.vignetteEnabled;
  82606. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  82607. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  82608. defines.TONEMAPPING = this.toneMappingEnabled;
  82609. switch (this._toneMappingType) {
  82610. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  82611. defines.TONEMAPPING_ACES = true;
  82612. break;
  82613. }
  82614. defines.CONTRAST = (this.contrast !== 1.0);
  82615. defines.EXPOSURE = (this.exposure !== 1.0);
  82616. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  82617. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  82618. if (defines.COLORGRADING) {
  82619. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  82620. }
  82621. else {
  82622. defines.COLORGRADING3D = false;
  82623. }
  82624. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  82625. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  82626. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  82627. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  82628. };
  82629. /**
  82630. * Returns true if all the image processing information are ready.
  82631. */
  82632. ImageProcessingConfiguration.prototype.isReady = function () {
  82633. // Color Grading texure can not be none blocking.
  82634. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  82635. };
  82636. /**
  82637. * Binds the image processing to the shader.
  82638. * @param effect The effect to bind to
  82639. */
  82640. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  82641. if (aspectRatio === void 0) { aspectRatio = 1; }
  82642. // Color Curves
  82643. if (this._colorCurvesEnabled && this.colorCurves) {
  82644. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  82645. }
  82646. // Vignette
  82647. if (this._vignetteEnabled) {
  82648. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  82649. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  82650. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  82651. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  82652. var vignetteScaleX = vignetteScaleY * aspectRatio;
  82653. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  82654. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  82655. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  82656. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  82657. var vignettePower = -2.0 * this.vignetteWeight;
  82658. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  82659. }
  82660. // Exposure
  82661. effect.setFloat("exposureLinear", this.exposure);
  82662. // Contrast
  82663. effect.setFloat("contrast", this.contrast);
  82664. // Color transform settings
  82665. if (this.colorGradingTexture) {
  82666. effect.setTexture("txColorTransform", this.colorGradingTexture);
  82667. var textureSize = this.colorGradingTexture.getSize().height;
  82668. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  82669. 0.5 / textureSize, // textureOffset
  82670. textureSize, // textureSize
  82671. this.colorGradingTexture.level // weight
  82672. );
  82673. }
  82674. };
  82675. /**
  82676. * Clones the current image processing instance.
  82677. * @return The cloned image processing
  82678. */
  82679. ImageProcessingConfiguration.prototype.clone = function () {
  82680. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  82681. };
  82682. /**
  82683. * Serializes the current image processing instance to a json representation.
  82684. * @return a JSON representation
  82685. */
  82686. ImageProcessingConfiguration.prototype.serialize = function () {
  82687. return BABYLON.SerializationHelper.Serialize(this);
  82688. };
  82689. /**
  82690. * Parses the image processing from a json representation.
  82691. * @param source the JSON source to parse
  82692. * @return The parsed image processing
  82693. */
  82694. ImageProcessingConfiguration.Parse = function (source) {
  82695. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  82696. };
  82697. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  82698. /**
  82699. * Used to apply the vignette as a mix with the pixel color.
  82700. */
  82701. get: function () {
  82702. return this._VIGNETTEMODE_MULTIPLY;
  82703. },
  82704. enumerable: true,
  82705. configurable: true
  82706. });
  82707. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  82708. /**
  82709. * Used to apply the vignette as a replacement of the pixel color.
  82710. */
  82711. get: function () {
  82712. return this._VIGNETTEMODE_OPAQUE;
  82713. },
  82714. enumerable: true,
  82715. configurable: true
  82716. });
  82717. /**
  82718. * Default tone mapping applied in BabylonJS.
  82719. */
  82720. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  82721. /**
  82722. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  82723. * to other engines rendering to increase portability.
  82724. */
  82725. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  82726. // Static constants associated to the image processing.
  82727. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  82728. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  82729. __decorate([
  82730. BABYLON.serializeAsColorCurves()
  82731. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  82732. __decorate([
  82733. BABYLON.serialize()
  82734. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  82735. __decorate([
  82736. BABYLON.serializeAsTexture()
  82737. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  82738. __decorate([
  82739. BABYLON.serialize()
  82740. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  82741. __decorate([
  82742. BABYLON.serialize()
  82743. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  82744. __decorate([
  82745. BABYLON.serialize()
  82746. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  82747. __decorate([
  82748. BABYLON.serialize()
  82749. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  82750. __decorate([
  82751. BABYLON.serialize()
  82752. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  82753. __decorate([
  82754. BABYLON.serialize()
  82755. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  82756. __decorate([
  82757. BABYLON.serialize()
  82758. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  82759. __decorate([
  82760. BABYLON.serialize()
  82761. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  82762. __decorate([
  82763. BABYLON.serialize()
  82764. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  82765. __decorate([
  82766. BABYLON.serialize()
  82767. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  82768. __decorate([
  82769. BABYLON.serialize()
  82770. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  82771. __decorate([
  82772. BABYLON.serializeAsColor4()
  82773. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  82774. __decorate([
  82775. BABYLON.serialize()
  82776. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  82777. __decorate([
  82778. BABYLON.serialize()
  82779. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  82780. __decorate([
  82781. BABYLON.serialize()
  82782. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  82783. __decorate([
  82784. BABYLON.serialize()
  82785. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  82786. __decorate([
  82787. BABYLON.serialize()
  82788. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  82789. return ImageProcessingConfiguration;
  82790. }());
  82791. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  82792. })(BABYLON || (BABYLON = {}));
  82793. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  82794. var BABYLON;
  82795. (function (BABYLON) {
  82796. /**
  82797. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  82798. * It can help converting any input color in a desired output one. This can then be used to create effects
  82799. * from sepia, black and white to sixties or futuristic rendering...
  82800. *
  82801. * The only supported format is currently 3dl.
  82802. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  82803. */
  82804. var ColorGradingTexture = /** @class */ (function (_super) {
  82805. __extends(ColorGradingTexture, _super);
  82806. /**
  82807. * Instantiates a ColorGradingTexture from the following parameters.
  82808. *
  82809. * @param url The location of the color gradind data (currently only supporting 3dl)
  82810. * @param scene The scene the texture will be used in
  82811. */
  82812. function ColorGradingTexture(url, scene) {
  82813. var _this = _super.call(this, scene) || this;
  82814. if (!url) {
  82815. return _this;
  82816. }
  82817. _this._engine = scene.getEngine();
  82818. _this._textureMatrix = BABYLON.Matrix.Identity();
  82819. _this.name = url;
  82820. _this.url = url;
  82821. _this.hasAlpha = false;
  82822. _this.isCube = false;
  82823. _this.is3D = _this._engine.webGLVersion > 1;
  82824. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82825. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82826. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82827. _this.anisotropicFilteringLevel = 1;
  82828. _this._texture = _this._getFromCache(url, true);
  82829. if (!_this._texture) {
  82830. if (!scene.useDelayedTextureLoading) {
  82831. _this.loadTexture();
  82832. }
  82833. else {
  82834. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82835. }
  82836. }
  82837. return _this;
  82838. }
  82839. /**
  82840. * Returns the texture matrix used in most of the material.
  82841. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  82842. */
  82843. ColorGradingTexture.prototype.getTextureMatrix = function () {
  82844. return this._textureMatrix;
  82845. };
  82846. /**
  82847. * Occurs when the file being loaded is a .3dl LUT file.
  82848. */
  82849. ColorGradingTexture.prototype.load3dlTexture = function () {
  82850. var engine = this._engine;
  82851. var texture;
  82852. if (engine.webGLVersion === 1) {
  82853. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82854. }
  82855. else {
  82856. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82857. }
  82858. this._texture = texture;
  82859. var callback = function (text) {
  82860. if (typeof text !== "string") {
  82861. return;
  82862. }
  82863. var data = null;
  82864. var tempData = null;
  82865. var line;
  82866. var lines = text.split('\n');
  82867. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  82868. var maxColor = 0;
  82869. for (var i = 0; i < lines.length; i++) {
  82870. line = lines[i];
  82871. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  82872. continue;
  82873. if (line.indexOf('#') === 0)
  82874. continue;
  82875. var words = line.split(" ");
  82876. if (size === 0) {
  82877. // Number of space + one
  82878. size = words.length;
  82879. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  82880. tempData = new Float32Array(size * size * size * 4);
  82881. continue;
  82882. }
  82883. if (size != 0) {
  82884. var r = Math.max(parseInt(words[0]), 0);
  82885. var g = Math.max(parseInt(words[1]), 0);
  82886. var b = Math.max(parseInt(words[2]), 0);
  82887. maxColor = Math.max(r, maxColor);
  82888. maxColor = Math.max(g, maxColor);
  82889. maxColor = Math.max(b, maxColor);
  82890. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  82891. if (tempData) {
  82892. tempData[pixelStorageIndex + 0] = r;
  82893. tempData[pixelStorageIndex + 1] = g;
  82894. tempData[pixelStorageIndex + 2] = b;
  82895. }
  82896. pixelIndexSlice++;
  82897. if (pixelIndexSlice % size == 0) {
  82898. pixelIndexH++;
  82899. pixelIndexSlice = 0;
  82900. if (pixelIndexH % size == 0) {
  82901. pixelIndexW++;
  82902. pixelIndexH = 0;
  82903. }
  82904. }
  82905. }
  82906. }
  82907. if (tempData && data) {
  82908. for (var i = 0; i < tempData.length; i++) {
  82909. if (i > 0 && (i + 1) % 4 === 0) {
  82910. data[i] = 255;
  82911. }
  82912. else {
  82913. var value = tempData[i];
  82914. data[i] = (value / maxColor * 255);
  82915. }
  82916. }
  82917. }
  82918. if (texture.is3D) {
  82919. texture.updateSize(size, size, size);
  82920. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82921. }
  82922. else {
  82923. texture.updateSize(size * size, size);
  82924. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82925. }
  82926. };
  82927. var scene = this.getScene();
  82928. if (scene) {
  82929. scene._loadFile(this.url, callback);
  82930. }
  82931. else {
  82932. this._engine._loadFile(this.url, callback);
  82933. }
  82934. return this._texture;
  82935. };
  82936. /**
  82937. * Starts the loading process of the texture.
  82938. */
  82939. ColorGradingTexture.prototype.loadTexture = function () {
  82940. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  82941. this.load3dlTexture();
  82942. }
  82943. };
  82944. /**
  82945. * Clones the color gradind texture.
  82946. */
  82947. ColorGradingTexture.prototype.clone = function () {
  82948. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  82949. // Base texture
  82950. newTexture.level = this.level;
  82951. return newTexture;
  82952. };
  82953. /**
  82954. * Called during delayed load for textures.
  82955. */
  82956. ColorGradingTexture.prototype.delayLoad = function () {
  82957. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82958. return;
  82959. }
  82960. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82961. this._texture = this._getFromCache(this.url, true);
  82962. if (!this._texture) {
  82963. this.loadTexture();
  82964. }
  82965. };
  82966. /**
  82967. * Parses a color grading texture serialized by Babylon.
  82968. * @param parsedTexture The texture information being parsedTexture
  82969. * @param scene The scene to load the texture in
  82970. * @param rootUrl The root url of the data assets to load
  82971. * @return A color gradind texture
  82972. */
  82973. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82974. var texture = null;
  82975. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82976. texture = new ColorGradingTexture(parsedTexture.name, scene);
  82977. texture.name = parsedTexture.name;
  82978. texture.level = parsedTexture.level;
  82979. }
  82980. return texture;
  82981. };
  82982. /**
  82983. * Serializes the LUT texture to json format.
  82984. */
  82985. ColorGradingTexture.prototype.serialize = function () {
  82986. if (!this.name) {
  82987. return null;
  82988. }
  82989. var serializationObject = {};
  82990. serializationObject.name = this.name;
  82991. serializationObject.level = this.level;
  82992. serializationObject.customType = "BABYLON.ColorGradingTexture";
  82993. return serializationObject;
  82994. };
  82995. /**
  82996. * Empty line regex stored for GC.
  82997. */
  82998. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  82999. return ColorGradingTexture;
  83000. }(BABYLON.BaseTexture));
  83001. BABYLON.ColorGradingTexture = ColorGradingTexture;
  83002. })(BABYLON || (BABYLON = {}));
  83003. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  83004. var BABYLON;
  83005. (function (BABYLON) {
  83006. /**
  83007. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83008. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83009. * 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;
  83010. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83011. */
  83012. var ColorCurves = /** @class */ (function () {
  83013. function ColorCurves() {
  83014. this._dirty = true;
  83015. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  83016. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  83017. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  83018. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  83019. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  83020. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  83021. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  83022. this._globalHue = 30;
  83023. this._globalDensity = 0;
  83024. this._globalSaturation = 0;
  83025. this._globalExposure = 0;
  83026. this._highlightsHue = 30;
  83027. this._highlightsDensity = 0;
  83028. this._highlightsSaturation = 0;
  83029. this._highlightsExposure = 0;
  83030. this._midtonesHue = 30;
  83031. this._midtonesDensity = 0;
  83032. this._midtonesSaturation = 0;
  83033. this._midtonesExposure = 0;
  83034. this._shadowsHue = 30;
  83035. this._shadowsDensity = 0;
  83036. this._shadowsSaturation = 0;
  83037. this._shadowsExposure = 0;
  83038. }
  83039. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  83040. /**
  83041. * Gets the global Hue value.
  83042. * 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).
  83043. */
  83044. get: function () {
  83045. return this._globalHue;
  83046. },
  83047. /**
  83048. * Sets the global Hue value.
  83049. * 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).
  83050. */
  83051. set: function (value) {
  83052. this._globalHue = value;
  83053. this._dirty = true;
  83054. },
  83055. enumerable: true,
  83056. configurable: true
  83057. });
  83058. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  83059. /**
  83060. * Gets the global Density value.
  83061. * 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.
  83062. * Values less than zero provide a filter of opposite hue.
  83063. */
  83064. get: function () {
  83065. return this._globalDensity;
  83066. },
  83067. /**
  83068. * Sets the global Density value.
  83069. * 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.
  83070. * Values less than zero provide a filter of opposite hue.
  83071. */
  83072. set: function (value) {
  83073. this._globalDensity = value;
  83074. this._dirty = true;
  83075. },
  83076. enumerable: true,
  83077. configurable: true
  83078. });
  83079. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  83080. /**
  83081. * Gets the global Saturation value.
  83082. * 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.
  83083. */
  83084. get: function () {
  83085. return this._globalSaturation;
  83086. },
  83087. /**
  83088. * Sets the global Saturation value.
  83089. * 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.
  83090. */
  83091. set: function (value) {
  83092. this._globalSaturation = value;
  83093. this._dirty = true;
  83094. },
  83095. enumerable: true,
  83096. configurable: true
  83097. });
  83098. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  83099. /**
  83100. * Gets the global Exposure value.
  83101. * 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.
  83102. */
  83103. get: function () {
  83104. return this._globalExposure;
  83105. },
  83106. /**
  83107. * Sets the global Exposure value.
  83108. * 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.
  83109. */
  83110. set: function (value) {
  83111. this._globalExposure = value;
  83112. this._dirty = true;
  83113. },
  83114. enumerable: true,
  83115. configurable: true
  83116. });
  83117. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  83118. /**
  83119. * Gets the highlights Hue value.
  83120. * 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).
  83121. */
  83122. get: function () {
  83123. return this._highlightsHue;
  83124. },
  83125. /**
  83126. * Sets the highlights Hue value.
  83127. * 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).
  83128. */
  83129. set: function (value) {
  83130. this._highlightsHue = value;
  83131. this._dirty = true;
  83132. },
  83133. enumerable: true,
  83134. configurable: true
  83135. });
  83136. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  83137. /**
  83138. * Gets the highlights Density value.
  83139. * 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.
  83140. * Values less than zero provide a filter of opposite hue.
  83141. */
  83142. get: function () {
  83143. return this._highlightsDensity;
  83144. },
  83145. /**
  83146. * Sets the highlights Density value.
  83147. * 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.
  83148. * Values less than zero provide a filter of opposite hue.
  83149. */
  83150. set: function (value) {
  83151. this._highlightsDensity = value;
  83152. this._dirty = true;
  83153. },
  83154. enumerable: true,
  83155. configurable: true
  83156. });
  83157. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  83158. /**
  83159. * Gets the highlights Saturation value.
  83160. * 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.
  83161. */
  83162. get: function () {
  83163. return this._highlightsSaturation;
  83164. },
  83165. /**
  83166. * Sets the highlights Saturation value.
  83167. * 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.
  83168. */
  83169. set: function (value) {
  83170. this._highlightsSaturation = value;
  83171. this._dirty = true;
  83172. },
  83173. enumerable: true,
  83174. configurable: true
  83175. });
  83176. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  83177. /**
  83178. * Gets the highlights Exposure value.
  83179. * 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.
  83180. */
  83181. get: function () {
  83182. return this._highlightsExposure;
  83183. },
  83184. /**
  83185. * Sets the highlights Exposure value.
  83186. * 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.
  83187. */
  83188. set: function (value) {
  83189. this._highlightsExposure = value;
  83190. this._dirty = true;
  83191. },
  83192. enumerable: true,
  83193. configurable: true
  83194. });
  83195. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  83196. /**
  83197. * Gets the midtones Hue value.
  83198. * 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).
  83199. */
  83200. get: function () {
  83201. return this._midtonesHue;
  83202. },
  83203. /**
  83204. * Sets the midtones Hue value.
  83205. * 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).
  83206. */
  83207. set: function (value) {
  83208. this._midtonesHue = value;
  83209. this._dirty = true;
  83210. },
  83211. enumerable: true,
  83212. configurable: true
  83213. });
  83214. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  83215. /**
  83216. * Gets the midtones Density value.
  83217. * 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.
  83218. * Values less than zero provide a filter of opposite hue.
  83219. */
  83220. get: function () {
  83221. return this._midtonesDensity;
  83222. },
  83223. /**
  83224. * Sets the midtones Density value.
  83225. * 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.
  83226. * Values less than zero provide a filter of opposite hue.
  83227. */
  83228. set: function (value) {
  83229. this._midtonesDensity = value;
  83230. this._dirty = true;
  83231. },
  83232. enumerable: true,
  83233. configurable: true
  83234. });
  83235. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  83236. /**
  83237. * Gets the midtones Saturation value.
  83238. * 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.
  83239. */
  83240. get: function () {
  83241. return this._midtonesSaturation;
  83242. },
  83243. /**
  83244. * Sets the midtones Saturation value.
  83245. * 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.
  83246. */
  83247. set: function (value) {
  83248. this._midtonesSaturation = value;
  83249. this._dirty = true;
  83250. },
  83251. enumerable: true,
  83252. configurable: true
  83253. });
  83254. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  83255. /**
  83256. * Gets the midtones Exposure value.
  83257. * 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.
  83258. */
  83259. get: function () {
  83260. return this._midtonesExposure;
  83261. },
  83262. /**
  83263. * Sets the midtones Exposure value.
  83264. * 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.
  83265. */
  83266. set: function (value) {
  83267. this._midtonesExposure = value;
  83268. this._dirty = true;
  83269. },
  83270. enumerable: true,
  83271. configurable: true
  83272. });
  83273. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  83274. /**
  83275. * Gets the shadows Hue value.
  83276. * 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).
  83277. */
  83278. get: function () {
  83279. return this._shadowsHue;
  83280. },
  83281. /**
  83282. * Sets the shadows Hue value.
  83283. * 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).
  83284. */
  83285. set: function (value) {
  83286. this._shadowsHue = value;
  83287. this._dirty = true;
  83288. },
  83289. enumerable: true,
  83290. configurable: true
  83291. });
  83292. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  83293. /**
  83294. * Gets the shadows Density value.
  83295. * 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.
  83296. * Values less than zero provide a filter of opposite hue.
  83297. */
  83298. get: function () {
  83299. return this._shadowsDensity;
  83300. },
  83301. /**
  83302. * Sets the shadows Density value.
  83303. * 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.
  83304. * Values less than zero provide a filter of opposite hue.
  83305. */
  83306. set: function (value) {
  83307. this._shadowsDensity = value;
  83308. this._dirty = true;
  83309. },
  83310. enumerable: true,
  83311. configurable: true
  83312. });
  83313. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  83314. /**
  83315. * Gets the shadows Saturation value.
  83316. * 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.
  83317. */
  83318. get: function () {
  83319. return this._shadowsSaturation;
  83320. },
  83321. /**
  83322. * Sets the shadows Saturation value.
  83323. * 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.
  83324. */
  83325. set: function (value) {
  83326. this._shadowsSaturation = value;
  83327. this._dirty = true;
  83328. },
  83329. enumerable: true,
  83330. configurable: true
  83331. });
  83332. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  83333. /**
  83334. * Gets the shadows Exposure value.
  83335. * 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.
  83336. */
  83337. get: function () {
  83338. return this._shadowsExposure;
  83339. },
  83340. /**
  83341. * Sets the shadows Exposure value.
  83342. * 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.
  83343. */
  83344. set: function (value) {
  83345. this._shadowsExposure = value;
  83346. this._dirty = true;
  83347. },
  83348. enumerable: true,
  83349. configurable: true
  83350. });
  83351. ColorCurves.prototype.getClassName = function () {
  83352. return "ColorCurves";
  83353. };
  83354. /**
  83355. * Binds the color curves to the shader.
  83356. * @param colorCurves The color curve to bind
  83357. * @param effect The effect to bind to
  83358. */
  83359. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  83360. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  83361. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  83362. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  83363. if (colorCurves._dirty) {
  83364. colorCurves._dirty = false;
  83365. // Fill in global info.
  83366. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  83367. // Compute highlights info.
  83368. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  83369. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  83370. // Compute midtones info.
  83371. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  83372. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  83373. // Compute shadows info.
  83374. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  83375. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  83376. // Compute deltas (neutral is midtones).
  83377. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  83378. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  83379. }
  83380. if (effect) {
  83381. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  83382. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  83383. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  83384. }
  83385. };
  83386. /**
  83387. * Prepare the list of uniforms associated with the ColorCurves effects.
  83388. * @param uniformsList The list of uniforms used in the effect
  83389. */
  83390. ColorCurves.PrepareUniforms = function (uniformsList) {
  83391. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  83392. };
  83393. /**
  83394. * Returns color grading data based on a hue, density, saturation and exposure value.
  83395. * @param filterHue The hue of the color filter.
  83396. * @param filterDensity The density of the color filter.
  83397. * @param saturation The saturation.
  83398. * @param exposure The exposure.
  83399. * @param result The result data container.
  83400. */
  83401. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  83402. if (hue == null) {
  83403. return;
  83404. }
  83405. hue = ColorCurves.clamp(hue, 0, 360);
  83406. density = ColorCurves.clamp(density, -100, 100);
  83407. saturation = ColorCurves.clamp(saturation, -100, 100);
  83408. exposure = ColorCurves.clamp(exposure, -100, 100);
  83409. // Remap the slider/config filter density with non-linear mapping and also scale by half
  83410. // so that the maximum filter density is only 50% control. This provides fine control
  83411. // for small values and reasonable range.
  83412. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  83413. density *= 0.5;
  83414. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  83415. if (density < 0) {
  83416. density *= -1;
  83417. hue = (hue + 180) % 360;
  83418. }
  83419. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  83420. result.scaleToRef(2, result);
  83421. result.a = 1 + 0.01 * saturation;
  83422. };
  83423. /**
  83424. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  83425. * @param value The input slider value in range [-100,100].
  83426. * @returns Adjusted value.
  83427. */
  83428. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  83429. value /= 100;
  83430. var x = Math.abs(value);
  83431. x = Math.pow(x, 2);
  83432. if (value < 0) {
  83433. x *= -1;
  83434. }
  83435. x *= 100;
  83436. return x;
  83437. };
  83438. /**
  83439. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  83440. * @param hue The hue (H) input.
  83441. * @param saturation The saturation (S) input.
  83442. * @param brightness The brightness (B) input.
  83443. * @result An RGBA color represented as Vector4.
  83444. */
  83445. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  83446. var h = ColorCurves.clamp(hue, 0, 360);
  83447. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  83448. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  83449. if (s === 0) {
  83450. result.r = v;
  83451. result.g = v;
  83452. result.b = v;
  83453. }
  83454. else {
  83455. // sector 0 to 5
  83456. h /= 60;
  83457. var i = Math.floor(h);
  83458. // fractional part of h
  83459. var f = h - i;
  83460. var p = v * (1 - s);
  83461. var q = v * (1 - s * f);
  83462. var t = v * (1 - s * (1 - f));
  83463. switch (i) {
  83464. case 0:
  83465. result.r = v;
  83466. result.g = t;
  83467. result.b = p;
  83468. break;
  83469. case 1:
  83470. result.r = q;
  83471. result.g = v;
  83472. result.b = p;
  83473. break;
  83474. case 2:
  83475. result.r = p;
  83476. result.g = v;
  83477. result.b = t;
  83478. break;
  83479. case 3:
  83480. result.r = p;
  83481. result.g = q;
  83482. result.b = v;
  83483. break;
  83484. case 4:
  83485. result.r = t;
  83486. result.g = p;
  83487. result.b = v;
  83488. break;
  83489. default: // case 5:
  83490. result.r = v;
  83491. result.g = p;
  83492. result.b = q;
  83493. break;
  83494. }
  83495. }
  83496. result.a = 1;
  83497. };
  83498. /**
  83499. * Returns a value clamped between min and max
  83500. * @param value The value to clamp
  83501. * @param min The minimum of value
  83502. * @param max The maximum of value
  83503. * @returns The clamped value.
  83504. */
  83505. ColorCurves.clamp = function (value, min, max) {
  83506. return Math.min(Math.max(value, min), max);
  83507. };
  83508. /**
  83509. * Clones the current color curve instance.
  83510. * @return The cloned curves
  83511. */
  83512. ColorCurves.prototype.clone = function () {
  83513. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  83514. };
  83515. /**
  83516. * Serializes the current color curve instance to a json representation.
  83517. * @return a JSON representation
  83518. */
  83519. ColorCurves.prototype.serialize = function () {
  83520. return BABYLON.SerializationHelper.Serialize(this);
  83521. };
  83522. /**
  83523. * Parses the color curve from a json representation.
  83524. * @param source the JSON source to parse
  83525. * @return The parsed curves
  83526. */
  83527. ColorCurves.Parse = function (source) {
  83528. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  83529. };
  83530. __decorate([
  83531. BABYLON.serialize()
  83532. ], ColorCurves.prototype, "_globalHue", void 0);
  83533. __decorate([
  83534. BABYLON.serialize()
  83535. ], ColorCurves.prototype, "_globalDensity", void 0);
  83536. __decorate([
  83537. BABYLON.serialize()
  83538. ], ColorCurves.prototype, "_globalSaturation", void 0);
  83539. __decorate([
  83540. BABYLON.serialize()
  83541. ], ColorCurves.prototype, "_globalExposure", void 0);
  83542. __decorate([
  83543. BABYLON.serialize()
  83544. ], ColorCurves.prototype, "_highlightsHue", void 0);
  83545. __decorate([
  83546. BABYLON.serialize()
  83547. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  83548. __decorate([
  83549. BABYLON.serialize()
  83550. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  83551. __decorate([
  83552. BABYLON.serialize()
  83553. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  83554. __decorate([
  83555. BABYLON.serialize()
  83556. ], ColorCurves.prototype, "_midtonesHue", void 0);
  83557. __decorate([
  83558. BABYLON.serialize()
  83559. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  83560. __decorate([
  83561. BABYLON.serialize()
  83562. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  83563. __decorate([
  83564. BABYLON.serialize()
  83565. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  83566. return ColorCurves;
  83567. }());
  83568. BABYLON.ColorCurves = ColorCurves;
  83569. })(BABYLON || (BABYLON = {}));
  83570. //# sourceMappingURL=babylon.colorCurves.js.map
  83571. var BABYLON;
  83572. (function (BABYLON) {
  83573. var RefractionPostProcess = /** @class */ (function (_super) {
  83574. __extends(RefractionPostProcess, _super);
  83575. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  83576. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  83577. _this.color = color;
  83578. _this.depth = depth;
  83579. _this.colorLevel = colorLevel;
  83580. _this._ownRefractionTexture = true;
  83581. _this.onActivateObservable.add(function (cam) {
  83582. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  83583. });
  83584. _this.onApplyObservable.add(function (effect) {
  83585. effect.setColor3("baseColor", _this.color);
  83586. effect.setFloat("depth", _this.depth);
  83587. effect.setFloat("colorLevel", _this.colorLevel);
  83588. effect.setTexture("refractionSampler", _this._refTexture);
  83589. });
  83590. return _this;
  83591. }
  83592. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  83593. /**
  83594. * Gets or sets the refraction texture
  83595. * Please note that you are responsible for disposing the texture if you set it manually
  83596. */
  83597. get: function () {
  83598. return this._refTexture;
  83599. },
  83600. set: function (value) {
  83601. if (this._refTexture && this._ownRefractionTexture) {
  83602. this._refTexture.dispose();
  83603. }
  83604. this._refTexture = value;
  83605. this._ownRefractionTexture = false;
  83606. },
  83607. enumerable: true,
  83608. configurable: true
  83609. });
  83610. // Methods
  83611. RefractionPostProcess.prototype.dispose = function (camera) {
  83612. if (this._refTexture && this._ownRefractionTexture) {
  83613. this._refTexture.dispose();
  83614. this._refTexture = null;
  83615. }
  83616. _super.prototype.dispose.call(this, camera);
  83617. };
  83618. return RefractionPostProcess;
  83619. }(BABYLON.PostProcess));
  83620. BABYLON.RefractionPostProcess = RefractionPostProcess;
  83621. })(BABYLON || (BABYLON = {}));
  83622. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  83623. var BABYLON;
  83624. (function (BABYLON) {
  83625. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  83626. __extends(BlackAndWhitePostProcess, _super);
  83627. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  83628. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  83629. _this.degree = 1;
  83630. _this.onApplyObservable.add(function (effect) {
  83631. effect.setFloat("degree", _this.degree);
  83632. });
  83633. return _this;
  83634. }
  83635. return BlackAndWhitePostProcess;
  83636. }(BABYLON.PostProcess));
  83637. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  83638. })(BABYLON || (BABYLON = {}));
  83639. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  83640. var BABYLON;
  83641. (function (BABYLON) {
  83642. /**
  83643. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  83644. * input texture to perform effects such as edge detection or sharpening
  83645. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  83646. */
  83647. var ConvolutionPostProcess = /** @class */ (function (_super) {
  83648. __extends(ConvolutionPostProcess, _super);
  83649. /**
  83650. * Creates a new instance ConvolutionPostProcess
  83651. * @param name The name of the effect.
  83652. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  83653. * @param options The required width/height ratio to downsize to before computing the render pass.
  83654. * @param camera The camera to apply the render pass to.
  83655. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83656. * @param engine The engine which the post process will be applied. (default: current engine)
  83657. * @param reusable If the post process can be reused on the same frame. (default: false)
  83658. * @param textureType Type of textures used when performing the post process. (default: 0)
  83659. */
  83660. function ConvolutionPostProcess(name,
  83661. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  83662. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  83663. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83664. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83665. _this.kernel = kernel;
  83666. _this.onApply = function (effect) {
  83667. effect.setFloat2("screenSize", _this.width, _this.height);
  83668. effect.setArray("kernel", _this.kernel);
  83669. };
  83670. return _this;
  83671. }
  83672. // Statics
  83673. /**
  83674. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83675. */
  83676. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  83677. /**
  83678. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83679. */
  83680. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  83681. /**
  83682. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83683. */
  83684. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  83685. /**
  83686. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83687. */
  83688. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  83689. /**
  83690. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83691. */
  83692. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  83693. /**
  83694. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83695. */
  83696. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  83697. return ConvolutionPostProcess;
  83698. }(BABYLON.PostProcess));
  83699. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  83700. })(BABYLON || (BABYLON = {}));
  83701. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  83702. var BABYLON;
  83703. (function (BABYLON) {
  83704. var FilterPostProcess = /** @class */ (function (_super) {
  83705. __extends(FilterPostProcess, _super);
  83706. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  83707. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  83708. _this.kernelMatrix = kernelMatrix;
  83709. _this.onApply = function (effect) {
  83710. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  83711. };
  83712. return _this;
  83713. }
  83714. return FilterPostProcess;
  83715. }(BABYLON.PostProcess));
  83716. BABYLON.FilterPostProcess = FilterPostProcess;
  83717. })(BABYLON || (BABYLON = {}));
  83718. //# sourceMappingURL=babylon.filterPostProcess.js.map
  83719. var BABYLON;
  83720. (function (BABYLON) {
  83721. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  83722. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  83723. __extends(VolumetricLightScatteringPostProcess, _super);
  83724. /**
  83725. * @constructor
  83726. * @param {string} name - The post-process name
  83727. * @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)
  83728. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  83729. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  83730. * @param {number} samples - The post-process quality, default 100
  83731. * @param {number} samplingMode - The post-process filtering mode
  83732. * @param {BABYLON.Engine} engine - The babylon engine
  83733. * @param {boolean} reusable - If the post-process is reusable
  83734. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  83735. */
  83736. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  83737. if (samples === void 0) { samples = 100; }
  83738. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83739. 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;
  83740. _this._screenCoordinates = BABYLON.Vector2.Zero();
  83741. /**
  83742. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  83743. */
  83744. _this.customMeshPosition = BABYLON.Vector3.Zero();
  83745. /**
  83746. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  83747. */
  83748. _this.useCustomMeshPosition = false;
  83749. /**
  83750. * If the post-process should inverse the light scattering direction
  83751. */
  83752. _this.invert = true;
  83753. /**
  83754. * Array containing the excluded meshes not rendered in the internal pass
  83755. */
  83756. _this.excludedMeshes = new Array();
  83757. /**
  83758. * Controls the overall intensity of the post-process
  83759. */
  83760. _this.exposure = 0.3;
  83761. /**
  83762. * Dissipates each sample's contribution in range [0, 1]
  83763. */
  83764. _this.decay = 0.96815;
  83765. /**
  83766. * Controls the overall intensity of each sample
  83767. */
  83768. _this.weight = 0.58767;
  83769. /**
  83770. * Controls the density of each sample
  83771. */
  83772. _this.density = 0.926;
  83773. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  83774. engine = scene.getEngine();
  83775. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  83776. // Configure mesh
  83777. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  83778. // Configure
  83779. _this._createPass(scene, ratio.passRatio || ratio);
  83780. _this.onActivate = function (camera) {
  83781. if (!_this.isSupported) {
  83782. _this.dispose(camera);
  83783. }
  83784. _this.onActivate = null;
  83785. };
  83786. _this.onApplyObservable.add(function (effect) {
  83787. _this._updateMeshScreenCoordinates(scene);
  83788. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  83789. effect.setFloat("exposure", _this.exposure);
  83790. effect.setFloat("decay", _this.decay);
  83791. effect.setFloat("weight", _this.weight);
  83792. effect.setFloat("density", _this.density);
  83793. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  83794. });
  83795. return _this;
  83796. }
  83797. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  83798. get: function () {
  83799. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83800. return false;
  83801. },
  83802. set: function (useDiffuseColor) {
  83803. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83804. },
  83805. enumerable: true,
  83806. configurable: true
  83807. });
  83808. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  83809. return "VolumetricLightScatteringPostProcess";
  83810. };
  83811. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  83812. var mesh = subMesh.getMesh();
  83813. // Render this.mesh as default
  83814. if (mesh === this.mesh && mesh.material) {
  83815. return mesh.material.isReady(mesh);
  83816. }
  83817. var defines = [];
  83818. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83819. var material = subMesh.getMaterial();
  83820. // Alpha test
  83821. if (material) {
  83822. if (material.needAlphaTesting()) {
  83823. defines.push("#define ALPHATEST");
  83824. }
  83825. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83826. attribs.push(BABYLON.VertexBuffer.UVKind);
  83827. defines.push("#define UV1");
  83828. }
  83829. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83830. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83831. defines.push("#define UV2");
  83832. }
  83833. }
  83834. // Bones
  83835. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83836. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83837. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83838. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83839. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83840. }
  83841. else {
  83842. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83843. }
  83844. // Instances
  83845. if (useInstances) {
  83846. defines.push("#define INSTANCES");
  83847. attribs.push("world0");
  83848. attribs.push("world1");
  83849. attribs.push("world2");
  83850. attribs.push("world3");
  83851. }
  83852. // Get correct effect
  83853. var join = defines.join("\n");
  83854. if (this._cachedDefines !== join) {
  83855. this._cachedDefines = join;
  83856. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  83857. }
  83858. return this._volumetricLightScatteringPass.isReady();
  83859. };
  83860. /**
  83861. * Sets the new light position for light scattering effect
  83862. * @param {BABYLON.Vector3} The new custom light position
  83863. */
  83864. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  83865. this.customMeshPosition = position;
  83866. };
  83867. /**
  83868. * Returns the light position for light scattering effect
  83869. * @return {BABYLON.Vector3} The custom light position
  83870. */
  83871. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  83872. return this.customMeshPosition;
  83873. };
  83874. /**
  83875. * Disposes the internal assets and detaches the post-process from the camera
  83876. */
  83877. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  83878. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  83879. if (rttIndex !== -1) {
  83880. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  83881. }
  83882. this._volumetricLightScatteringRTT.dispose();
  83883. _super.prototype.dispose.call(this, camera);
  83884. };
  83885. /**
  83886. * Returns the render target texture used by the post-process
  83887. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  83888. */
  83889. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  83890. return this._volumetricLightScatteringRTT;
  83891. };
  83892. // Private methods
  83893. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  83894. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  83895. return true;
  83896. }
  83897. return false;
  83898. };
  83899. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  83900. var _this = this;
  83901. var engine = scene.getEngine();
  83902. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83903. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83904. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83905. this._volumetricLightScatteringRTT.renderList = null;
  83906. this._volumetricLightScatteringRTT.renderParticles = false;
  83907. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  83908. var camera = this.getCamera();
  83909. if (camera) {
  83910. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83911. }
  83912. else {
  83913. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83914. }
  83915. // Custom render function for submeshes
  83916. var renderSubMesh = function (subMesh) {
  83917. var mesh = subMesh.getRenderingMesh();
  83918. if (_this._meshExcluded(mesh)) {
  83919. return;
  83920. }
  83921. var material = subMesh.getMaterial();
  83922. if (!material) {
  83923. return;
  83924. }
  83925. var scene = mesh.getScene();
  83926. var engine = scene.getEngine();
  83927. // Culling
  83928. engine.setState(material.backFaceCulling);
  83929. // Managing instances
  83930. var batch = mesh._getInstancesRenderList(subMesh._id);
  83931. if (batch.mustReturn) {
  83932. return;
  83933. }
  83934. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83935. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  83936. var effect = _this._volumetricLightScatteringPass;
  83937. if (mesh === _this.mesh) {
  83938. if (subMesh.effect) {
  83939. effect = subMesh.effect;
  83940. }
  83941. else {
  83942. effect = material.getEffect();
  83943. }
  83944. }
  83945. engine.enableEffect(effect);
  83946. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  83947. if (mesh === _this.mesh) {
  83948. material.bind(mesh.getWorldMatrix(), mesh);
  83949. }
  83950. else {
  83951. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  83952. // Alpha test
  83953. if (material && material.needAlphaTesting()) {
  83954. var alphaTexture = material.getAlphaTestTexture();
  83955. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  83956. if (alphaTexture) {
  83957. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83958. }
  83959. }
  83960. // Bones
  83961. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83962. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83963. }
  83964. }
  83965. // Draw
  83966. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  83967. }
  83968. };
  83969. // Render target texture callbacks
  83970. var savedSceneClearColor;
  83971. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  83972. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  83973. savedSceneClearColor = scene.clearColor;
  83974. scene.clearColor = sceneClearColor;
  83975. });
  83976. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  83977. scene.clearColor = savedSceneClearColor;
  83978. });
  83979. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83980. var engine = scene.getEngine();
  83981. var index;
  83982. if (depthOnlySubMeshes.length) {
  83983. engine.setColorWrite(false);
  83984. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83985. renderSubMesh(depthOnlySubMeshes.data[index]);
  83986. }
  83987. engine.setColorWrite(true);
  83988. }
  83989. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83990. renderSubMesh(opaqueSubMeshes.data[index]);
  83991. }
  83992. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83993. renderSubMesh(alphaTestSubMeshes.data[index]);
  83994. }
  83995. if (transparentSubMeshes.length) {
  83996. // Sort sub meshes
  83997. for (index = 0; index < transparentSubMeshes.length; index++) {
  83998. var submesh = transparentSubMeshes.data[index];
  83999. var boundingInfo = submesh.getBoundingInfo();
  84000. if (boundingInfo && scene.activeCamera) {
  84001. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  84002. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  84003. }
  84004. }
  84005. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  84006. sortedArray.sort(function (a, b) {
  84007. // Alpha index first
  84008. if (a._alphaIndex > b._alphaIndex) {
  84009. return 1;
  84010. }
  84011. if (a._alphaIndex < b._alphaIndex) {
  84012. return -1;
  84013. }
  84014. // Then distance to camera
  84015. if (a._distanceToCamera < b._distanceToCamera) {
  84016. return 1;
  84017. }
  84018. if (a._distanceToCamera > b._distanceToCamera) {
  84019. return -1;
  84020. }
  84021. return 0;
  84022. });
  84023. // Render sub meshes
  84024. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  84025. for (index = 0; index < sortedArray.length; index++) {
  84026. renderSubMesh(sortedArray[index]);
  84027. }
  84028. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84029. }
  84030. };
  84031. };
  84032. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  84033. var transform = scene.getTransformMatrix();
  84034. var meshPosition;
  84035. if (this.useCustomMeshPosition) {
  84036. meshPosition = this.customMeshPosition;
  84037. }
  84038. else if (this.attachedNode) {
  84039. meshPosition = this.attachedNode.position;
  84040. }
  84041. else {
  84042. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  84043. }
  84044. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  84045. this._screenCoordinates.x = pos.x / this._viewPort.width;
  84046. this._screenCoordinates.y = pos.y / this._viewPort.height;
  84047. if (this.invert)
  84048. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  84049. };
  84050. // Static methods
  84051. /**
  84052. * Creates a default mesh for the Volumeric Light Scattering post-process
  84053. * @param {string} The mesh name
  84054. * @param {BABYLON.Scene} The scene where to create the mesh
  84055. * @return {BABYLON.Mesh} the default mesh
  84056. */
  84057. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  84058. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  84059. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  84060. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  84061. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  84062. mesh.material = material;
  84063. return mesh;
  84064. };
  84065. __decorate([
  84066. BABYLON.serializeAsVector3()
  84067. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  84068. __decorate([
  84069. BABYLON.serialize()
  84070. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  84071. __decorate([
  84072. BABYLON.serialize()
  84073. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  84074. __decorate([
  84075. BABYLON.serializeAsMeshReference()
  84076. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  84077. __decorate([
  84078. BABYLON.serialize()
  84079. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  84080. __decorate([
  84081. BABYLON.serialize()
  84082. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  84083. __decorate([
  84084. BABYLON.serialize()
  84085. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  84086. __decorate([
  84087. BABYLON.serialize()
  84088. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  84089. __decorate([
  84090. BABYLON.serialize()
  84091. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  84092. return VolumetricLightScatteringPostProcess;
  84093. }(BABYLON.PostProcess));
  84094. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  84095. })(BABYLON || (BABYLON = {}));
  84096. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  84097. //
  84098. // This post-process allows the modification of rendered colors by using
  84099. // a 'look-up table' (LUT). This effect is also called Color Grading.
  84100. //
  84101. // The object needs to be provided an url to a texture containing the color
  84102. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  84103. // Use an image editing software to tweak the LUT to match your needs.
  84104. //
  84105. // For an example of a color LUT, see here:
  84106. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  84107. // For explanations on color grading, see here:
  84108. // http://udn.epicgames.com/Three/ColorGrading.html
  84109. //
  84110. var BABYLON;
  84111. (function (BABYLON) {
  84112. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  84113. __extends(ColorCorrectionPostProcess, _super);
  84114. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  84115. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  84116. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84117. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  84118. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84119. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84120. _this.onApply = function (effect) {
  84121. effect.setTexture("colorTable", _this._colorTableTexture);
  84122. };
  84123. return _this;
  84124. }
  84125. return ColorCorrectionPostProcess;
  84126. }(BABYLON.PostProcess));
  84127. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  84128. })(BABYLON || (BABYLON = {}));
  84129. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  84130. var BABYLON;
  84131. (function (BABYLON) {
  84132. /** Defines operator used for tonemapping */
  84133. var TonemappingOperator;
  84134. (function (TonemappingOperator) {
  84135. /** Hable */
  84136. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  84137. /** Reinhard */
  84138. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  84139. /** HejiDawson */
  84140. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  84141. /** Photographic */
  84142. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  84143. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  84144. ;
  84145. /**
  84146. * Defines a post process to apply tone mapping
  84147. */
  84148. var TonemapPostProcess = /** @class */ (function (_super) {
  84149. __extends(TonemapPostProcess, _super);
  84150. /**
  84151. * Creates a new TonemapPostProcess
  84152. * @param name defines the name of the postprocess
  84153. * @param _operator defines the operator to use
  84154. * @param exposureAdjustment defines the required exposure adjustement
  84155. * @param camera defines the camera to use (can be null)
  84156. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  84157. * @param engine defines the hosting engine (can be ignore if camera is set)
  84158. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  84159. */
  84160. function TonemapPostProcess(name, _operator,
  84161. /** Defines the required exposure adjustement */
  84162. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  84163. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84164. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84165. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  84166. _this._operator = _operator;
  84167. _this.exposureAdjustment = exposureAdjustment;
  84168. var defines = "#define ";
  84169. if (_this._operator === TonemappingOperator.Hable)
  84170. defines += "HABLE_TONEMAPPING";
  84171. else if (_this._operator === TonemappingOperator.Reinhard)
  84172. defines += "REINHARD_TONEMAPPING";
  84173. else if (_this._operator === TonemappingOperator.HejiDawson)
  84174. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  84175. else if (_this._operator === TonemappingOperator.Photographic)
  84176. defines += "PHOTOGRAPHIC_TONEMAPPING";
  84177. //sadly a second call to create the effect.
  84178. _this.updateEffect(defines);
  84179. _this.onApply = function (effect) {
  84180. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  84181. };
  84182. return _this;
  84183. }
  84184. return TonemapPostProcess;
  84185. }(BABYLON.PostProcess));
  84186. BABYLON.TonemapPostProcess = TonemapPostProcess;
  84187. })(BABYLON || (BABYLON = {}));
  84188. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  84189. var BABYLON;
  84190. (function (BABYLON) {
  84191. var DisplayPassPostProcess = /** @class */ (function (_super) {
  84192. __extends(DisplayPassPostProcess, _super);
  84193. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  84194. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  84195. }
  84196. return DisplayPassPostProcess;
  84197. }(BABYLON.PostProcess));
  84198. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  84199. })(BABYLON || (BABYLON = {}));
  84200. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  84201. var BABYLON;
  84202. (function (BABYLON) {
  84203. var HighlightsPostProcess = /** @class */ (function (_super) {
  84204. __extends(HighlightsPostProcess, _super);
  84205. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  84206. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84207. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  84208. }
  84209. return HighlightsPostProcess;
  84210. }(BABYLON.PostProcess));
  84211. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  84212. })(BABYLON || (BABYLON = {}));
  84213. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  84214. var BABYLON;
  84215. (function (BABYLON) {
  84216. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  84217. __extends(ImageProcessingPostProcess, _super);
  84218. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  84219. if (camera === void 0) { camera = null; }
  84220. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84221. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  84222. _this._fromLinearSpace = true;
  84223. /**
  84224. * Defines cache preventing GC.
  84225. */
  84226. _this._defines = {
  84227. IMAGEPROCESSING: false,
  84228. VIGNETTE: false,
  84229. VIGNETTEBLENDMODEMULTIPLY: false,
  84230. VIGNETTEBLENDMODEOPAQUE: false,
  84231. TONEMAPPING: false,
  84232. TONEMAPPING_ACES: false,
  84233. CONTRAST: false,
  84234. COLORCURVES: false,
  84235. COLORGRADING: false,
  84236. COLORGRADING3D: false,
  84237. FROMLINEARSPACE: false,
  84238. SAMPLER3DGREENDEPTH: false,
  84239. SAMPLER3DBGRMAP: false,
  84240. IMAGEPROCESSINGPOSTPROCESS: false,
  84241. EXPOSURE: false,
  84242. };
  84243. // Setup the configuration as forced by the constructor. This would then not force the
  84244. // scene materials output in linear space and let untouched the default forward pass.
  84245. if (imageProcessingConfiguration) {
  84246. imageProcessingConfiguration.applyByPostProcess = true;
  84247. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  84248. // This will cause the shader to be compiled
  84249. _this.fromLinearSpace = false;
  84250. }
  84251. // Setup the default processing configuration to the scene.
  84252. else {
  84253. _this._attachImageProcessingConfiguration(null, true);
  84254. _this.imageProcessingConfiguration.applyByPostProcess = true;
  84255. }
  84256. _this.onApply = function (effect) {
  84257. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  84258. };
  84259. return _this;
  84260. }
  84261. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  84262. /**
  84263. * Gets the image processing configuration used either in this material.
  84264. */
  84265. get: function () {
  84266. return this._imageProcessingConfiguration;
  84267. },
  84268. /**
  84269. * Sets the Default image processing configuration used either in the this material.
  84270. *
  84271. * If sets to null, the scene one is in use.
  84272. */
  84273. set: function (value) {
  84274. this._attachImageProcessingConfiguration(value);
  84275. },
  84276. enumerable: true,
  84277. configurable: true
  84278. });
  84279. /**
  84280. * Attaches a new image processing configuration to the PBR Material.
  84281. * @param configuration
  84282. */
  84283. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  84284. var _this = this;
  84285. if (doNotBuild === void 0) { doNotBuild = false; }
  84286. if (configuration === this._imageProcessingConfiguration) {
  84287. return;
  84288. }
  84289. // Detaches observer.
  84290. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84291. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84292. }
  84293. // Pick the scene configuration if needed.
  84294. if (!configuration) {
  84295. var scene = null;
  84296. var engine = this.getEngine();
  84297. var camera = this.getCamera();
  84298. if (camera) {
  84299. scene = camera.getScene();
  84300. }
  84301. else if (engine && engine.scenes) {
  84302. var scenes = engine.scenes;
  84303. scene = scenes[scenes.length - 1];
  84304. }
  84305. else {
  84306. scene = BABYLON.Engine.LastCreatedScene;
  84307. }
  84308. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  84309. }
  84310. else {
  84311. this._imageProcessingConfiguration = configuration;
  84312. }
  84313. // Attaches observer.
  84314. if (this._imageProcessingConfiguration) {
  84315. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  84316. _this._updateParameters();
  84317. });
  84318. }
  84319. // Ensure the effect will be rebuilt.
  84320. if (!doNotBuild) {
  84321. this._updateParameters();
  84322. }
  84323. };
  84324. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  84325. /**
  84326. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  84327. */
  84328. get: function () {
  84329. return this.imageProcessingConfiguration.colorCurves;
  84330. },
  84331. /**
  84332. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  84333. */
  84334. set: function (value) {
  84335. this.imageProcessingConfiguration.colorCurves = value;
  84336. },
  84337. enumerable: true,
  84338. configurable: true
  84339. });
  84340. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  84341. /**
  84342. * Gets wether the color curves effect is enabled.
  84343. */
  84344. get: function () {
  84345. return this.imageProcessingConfiguration.colorCurvesEnabled;
  84346. },
  84347. /**
  84348. * Sets wether the color curves effect is enabled.
  84349. */
  84350. set: function (value) {
  84351. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  84352. },
  84353. enumerable: true,
  84354. configurable: true
  84355. });
  84356. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  84357. /**
  84358. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  84359. */
  84360. get: function () {
  84361. return this.imageProcessingConfiguration.colorGradingTexture;
  84362. },
  84363. /**
  84364. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  84365. */
  84366. set: function (value) {
  84367. this.imageProcessingConfiguration.colorGradingTexture = value;
  84368. },
  84369. enumerable: true,
  84370. configurable: true
  84371. });
  84372. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  84373. /**
  84374. * Gets wether the color grading effect is enabled.
  84375. */
  84376. get: function () {
  84377. return this.imageProcessingConfiguration.colorGradingEnabled;
  84378. },
  84379. /**
  84380. * Gets wether the color grading effect is enabled.
  84381. */
  84382. set: function (value) {
  84383. this.imageProcessingConfiguration.colorGradingEnabled = value;
  84384. },
  84385. enumerable: true,
  84386. configurable: true
  84387. });
  84388. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  84389. /**
  84390. * Gets exposure used in the effect.
  84391. */
  84392. get: function () {
  84393. return this.imageProcessingConfiguration.exposure;
  84394. },
  84395. /**
  84396. * Sets exposure used in the effect.
  84397. */
  84398. set: function (value) {
  84399. this.imageProcessingConfiguration.exposure = value;
  84400. },
  84401. enumerable: true,
  84402. configurable: true
  84403. });
  84404. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  84405. /**
  84406. * Gets wether tonemapping is enabled or not.
  84407. */
  84408. get: function () {
  84409. return this._imageProcessingConfiguration.toneMappingEnabled;
  84410. },
  84411. /**
  84412. * Sets wether tonemapping is enabled or not
  84413. */
  84414. set: function (value) {
  84415. this._imageProcessingConfiguration.toneMappingEnabled = value;
  84416. },
  84417. enumerable: true,
  84418. configurable: true
  84419. });
  84420. ;
  84421. ;
  84422. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  84423. /**
  84424. * Gets contrast used in the effect.
  84425. */
  84426. get: function () {
  84427. return this.imageProcessingConfiguration.contrast;
  84428. },
  84429. /**
  84430. * Sets contrast used in the effect.
  84431. */
  84432. set: function (value) {
  84433. this.imageProcessingConfiguration.contrast = value;
  84434. },
  84435. enumerable: true,
  84436. configurable: true
  84437. });
  84438. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  84439. /**
  84440. * Gets Vignette stretch size.
  84441. */
  84442. get: function () {
  84443. return this.imageProcessingConfiguration.vignetteStretch;
  84444. },
  84445. /**
  84446. * Sets Vignette stretch size.
  84447. */
  84448. set: function (value) {
  84449. this.imageProcessingConfiguration.vignetteStretch = value;
  84450. },
  84451. enumerable: true,
  84452. configurable: true
  84453. });
  84454. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  84455. /**
  84456. * Gets Vignette centre X Offset.
  84457. */
  84458. get: function () {
  84459. return this.imageProcessingConfiguration.vignetteCentreX;
  84460. },
  84461. /**
  84462. * Sets Vignette centre X Offset.
  84463. */
  84464. set: function (value) {
  84465. this.imageProcessingConfiguration.vignetteCentreX = value;
  84466. },
  84467. enumerable: true,
  84468. configurable: true
  84469. });
  84470. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  84471. /**
  84472. * Gets Vignette centre Y Offset.
  84473. */
  84474. get: function () {
  84475. return this.imageProcessingConfiguration.vignetteCentreY;
  84476. },
  84477. /**
  84478. * Sets Vignette centre Y Offset.
  84479. */
  84480. set: function (value) {
  84481. this.imageProcessingConfiguration.vignetteCentreY = value;
  84482. },
  84483. enumerable: true,
  84484. configurable: true
  84485. });
  84486. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  84487. /**
  84488. * Gets Vignette weight or intensity of the vignette effect.
  84489. */
  84490. get: function () {
  84491. return this.imageProcessingConfiguration.vignetteWeight;
  84492. },
  84493. /**
  84494. * Sets Vignette weight or intensity of the vignette effect.
  84495. */
  84496. set: function (value) {
  84497. this.imageProcessingConfiguration.vignetteWeight = value;
  84498. },
  84499. enumerable: true,
  84500. configurable: true
  84501. });
  84502. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  84503. /**
  84504. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84505. * if vignetteEnabled is set to true.
  84506. */
  84507. get: function () {
  84508. return this.imageProcessingConfiguration.vignetteColor;
  84509. },
  84510. /**
  84511. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84512. * if vignetteEnabled is set to true.
  84513. */
  84514. set: function (value) {
  84515. this.imageProcessingConfiguration.vignetteColor = value;
  84516. },
  84517. enumerable: true,
  84518. configurable: true
  84519. });
  84520. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  84521. /**
  84522. * Gets Camera field of view used by the Vignette effect.
  84523. */
  84524. get: function () {
  84525. return this.imageProcessingConfiguration.vignetteCameraFov;
  84526. },
  84527. /**
  84528. * Sets Camera field of view used by the Vignette effect.
  84529. */
  84530. set: function (value) {
  84531. this.imageProcessingConfiguration.vignetteCameraFov = value;
  84532. },
  84533. enumerable: true,
  84534. configurable: true
  84535. });
  84536. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  84537. /**
  84538. * Gets the vignette blend mode allowing different kind of effect.
  84539. */
  84540. get: function () {
  84541. return this.imageProcessingConfiguration.vignetteBlendMode;
  84542. },
  84543. /**
  84544. * Sets the vignette blend mode allowing different kind of effect.
  84545. */
  84546. set: function (value) {
  84547. this.imageProcessingConfiguration.vignetteBlendMode = value;
  84548. },
  84549. enumerable: true,
  84550. configurable: true
  84551. });
  84552. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  84553. /**
  84554. * Gets wether the vignette effect is enabled.
  84555. */
  84556. get: function () {
  84557. return this.imageProcessingConfiguration.vignetteEnabled;
  84558. },
  84559. /**
  84560. * Sets wether the vignette effect is enabled.
  84561. */
  84562. set: function (value) {
  84563. this.imageProcessingConfiguration.vignetteEnabled = value;
  84564. },
  84565. enumerable: true,
  84566. configurable: true
  84567. });
  84568. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  84569. /**
  84570. * Gets wether the input of the processing is in Gamma or Linear Space.
  84571. */
  84572. get: function () {
  84573. return this._fromLinearSpace;
  84574. },
  84575. /**
  84576. * Sets wether the input of the processing is in Gamma or Linear Space.
  84577. */
  84578. set: function (value) {
  84579. if (this._fromLinearSpace === value) {
  84580. return;
  84581. }
  84582. this._fromLinearSpace = value;
  84583. this._updateParameters();
  84584. },
  84585. enumerable: true,
  84586. configurable: true
  84587. });
  84588. ImageProcessingPostProcess.prototype.getClassName = function () {
  84589. return "ImageProcessingPostProcess";
  84590. };
  84591. ImageProcessingPostProcess.prototype._updateParameters = function () {
  84592. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  84593. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  84594. var defines = "";
  84595. for (var define in this._defines) {
  84596. if (this._defines[define]) {
  84597. defines += "#define " + define + ";\r\n";
  84598. }
  84599. }
  84600. var samplers = ["textureSampler"];
  84601. var uniforms = ["scale"];
  84602. if (BABYLON.ImageProcessingConfiguration) {
  84603. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  84604. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  84605. }
  84606. this.updateEffect(defines, uniforms, samplers);
  84607. };
  84608. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  84609. _super.prototype.dispose.call(this, camera);
  84610. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84611. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84612. }
  84613. if (this._imageProcessingConfiguration) {
  84614. this.imageProcessingConfiguration.applyByPostProcess = false;
  84615. }
  84616. };
  84617. __decorate([
  84618. BABYLON.serialize()
  84619. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  84620. return ImageProcessingPostProcess;
  84621. }(BABYLON.PostProcess));
  84622. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  84623. })(BABYLON || (BABYLON = {}));
  84624. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  84625. var BABYLON;
  84626. (function (BABYLON) {
  84627. /**
  84628. * Class used to store bone information
  84629. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  84630. */
  84631. var Bone = /** @class */ (function (_super) {
  84632. __extends(Bone, _super);
  84633. /**
  84634. * Create a new bone
  84635. * @param name defines the bone name
  84636. * @param skeleton defines the parent skeleton
  84637. * @param parentBone defines the parent (can be null if the bone is the root)
  84638. * @param localMatrix defines the local matrix
  84639. * @param restPose defines the rest pose matrix
  84640. * @param baseMatrix defines the base matrix
  84641. * @param index defines index of the bone in the hiearchy
  84642. */
  84643. function Bone(
  84644. /**
  84645. * defines the bone name
  84646. */
  84647. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  84648. if (parentBone === void 0) { parentBone = null; }
  84649. if (localMatrix === void 0) { localMatrix = null; }
  84650. if (restPose === void 0) { restPose = null; }
  84651. if (baseMatrix === void 0) { baseMatrix = null; }
  84652. if (index === void 0) { index = null; }
  84653. var _this = _super.call(this, name, skeleton.getScene()) || this;
  84654. _this.name = name;
  84655. /**
  84656. * Gets the list of child bones
  84657. */
  84658. _this.children = new Array();
  84659. /** Gets the animations associated with this bone */
  84660. _this.animations = new Array();
  84661. /**
  84662. * @hidden Internal only
  84663. * Set this value to map this bone to a different index in the transform matrices
  84664. * Set this value to -1 to exclude the bone from the transform matrices
  84665. */
  84666. _this._index = null;
  84667. _this._absoluteTransform = new BABYLON.Matrix();
  84668. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  84669. _this._scalingDeterminant = 1;
  84670. _this._worldTransform = new BABYLON.Matrix();
  84671. _this._needToDecompose = true;
  84672. _this._needToCompose = false;
  84673. _this._skeleton = skeleton;
  84674. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  84675. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  84676. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  84677. _this._index = index;
  84678. skeleton.bones.push(_this);
  84679. _this.setParent(parentBone, false);
  84680. if (baseMatrix || localMatrix) {
  84681. _this._updateDifferenceMatrix();
  84682. }
  84683. return _this;
  84684. }
  84685. Object.defineProperty(Bone.prototype, "_matrix", {
  84686. /** @hidden */
  84687. get: function () {
  84688. this._compose();
  84689. return this._localMatrix;
  84690. },
  84691. /** @hidden */
  84692. set: function (value) {
  84693. this._localMatrix.copyFrom(value);
  84694. this._needToDecompose = true;
  84695. },
  84696. enumerable: true,
  84697. configurable: true
  84698. });
  84699. // Members
  84700. /**
  84701. * Gets the parent skeleton
  84702. * @returns a skeleton
  84703. */
  84704. Bone.prototype.getSkeleton = function () {
  84705. return this._skeleton;
  84706. };
  84707. /**
  84708. * Gets parent bone
  84709. * @returns a bone or null if the bone is the root of the bone hierarchy
  84710. */
  84711. Bone.prototype.getParent = function () {
  84712. return this._parent;
  84713. };
  84714. /**
  84715. * Sets the parent bone
  84716. * @param parent defines the parent (can be null if the bone is the root)
  84717. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84718. */
  84719. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  84720. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84721. if (this._parent === parent) {
  84722. return;
  84723. }
  84724. if (this._parent) {
  84725. var index = this._parent.children.indexOf(this);
  84726. if (index !== -1) {
  84727. this._parent.children.splice(index, 1);
  84728. }
  84729. }
  84730. this._parent = parent;
  84731. if (this._parent) {
  84732. this._parent.children.push(this);
  84733. }
  84734. if (updateDifferenceMatrix) {
  84735. this._updateDifferenceMatrix();
  84736. }
  84737. this.markAsDirty();
  84738. };
  84739. /**
  84740. * Gets the local matrix
  84741. * @returns a matrix
  84742. */
  84743. Bone.prototype.getLocalMatrix = function () {
  84744. this._compose();
  84745. return this._localMatrix;
  84746. };
  84747. /**
  84748. * Gets the base matrix (initial matrix which remains unchanged)
  84749. * @returns a matrix
  84750. */
  84751. Bone.prototype.getBaseMatrix = function () {
  84752. return this._baseMatrix;
  84753. };
  84754. /**
  84755. * Gets the rest pose matrix
  84756. * @returns a matrix
  84757. */
  84758. Bone.prototype.getRestPose = function () {
  84759. return this._restPose;
  84760. };
  84761. /**
  84762. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  84763. */
  84764. Bone.prototype.getWorldMatrix = function () {
  84765. return this._worldTransform;
  84766. };
  84767. /**
  84768. * Sets the local matrix to rest pose matrix
  84769. */
  84770. Bone.prototype.returnToRest = function () {
  84771. this.updateMatrix(this._restPose.clone());
  84772. };
  84773. /**
  84774. * Gets the inverse of the absolute transform matrix.
  84775. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  84776. * @returns a matrix
  84777. */
  84778. Bone.prototype.getInvertedAbsoluteTransform = function () {
  84779. return this._invertedAbsoluteTransform;
  84780. };
  84781. /**
  84782. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  84783. * @returns a matrix
  84784. */
  84785. Bone.prototype.getAbsoluteTransform = function () {
  84786. return this._absoluteTransform;
  84787. };
  84788. Object.defineProperty(Bone.prototype, "position", {
  84789. // Properties (matches AbstractMesh properties)
  84790. /** Gets or sets current position (in local space) */
  84791. get: function () {
  84792. this._decompose();
  84793. return this._localPosition;
  84794. },
  84795. set: function (newPosition) {
  84796. this._decompose();
  84797. this._localPosition.copyFrom(newPosition);
  84798. this._markAsDirtyAndCompose();
  84799. },
  84800. enumerable: true,
  84801. configurable: true
  84802. });
  84803. Object.defineProperty(Bone.prototype, "rotation", {
  84804. /** Gets or sets current rotation (in local space) */
  84805. get: function () {
  84806. return this.getRotation();
  84807. },
  84808. set: function (newRotation) {
  84809. this.setRotation(newRotation);
  84810. },
  84811. enumerable: true,
  84812. configurable: true
  84813. });
  84814. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  84815. /** Gets or sets current rotation quaternion (in local space) */
  84816. get: function () {
  84817. this._decompose();
  84818. return this._localRotation;
  84819. },
  84820. set: function (newRotation) {
  84821. this.setRotationQuaternion(newRotation);
  84822. },
  84823. enumerable: true,
  84824. configurable: true
  84825. });
  84826. Object.defineProperty(Bone.prototype, "scaling", {
  84827. /** Gets or sets current scaling (in local space) */
  84828. get: function () {
  84829. return this.getScale();
  84830. },
  84831. set: function (newScaling) {
  84832. this.setScale(newScaling);
  84833. },
  84834. enumerable: true,
  84835. configurable: true
  84836. });
  84837. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  84838. /**
  84839. * Gets the animation properties override
  84840. */
  84841. get: function () {
  84842. return this._skeleton.animationPropertiesOverride;
  84843. },
  84844. enumerable: true,
  84845. configurable: true
  84846. });
  84847. // Methods
  84848. Bone.prototype._decompose = function () {
  84849. if (!this._needToDecompose) {
  84850. return;
  84851. }
  84852. this._needToDecompose = false;
  84853. if (!this._localScaling) {
  84854. this._localScaling = BABYLON.Vector3.Zero();
  84855. this._localRotation = BABYLON.Quaternion.Zero();
  84856. this._localPosition = BABYLON.Vector3.Zero();
  84857. }
  84858. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  84859. };
  84860. Bone.prototype._compose = function () {
  84861. if (!this._needToCompose) {
  84862. return;
  84863. }
  84864. this._needToCompose = false;
  84865. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  84866. };
  84867. /**
  84868. * Update the base and local matrices
  84869. * @param matrix defines the new base or local matrix
  84870. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84871. * @param updateLocalMatrix defines if the local matrix should be updated
  84872. */
  84873. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  84874. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84875. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  84876. this._baseMatrix.copyFrom(matrix);
  84877. if (updateDifferenceMatrix) {
  84878. this._updateDifferenceMatrix();
  84879. }
  84880. if (updateLocalMatrix) {
  84881. this._localMatrix.copyFrom(matrix);
  84882. this._markAsDirtyAndDecompose();
  84883. }
  84884. else {
  84885. this.markAsDirty();
  84886. }
  84887. };
  84888. /** @hidden */
  84889. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  84890. if (updateChildren === void 0) { updateChildren = true; }
  84891. if (!rootMatrix) {
  84892. rootMatrix = this._baseMatrix;
  84893. }
  84894. if (this._parent) {
  84895. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84896. }
  84897. else {
  84898. this._absoluteTransform.copyFrom(rootMatrix);
  84899. }
  84900. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  84901. if (updateChildren) {
  84902. for (var index = 0; index < this.children.length; index++) {
  84903. this.children[index]._updateDifferenceMatrix();
  84904. }
  84905. }
  84906. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  84907. };
  84908. /**
  84909. * Flag the bone as dirty (Forcing it to update everything)
  84910. */
  84911. Bone.prototype.markAsDirty = function () {
  84912. this._currentRenderId++;
  84913. this._childRenderId++;
  84914. this._skeleton._markAsDirty();
  84915. };
  84916. Bone.prototype._markAsDirtyAndCompose = function () {
  84917. this.markAsDirty();
  84918. this._needToCompose = true;
  84919. };
  84920. Bone.prototype._markAsDirtyAndDecompose = function () {
  84921. this.markAsDirty();
  84922. this._needToDecompose = true;
  84923. };
  84924. /**
  84925. * Copy an animation range from another bone
  84926. * @param source defines the source bone
  84927. * @param rangeName defines the range name to copy
  84928. * @param frameOffset defines the frame offset
  84929. * @param rescaleAsRequired defines if rescaling must be applied if required
  84930. * @param skelDimensionsRatio defines the scaling ratio
  84931. * @returns true if operation was successful
  84932. */
  84933. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  84934. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84935. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  84936. // all animation may be coming from a library skeleton, so may need to create animation
  84937. if (this.animations.length === 0) {
  84938. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  84939. this.animations[0].setKeys([]);
  84940. }
  84941. // get animation info / verify there is such a range from the source bone
  84942. var sourceRange = source.animations[0].getRange(rangeName);
  84943. if (!sourceRange) {
  84944. return false;
  84945. }
  84946. var from = sourceRange.from;
  84947. var to = sourceRange.to;
  84948. var sourceKeys = source.animations[0].getKeys();
  84949. // rescaling prep
  84950. var sourceBoneLength = source.length;
  84951. var sourceParent = source.getParent();
  84952. var parent = this.getParent();
  84953. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  84954. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  84955. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  84956. var destKeys = this.animations[0].getKeys();
  84957. // loop vars declaration
  84958. var orig;
  84959. var origTranslation;
  84960. var mat;
  84961. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  84962. orig = sourceKeys[key];
  84963. if (orig.frame >= from && orig.frame <= to) {
  84964. if (rescaleAsRequired) {
  84965. mat = orig.value.clone();
  84966. // scale based on parent ratio, when bone has parent
  84967. if (parentScalingReqd) {
  84968. origTranslation = mat.getTranslation();
  84969. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  84970. // scale based on skeleton dimension ratio when root bone, and value is passed
  84971. }
  84972. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  84973. origTranslation = mat.getTranslation();
  84974. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  84975. // use original when root bone, and no data for skelDimensionsRatio
  84976. }
  84977. else {
  84978. mat = orig.value;
  84979. }
  84980. }
  84981. else {
  84982. mat = orig.value;
  84983. }
  84984. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  84985. }
  84986. }
  84987. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  84988. return true;
  84989. };
  84990. /**
  84991. * Translate the bone in local or world space
  84992. * @param vec The amount to translate the bone
  84993. * @param space The space that the translation is in
  84994. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84995. */
  84996. Bone.prototype.translate = function (vec, space, mesh) {
  84997. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84998. var lm = this.getLocalMatrix();
  84999. if (space == BABYLON.Space.LOCAL) {
  85000. lm.m[12] += vec.x;
  85001. lm.m[13] += vec.y;
  85002. lm.m[14] += vec.z;
  85003. }
  85004. else {
  85005. var wm = null;
  85006. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85007. if (mesh) {
  85008. wm = mesh.getWorldMatrix();
  85009. }
  85010. this._skeleton.computeAbsoluteTransforms();
  85011. var tmat = Bone._tmpMats[0];
  85012. var tvec = Bone._tmpVecs[0];
  85013. if (this._parent) {
  85014. if (mesh && wm) {
  85015. tmat.copyFrom(this._parent.getAbsoluteTransform());
  85016. tmat.multiplyToRef(wm, tmat);
  85017. }
  85018. else {
  85019. tmat.copyFrom(this._parent.getAbsoluteTransform());
  85020. }
  85021. }
  85022. tmat.m[12] = 0;
  85023. tmat.m[13] = 0;
  85024. tmat.m[14] = 0;
  85025. tmat.invert();
  85026. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  85027. lm.m[12] += tvec.x;
  85028. lm.m[13] += tvec.y;
  85029. lm.m[14] += tvec.z;
  85030. }
  85031. this._markAsDirtyAndDecompose();
  85032. };
  85033. /**
  85034. * Set the postion of the bone in local or world space
  85035. * @param position The position to set the bone
  85036. * @param space The space that the position is in
  85037. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85038. */
  85039. Bone.prototype.setPosition = function (position, space, mesh) {
  85040. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85041. var lm = this.getLocalMatrix();
  85042. if (space == BABYLON.Space.LOCAL) {
  85043. lm.m[12] = position.x;
  85044. lm.m[13] = position.y;
  85045. lm.m[14] = position.z;
  85046. }
  85047. else {
  85048. var wm = null;
  85049. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85050. if (mesh) {
  85051. wm = mesh.getWorldMatrix();
  85052. }
  85053. this._skeleton.computeAbsoluteTransforms();
  85054. var tmat = Bone._tmpMats[0];
  85055. var vec = Bone._tmpVecs[0];
  85056. if (this._parent) {
  85057. if (mesh && wm) {
  85058. tmat.copyFrom(this._parent.getAbsoluteTransform());
  85059. tmat.multiplyToRef(wm, tmat);
  85060. }
  85061. else {
  85062. tmat.copyFrom(this._parent.getAbsoluteTransform());
  85063. }
  85064. }
  85065. tmat.invert();
  85066. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  85067. lm.m[12] = vec.x;
  85068. lm.m[13] = vec.y;
  85069. lm.m[14] = vec.z;
  85070. }
  85071. this._markAsDirtyAndDecompose();
  85072. };
  85073. /**
  85074. * Set the absolute position of the bone (world space)
  85075. * @param position The position to set the bone
  85076. * @param mesh The mesh that this bone is attached to
  85077. */
  85078. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  85079. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  85080. };
  85081. /**
  85082. * Scale the bone on the x, y and z axes (in local space)
  85083. * @param x The amount to scale the bone on the x axis
  85084. * @param y The amount to scale the bone on the y axis
  85085. * @param z The amount to scale the bone on the z axis
  85086. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  85087. */
  85088. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  85089. if (scaleChildren === void 0) { scaleChildren = false; }
  85090. var locMat = this.getLocalMatrix();
  85091. // Apply new scaling on top of current local matrix
  85092. var scaleMat = Bone._tmpMats[0];
  85093. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  85094. scaleMat.multiplyToRef(locMat, locMat);
  85095. // Invert scaling matrix and apply the inverse to all children
  85096. scaleMat.invert();
  85097. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  85098. var child = _a[_i];
  85099. var cm = child.getLocalMatrix();
  85100. cm.multiplyToRef(scaleMat, cm);
  85101. cm.m[12] *= x;
  85102. cm.m[13] *= y;
  85103. cm.m[14] *= z;
  85104. child._markAsDirtyAndDecompose();
  85105. }
  85106. this._markAsDirtyAndDecompose();
  85107. if (scaleChildren) {
  85108. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  85109. var child = _c[_b];
  85110. child.scale(x, y, z, scaleChildren);
  85111. }
  85112. }
  85113. };
  85114. /**
  85115. * Set the bone scaling in local space
  85116. * @param scale defines the scaling vector
  85117. */
  85118. Bone.prototype.setScale = function (scale) {
  85119. this._decompose();
  85120. this._localScaling.copyFrom(scale);
  85121. this._markAsDirtyAndCompose();
  85122. };
  85123. /**
  85124. * Gets the current scaling in local space
  85125. * @returns the current scaling vector
  85126. */
  85127. Bone.prototype.getScale = function () {
  85128. this._decompose();
  85129. return this._localScaling;
  85130. };
  85131. /**
  85132. * Gets the current scaling in local space and stores it in a target vector
  85133. * @param result defines the target vector
  85134. */
  85135. Bone.prototype.getScaleToRef = function (result) {
  85136. this._decompose();
  85137. result.copyFrom(this._localScaling);
  85138. };
  85139. /**
  85140. * Set the yaw, pitch, and roll of the bone in local or world space
  85141. * @param yaw The rotation of the bone on the y axis
  85142. * @param pitch The rotation of the bone on the x axis
  85143. * @param roll The rotation of the bone on the z axis
  85144. * @param space The space that the axes of rotation are in
  85145. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85146. */
  85147. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  85148. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85149. if (space === BABYLON.Space.LOCAL) {
  85150. var quat = Bone._tmpQuat;
  85151. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  85152. this.setRotationQuaternion(quat, space, mesh);
  85153. return;
  85154. }
  85155. var rotMatInv = Bone._tmpMats[0];
  85156. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  85157. return;
  85158. }
  85159. var rotMat = Bone._tmpMats[1];
  85160. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  85161. rotMatInv.multiplyToRef(rotMat, rotMat);
  85162. this._rotateWithMatrix(rotMat, space, mesh);
  85163. };
  85164. /**
  85165. * Add a rotation to the bone on an axis in local or world space
  85166. * @param axis The axis to rotate the bone on
  85167. * @param amount The amount to rotate the bone
  85168. * @param space The space that the axis is in
  85169. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85170. */
  85171. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  85172. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85173. var rmat = Bone._tmpMats[0];
  85174. rmat.m[12] = 0;
  85175. rmat.m[13] = 0;
  85176. rmat.m[14] = 0;
  85177. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  85178. this._rotateWithMatrix(rmat, space, mesh);
  85179. };
  85180. /**
  85181. * Set the rotation of the bone to a particular axis angle in local or world space
  85182. * @param axis The axis to rotate the bone on
  85183. * @param angle The angle that the bone should be rotated to
  85184. * @param space The space that the axis is in
  85185. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85186. */
  85187. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  85188. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85189. if (space === BABYLON.Space.LOCAL) {
  85190. var quat = Bone._tmpQuat;
  85191. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  85192. this.setRotationQuaternion(quat, space, mesh);
  85193. return;
  85194. }
  85195. var rotMatInv = Bone._tmpMats[0];
  85196. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  85197. return;
  85198. }
  85199. var rotMat = Bone._tmpMats[1];
  85200. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  85201. rotMatInv.multiplyToRef(rotMat, rotMat);
  85202. this._rotateWithMatrix(rotMat, space, mesh);
  85203. };
  85204. /**
  85205. * Set the euler rotation of the bone in local of world space
  85206. * @param rotation The euler rotation that the bone should be set to
  85207. * @param space The space that the rotation is in
  85208. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85209. */
  85210. Bone.prototype.setRotation = function (rotation, space, mesh) {
  85211. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85212. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  85213. };
  85214. /**
  85215. * Set the quaternion rotation of the bone in local of world space
  85216. * @param quat The quaternion rotation that the bone should be set to
  85217. * @param space The space that the rotation is in
  85218. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85219. */
  85220. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  85221. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85222. if (space === BABYLON.Space.LOCAL) {
  85223. this._decompose();
  85224. this._localRotation.copyFrom(quat);
  85225. this._markAsDirtyAndCompose();
  85226. return;
  85227. }
  85228. var rotMatInv = Bone._tmpMats[0];
  85229. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  85230. return;
  85231. }
  85232. var rotMat = Bone._tmpMats[1];
  85233. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  85234. rotMatInv.multiplyToRef(rotMat, rotMat);
  85235. this._rotateWithMatrix(rotMat, space, mesh);
  85236. };
  85237. /**
  85238. * Set the rotation matrix of the bone in local of world space
  85239. * @param rotMat The rotation matrix that the bone should be set to
  85240. * @param space The space that the rotation is in
  85241. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85242. */
  85243. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  85244. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85245. if (space === BABYLON.Space.LOCAL) {
  85246. var quat = Bone._tmpQuat;
  85247. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  85248. this.setRotationQuaternion(quat, space, mesh);
  85249. return;
  85250. }
  85251. var rotMatInv = Bone._tmpMats[0];
  85252. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  85253. return;
  85254. }
  85255. var rotMat2 = Bone._tmpMats[1];
  85256. rotMat2.copyFrom(rotMat);
  85257. rotMatInv.multiplyToRef(rotMat, rotMat2);
  85258. this._rotateWithMatrix(rotMat2, space, mesh);
  85259. };
  85260. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  85261. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85262. var lmat = this.getLocalMatrix();
  85263. var lx = lmat.m[12];
  85264. var ly = lmat.m[13];
  85265. var lz = lmat.m[14];
  85266. var parent = this.getParent();
  85267. var parentScale = Bone._tmpMats[3];
  85268. var parentScaleInv = Bone._tmpMats[4];
  85269. if (parent && space == BABYLON.Space.WORLD) {
  85270. if (mesh) {
  85271. parentScale.copyFrom(mesh.getWorldMatrix());
  85272. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  85273. }
  85274. else {
  85275. parentScale.copyFrom(parent.getAbsoluteTransform());
  85276. }
  85277. parentScaleInv.copyFrom(parentScale);
  85278. parentScaleInv.invert();
  85279. lmat.multiplyToRef(parentScale, lmat);
  85280. lmat.multiplyToRef(rmat, lmat);
  85281. lmat.multiplyToRef(parentScaleInv, lmat);
  85282. }
  85283. else {
  85284. if (space == BABYLON.Space.WORLD && mesh) {
  85285. parentScale.copyFrom(mesh.getWorldMatrix());
  85286. parentScaleInv.copyFrom(parentScale);
  85287. parentScaleInv.invert();
  85288. lmat.multiplyToRef(parentScale, lmat);
  85289. lmat.multiplyToRef(rmat, lmat);
  85290. lmat.multiplyToRef(parentScaleInv, lmat);
  85291. }
  85292. else {
  85293. lmat.multiplyToRef(rmat, lmat);
  85294. }
  85295. }
  85296. lmat.m[12] = lx;
  85297. lmat.m[13] = ly;
  85298. lmat.m[14] = lz;
  85299. this.computeAbsoluteTransforms();
  85300. this._markAsDirtyAndDecompose();
  85301. };
  85302. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  85303. var scaleMatrix = Bone._tmpMats[2];
  85304. rotMatInv.copyFrom(this.getAbsoluteTransform());
  85305. if (mesh) {
  85306. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  85307. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  85308. }
  85309. rotMatInv.invert();
  85310. if (isNaN(rotMatInv.m[0])) {
  85311. // Matrix failed to invert.
  85312. // This can happen if scale is zero for example.
  85313. return false;
  85314. }
  85315. scaleMatrix.m[0] *= this._scalingDeterminant;
  85316. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  85317. return true;
  85318. };
  85319. /**
  85320. * Get the position of the bone in local or world space
  85321. * @param space The space that the returned position is in
  85322. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85323. * @returns The position of the bone
  85324. */
  85325. Bone.prototype.getPosition = function (space, mesh) {
  85326. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85327. if (mesh === void 0) { mesh = null; }
  85328. var pos = BABYLON.Vector3.Zero();
  85329. this.getPositionToRef(space, mesh, pos);
  85330. return pos;
  85331. };
  85332. /**
  85333. * Copy the position of the bone to a vector3 in local or world space
  85334. * @param space The space that the returned position is in
  85335. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85336. * @param result The vector3 to copy the position to
  85337. */
  85338. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  85339. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85340. if (space == BABYLON.Space.LOCAL) {
  85341. var lm = this.getLocalMatrix();
  85342. result.x = lm.m[12];
  85343. result.y = lm.m[13];
  85344. result.z = lm.m[14];
  85345. }
  85346. else {
  85347. var wm = null;
  85348. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85349. if (mesh) {
  85350. wm = mesh.getWorldMatrix();
  85351. }
  85352. this._skeleton.computeAbsoluteTransforms();
  85353. var tmat = Bone._tmpMats[0];
  85354. if (mesh && wm) {
  85355. tmat.copyFrom(this.getAbsoluteTransform());
  85356. tmat.multiplyToRef(wm, tmat);
  85357. }
  85358. else {
  85359. tmat = this.getAbsoluteTransform();
  85360. }
  85361. result.x = tmat.m[12];
  85362. result.y = tmat.m[13];
  85363. result.z = tmat.m[14];
  85364. }
  85365. };
  85366. /**
  85367. * Get the absolute position of the bone (world space)
  85368. * @param mesh The mesh that this bone is attached to
  85369. * @returns The absolute position of the bone
  85370. */
  85371. Bone.prototype.getAbsolutePosition = function (mesh) {
  85372. if (mesh === void 0) { mesh = null; }
  85373. var pos = BABYLON.Vector3.Zero();
  85374. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  85375. return pos;
  85376. };
  85377. /**
  85378. * Copy the absolute position of the bone (world space) to the result param
  85379. * @param mesh The mesh that this bone is attached to
  85380. * @param result The vector3 to copy the absolute position to
  85381. */
  85382. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  85383. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  85384. };
  85385. /**
  85386. * Compute the absolute transforms of this bone and its children
  85387. */
  85388. Bone.prototype.computeAbsoluteTransforms = function () {
  85389. this._compose();
  85390. if (this._parent) {
  85391. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  85392. }
  85393. else {
  85394. this._absoluteTransform.copyFrom(this._localMatrix);
  85395. var poseMatrix = this._skeleton.getPoseMatrix();
  85396. if (poseMatrix) {
  85397. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  85398. }
  85399. }
  85400. var children = this.children;
  85401. var len = children.length;
  85402. for (var i = 0; i < len; i++) {
  85403. children[i].computeAbsoluteTransforms();
  85404. }
  85405. };
  85406. /**
  85407. * Get the world direction from an axis that is in the local space of the bone
  85408. * @param localAxis The local direction that is used to compute the world direction
  85409. * @param mesh The mesh that this bone is attached to
  85410. * @returns The world direction
  85411. */
  85412. Bone.prototype.getDirection = function (localAxis, mesh) {
  85413. if (mesh === void 0) { mesh = null; }
  85414. var result = BABYLON.Vector3.Zero();
  85415. this.getDirectionToRef(localAxis, mesh, result);
  85416. return result;
  85417. };
  85418. /**
  85419. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  85420. * @param localAxis The local direction that is used to compute the world direction
  85421. * @param mesh The mesh that this bone is attached to
  85422. * @param result The vector3 that the world direction will be copied to
  85423. */
  85424. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  85425. if (mesh === void 0) { mesh = null; }
  85426. var wm = null;
  85427. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85428. if (mesh) {
  85429. wm = mesh.getWorldMatrix();
  85430. }
  85431. this._skeleton.computeAbsoluteTransforms();
  85432. var mat = Bone._tmpMats[0];
  85433. mat.copyFrom(this.getAbsoluteTransform());
  85434. if (mesh && wm) {
  85435. mat.multiplyToRef(wm, mat);
  85436. }
  85437. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  85438. result.normalize();
  85439. };
  85440. /**
  85441. * Get the euler rotation of the bone in local or world space
  85442. * @param space The space that the rotation should be in
  85443. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85444. * @returns The euler rotation
  85445. */
  85446. Bone.prototype.getRotation = function (space, mesh) {
  85447. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85448. if (mesh === void 0) { mesh = null; }
  85449. var result = BABYLON.Vector3.Zero();
  85450. this.getRotationToRef(space, mesh, result);
  85451. return result;
  85452. };
  85453. /**
  85454. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  85455. * @param space The space that the rotation should be in
  85456. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85457. * @param result The vector3 that the rotation should be copied to
  85458. */
  85459. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  85460. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85461. if (mesh === void 0) { mesh = null; }
  85462. var quat = Bone._tmpQuat;
  85463. this.getRotationQuaternionToRef(space, mesh, quat);
  85464. quat.toEulerAnglesToRef(result);
  85465. };
  85466. /**
  85467. * Get the quaternion rotation of the bone in either local or world space
  85468. * @param space The space that the rotation should be in
  85469. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85470. * @returns The quaternion rotation
  85471. */
  85472. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  85473. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85474. if (mesh === void 0) { mesh = null; }
  85475. var result = BABYLON.Quaternion.Identity();
  85476. this.getRotationQuaternionToRef(space, mesh, result);
  85477. return result;
  85478. };
  85479. /**
  85480. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  85481. * @param space The space that the rotation should be in
  85482. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85483. * @param result The quaternion that the rotation should be copied to
  85484. */
  85485. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  85486. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85487. if (mesh === void 0) { mesh = null; }
  85488. if (space == BABYLON.Space.LOCAL) {
  85489. this._decompose();
  85490. result.copyFrom(this._localRotation);
  85491. }
  85492. else {
  85493. var mat = Bone._tmpMats[0];
  85494. var amat = this.getAbsoluteTransform();
  85495. if (mesh) {
  85496. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  85497. }
  85498. else {
  85499. mat.copyFrom(amat);
  85500. }
  85501. mat.m[0] *= this._scalingDeterminant;
  85502. mat.m[1] *= this._scalingDeterminant;
  85503. mat.m[2] *= this._scalingDeterminant;
  85504. mat.decompose(undefined, result, undefined);
  85505. }
  85506. };
  85507. /**
  85508. * Get the rotation matrix of the bone in local or world space
  85509. * @param space The space that the rotation should be in
  85510. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85511. * @returns The rotation matrix
  85512. */
  85513. Bone.prototype.getRotationMatrix = function (space, mesh) {
  85514. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85515. var result = BABYLON.Matrix.Identity();
  85516. this.getRotationMatrixToRef(space, mesh, result);
  85517. return result;
  85518. };
  85519. /**
  85520. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  85521. * @param space The space that the rotation should be in
  85522. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85523. * @param result The quaternion that the rotation should be copied to
  85524. */
  85525. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  85526. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85527. if (space == BABYLON.Space.LOCAL) {
  85528. this.getLocalMatrix().getRotationMatrixToRef(result);
  85529. }
  85530. else {
  85531. var mat = Bone._tmpMats[0];
  85532. var amat = this.getAbsoluteTransform();
  85533. if (mesh) {
  85534. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  85535. }
  85536. else {
  85537. mat.copyFrom(amat);
  85538. }
  85539. mat.m[0] *= this._scalingDeterminant;
  85540. mat.m[1] *= this._scalingDeterminant;
  85541. mat.m[2] *= this._scalingDeterminant;
  85542. mat.getRotationMatrixToRef(result);
  85543. }
  85544. };
  85545. /**
  85546. * Get the world position of a point that is in the local space of the bone
  85547. * @param position The local position
  85548. * @param mesh The mesh that this bone is attached to
  85549. * @returns The world position
  85550. */
  85551. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  85552. if (mesh === void 0) { mesh = null; }
  85553. var result = BABYLON.Vector3.Zero();
  85554. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  85555. return result;
  85556. };
  85557. /**
  85558. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  85559. * @param position The local position
  85560. * @param mesh The mesh that this bone is attached to
  85561. * @param result The vector3 that the world position should be copied to
  85562. */
  85563. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  85564. if (mesh === void 0) { mesh = null; }
  85565. var wm = null;
  85566. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85567. if (mesh) {
  85568. wm = mesh.getWorldMatrix();
  85569. }
  85570. this._skeleton.computeAbsoluteTransforms();
  85571. var tmat = Bone._tmpMats[0];
  85572. if (mesh && wm) {
  85573. tmat.copyFrom(this.getAbsoluteTransform());
  85574. tmat.multiplyToRef(wm, tmat);
  85575. }
  85576. else {
  85577. tmat = this.getAbsoluteTransform();
  85578. }
  85579. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  85580. };
  85581. /**
  85582. * Get the local position of a point that is in world space
  85583. * @param position The world position
  85584. * @param mesh The mesh that this bone is attached to
  85585. * @returns The local position
  85586. */
  85587. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  85588. if (mesh === void 0) { mesh = null; }
  85589. var result = BABYLON.Vector3.Zero();
  85590. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  85591. return result;
  85592. };
  85593. /**
  85594. * Get the local position of a point that is in world space and copy it to the result param
  85595. * @param position The world position
  85596. * @param mesh The mesh that this bone is attached to
  85597. * @param result The vector3 that the local position should be copied to
  85598. */
  85599. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  85600. if (mesh === void 0) { mesh = null; }
  85601. var wm = null;
  85602. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85603. if (mesh) {
  85604. wm = mesh.getWorldMatrix();
  85605. }
  85606. this._skeleton.computeAbsoluteTransforms();
  85607. var tmat = Bone._tmpMats[0];
  85608. tmat.copyFrom(this.getAbsoluteTransform());
  85609. if (mesh && wm) {
  85610. tmat.multiplyToRef(wm, tmat);
  85611. }
  85612. tmat.invert();
  85613. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  85614. };
  85615. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85616. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  85617. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85618. return Bone;
  85619. }(BABYLON.Node));
  85620. BABYLON.Bone = Bone;
  85621. })(BABYLON || (BABYLON = {}));
  85622. //# sourceMappingURL=babylon.bone.js.map
  85623. var BABYLON;
  85624. (function (BABYLON) {
  85625. /**
  85626. * Class used to apply inverse kinematics to bones
  85627. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  85628. */
  85629. var BoneIKController = /** @class */ (function () {
  85630. /**
  85631. * Creates a new BoneIKController
  85632. * @param mesh defines the mesh to control
  85633. * @param bone defines the bone to control
  85634. * @param options defines options to set up the controller
  85635. */
  85636. function BoneIKController(mesh, bone, options) {
  85637. /**
  85638. * Gets or sets the target position
  85639. */
  85640. this.targetPosition = BABYLON.Vector3.Zero();
  85641. /**
  85642. * Gets or sets the pole target position
  85643. */
  85644. this.poleTargetPosition = BABYLON.Vector3.Zero();
  85645. /**
  85646. * Gets or sets the pole target local offset
  85647. */
  85648. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  85649. /**
  85650. * Gets or sets the pole angle
  85651. */
  85652. this.poleAngle = 0;
  85653. /**
  85654. * 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)
  85655. */
  85656. this.slerpAmount = 1;
  85657. this._bone1Quat = BABYLON.Quaternion.Identity();
  85658. this._bone1Mat = BABYLON.Matrix.Identity();
  85659. this._bone2Ang = Math.PI;
  85660. this._maxAngle = Math.PI;
  85661. this._rightHandedSystem = false;
  85662. this._bendAxis = BABYLON.Vector3.Right();
  85663. this._slerping = false;
  85664. this._adjustRoll = 0;
  85665. this._bone2 = bone;
  85666. this._bone1 = bone.getParent();
  85667. if (!this._bone1) {
  85668. return;
  85669. }
  85670. this.mesh = mesh;
  85671. var bonePos = bone.getPosition();
  85672. if (bone.getAbsoluteTransform().determinant() > 0) {
  85673. this._rightHandedSystem = true;
  85674. this._bendAxis.x = 0;
  85675. this._bendAxis.y = 0;
  85676. this._bendAxis.z = -1;
  85677. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  85678. this._adjustRoll = Math.PI * .5;
  85679. this._bendAxis.z = 1;
  85680. }
  85681. }
  85682. if (this._bone1.length) {
  85683. var boneScale1 = this._bone1.getScale();
  85684. var boneScale2 = this._bone2.getScale();
  85685. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  85686. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  85687. }
  85688. else if (this._bone1.children[0]) {
  85689. mesh.computeWorldMatrix(true);
  85690. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  85691. var pos2 = this._bone2.getAbsolutePosition(mesh);
  85692. var pos3 = this._bone1.getAbsolutePosition(mesh);
  85693. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  85694. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  85695. }
  85696. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  85697. this.maxAngle = Math.PI;
  85698. if (options) {
  85699. if (options.targetMesh) {
  85700. this.targetMesh = options.targetMesh;
  85701. this.targetMesh.computeWorldMatrix(true);
  85702. }
  85703. if (options.poleTargetMesh) {
  85704. this.poleTargetMesh = options.poleTargetMesh;
  85705. this.poleTargetMesh.computeWorldMatrix(true);
  85706. }
  85707. else if (options.poleTargetBone) {
  85708. this.poleTargetBone = options.poleTargetBone;
  85709. }
  85710. else if (this._bone1.getParent()) {
  85711. this.poleTargetBone = this._bone1.getParent();
  85712. }
  85713. if (options.poleTargetLocalOffset) {
  85714. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  85715. }
  85716. if (options.poleAngle) {
  85717. this.poleAngle = options.poleAngle;
  85718. }
  85719. if (options.bendAxis) {
  85720. this._bendAxis.copyFrom(options.bendAxis);
  85721. }
  85722. if (options.maxAngle) {
  85723. this.maxAngle = options.maxAngle;
  85724. }
  85725. if (options.slerpAmount) {
  85726. this.slerpAmount = options.slerpAmount;
  85727. }
  85728. }
  85729. }
  85730. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  85731. /**
  85732. * Gets or sets maximum allowed angle
  85733. */
  85734. get: function () {
  85735. return this._maxAngle;
  85736. },
  85737. set: function (value) {
  85738. this._setMaxAngle(value);
  85739. },
  85740. enumerable: true,
  85741. configurable: true
  85742. });
  85743. BoneIKController.prototype._setMaxAngle = function (ang) {
  85744. if (ang < 0) {
  85745. ang = 0;
  85746. }
  85747. if (ang > Math.PI || ang == undefined) {
  85748. ang = Math.PI;
  85749. }
  85750. this._maxAngle = ang;
  85751. var a = this._bone1Length;
  85752. var b = this._bone2Length;
  85753. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  85754. };
  85755. /**
  85756. * Force the controller to update the bones
  85757. */
  85758. BoneIKController.prototype.update = function () {
  85759. var bone1 = this._bone1;
  85760. if (!bone1) {
  85761. return;
  85762. }
  85763. var target = this.targetPosition;
  85764. var poleTarget = this.poleTargetPosition;
  85765. var mat1 = BoneIKController._tmpMats[0];
  85766. var mat2 = BoneIKController._tmpMats[1];
  85767. if (this.targetMesh) {
  85768. target.copyFrom(this.targetMesh.getAbsolutePosition());
  85769. }
  85770. if (this.poleTargetBone) {
  85771. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  85772. }
  85773. else if (this.poleTargetMesh) {
  85774. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  85775. }
  85776. var bonePos = BoneIKController._tmpVecs[0];
  85777. var zaxis = BoneIKController._tmpVecs[1];
  85778. var xaxis = BoneIKController._tmpVecs[2];
  85779. var yaxis = BoneIKController._tmpVecs[3];
  85780. var upAxis = BoneIKController._tmpVecs[4];
  85781. var _tmpQuat = BoneIKController._tmpQuat;
  85782. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  85783. poleTarget.subtractToRef(bonePos, upAxis);
  85784. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  85785. upAxis.y = 1;
  85786. }
  85787. else {
  85788. upAxis.normalize();
  85789. }
  85790. target.subtractToRef(bonePos, yaxis);
  85791. yaxis.normalize();
  85792. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  85793. zaxis.normalize();
  85794. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  85795. xaxis.normalize();
  85796. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  85797. var a = this._bone1Length;
  85798. var b = this._bone2Length;
  85799. var c = BABYLON.Vector3.Distance(bonePos, target);
  85800. if (this._maxReach > 0) {
  85801. c = Math.min(this._maxReach, c);
  85802. }
  85803. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  85804. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  85805. if (acosa > 1) {
  85806. acosa = 1;
  85807. }
  85808. if (acosb > 1) {
  85809. acosb = 1;
  85810. }
  85811. if (acosa < -1) {
  85812. acosa = -1;
  85813. }
  85814. if (acosb < -1) {
  85815. acosb = -1;
  85816. }
  85817. var angA = Math.acos(acosa);
  85818. var angB = Math.acos(acosb);
  85819. var angC = -angA - angB;
  85820. if (this._rightHandedSystem) {
  85821. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  85822. mat2.multiplyToRef(mat1, mat1);
  85823. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  85824. mat2.multiplyToRef(mat1, mat1);
  85825. }
  85826. else {
  85827. var _tmpVec = BoneIKController._tmpVecs[5];
  85828. _tmpVec.copyFrom(this._bendAxis);
  85829. _tmpVec.x *= -1;
  85830. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  85831. mat2.multiplyToRef(mat1, mat1);
  85832. }
  85833. if (this.poleAngle) {
  85834. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  85835. mat1.multiplyToRef(mat2, mat1);
  85836. }
  85837. if (this._bone1) {
  85838. if (this.slerpAmount < 1) {
  85839. if (!this._slerping) {
  85840. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  85841. }
  85842. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  85843. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  85844. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  85845. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  85846. this._slerping = true;
  85847. }
  85848. else {
  85849. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  85850. this._bone1Mat.copyFrom(mat1);
  85851. this._slerping = false;
  85852. }
  85853. }
  85854. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  85855. this._bone2Ang = angC;
  85856. };
  85857. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85858. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  85859. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85860. return BoneIKController;
  85861. }());
  85862. BABYLON.BoneIKController = BoneIKController;
  85863. })(BABYLON || (BABYLON = {}));
  85864. //# sourceMappingURL=babylon.boneIKController.js.map
  85865. var BABYLON;
  85866. (function (BABYLON) {
  85867. /**
  85868. * Class used to make a bone look toward a point in space
  85869. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  85870. */
  85871. var BoneLookController = /** @class */ (function () {
  85872. /**
  85873. * Create a BoneLookController
  85874. * @param mesh the mesh that the bone belongs to
  85875. * @param bone the bone that will be looking to the target
  85876. * @param target the target Vector3 to look at
  85877. * @param settings optional settings:
  85878. * * maxYaw: the maximum angle the bone will yaw to
  85879. * * minYaw: the minimum angle the bone will yaw to
  85880. * * maxPitch: the maximum angle the bone will pitch to
  85881. * * minPitch: the minimum angle the bone will yaw to
  85882. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  85883. * * upAxis: the up axis of the coordinate system
  85884. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  85885. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  85886. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  85887. * * adjustYaw: used to make an adjustment to the yaw of the bone
  85888. * * adjustPitch: used to make an adjustment to the pitch of the bone
  85889. * * adjustRoll: used to make an adjustment to the roll of the bone
  85890. **/
  85891. function BoneLookController(mesh, bone, target, options) {
  85892. /**
  85893. * The up axis of the coordinate system that is used when the bone is rotated
  85894. */
  85895. this.upAxis = BABYLON.Vector3.Up();
  85896. /**
  85897. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  85898. */
  85899. this.upAxisSpace = BABYLON.Space.LOCAL;
  85900. /**
  85901. * Used to make an adjustment to the yaw of the bone
  85902. */
  85903. this.adjustYaw = 0;
  85904. /**
  85905. * Used to make an adjustment to the pitch of the bone
  85906. */
  85907. this.adjustPitch = 0;
  85908. /**
  85909. * Used to make an adjustment to the roll of the bone
  85910. */
  85911. this.adjustRoll = 0;
  85912. /**
  85913. * 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)
  85914. */
  85915. this.slerpAmount = 1;
  85916. this._boneQuat = BABYLON.Quaternion.Identity();
  85917. this._slerping = false;
  85918. this._firstFrameSkipped = false;
  85919. this._fowardAxis = BABYLON.Vector3.Forward();
  85920. this.mesh = mesh;
  85921. this.bone = bone;
  85922. this.target = target;
  85923. if (options) {
  85924. if (options.adjustYaw) {
  85925. this.adjustYaw = options.adjustYaw;
  85926. }
  85927. if (options.adjustPitch) {
  85928. this.adjustPitch = options.adjustPitch;
  85929. }
  85930. if (options.adjustRoll) {
  85931. this.adjustRoll = options.adjustRoll;
  85932. }
  85933. if (options.maxYaw != null) {
  85934. this.maxYaw = options.maxYaw;
  85935. }
  85936. else {
  85937. this.maxYaw = Math.PI;
  85938. }
  85939. if (options.minYaw != null) {
  85940. this.minYaw = options.minYaw;
  85941. }
  85942. else {
  85943. this.minYaw = -Math.PI;
  85944. }
  85945. if (options.maxPitch != null) {
  85946. this.maxPitch = options.maxPitch;
  85947. }
  85948. else {
  85949. this.maxPitch = Math.PI;
  85950. }
  85951. if (options.minPitch != null) {
  85952. this.minPitch = options.minPitch;
  85953. }
  85954. else {
  85955. this.minPitch = -Math.PI;
  85956. }
  85957. if (options.slerpAmount != null) {
  85958. this.slerpAmount = options.slerpAmount;
  85959. }
  85960. if (options.upAxis != null) {
  85961. this.upAxis = options.upAxis;
  85962. }
  85963. if (options.upAxisSpace != null) {
  85964. this.upAxisSpace = options.upAxisSpace;
  85965. }
  85966. if (options.yawAxis != null || options.pitchAxis != null) {
  85967. var newYawAxis = BABYLON.Axis.Y;
  85968. var newPitchAxis = BABYLON.Axis.X;
  85969. if (options.yawAxis != null) {
  85970. newYawAxis = options.yawAxis.clone();
  85971. newYawAxis.normalize();
  85972. }
  85973. if (options.pitchAxis != null) {
  85974. newPitchAxis = options.pitchAxis.clone();
  85975. newPitchAxis.normalize();
  85976. }
  85977. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  85978. this._transformYawPitch = BABYLON.Matrix.Identity();
  85979. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  85980. this._transformYawPitchInv = this._transformYawPitch.clone();
  85981. this._transformYawPitch.invert();
  85982. }
  85983. }
  85984. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  85985. this.upAxisSpace = BABYLON.Space.LOCAL;
  85986. }
  85987. }
  85988. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  85989. /**
  85990. * Gets or sets the minimum yaw angle that the bone can look to
  85991. */
  85992. get: function () {
  85993. return this._minYaw;
  85994. },
  85995. set: function (value) {
  85996. this._minYaw = value;
  85997. this._minYawSin = Math.sin(value);
  85998. this._minYawCos = Math.cos(value);
  85999. if (this._maxYaw != null) {
  86000. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  86001. this._yawRange = this._maxYaw - this._minYaw;
  86002. }
  86003. },
  86004. enumerable: true,
  86005. configurable: true
  86006. });
  86007. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  86008. /**
  86009. * Gets or sets the maximum yaw angle that the bone can look to
  86010. */
  86011. get: function () {
  86012. return this._maxYaw;
  86013. },
  86014. set: function (value) {
  86015. this._maxYaw = value;
  86016. this._maxYawSin = Math.sin(value);
  86017. this._maxYawCos = Math.cos(value);
  86018. if (this._minYaw != null) {
  86019. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  86020. this._yawRange = this._maxYaw - this._minYaw;
  86021. }
  86022. },
  86023. enumerable: true,
  86024. configurable: true
  86025. });
  86026. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  86027. /**
  86028. * Gets or sets the minimum pitch angle that the bone can look to
  86029. */
  86030. get: function () {
  86031. return this._minPitch;
  86032. },
  86033. set: function (value) {
  86034. this._minPitch = value;
  86035. this._minPitchTan = Math.tan(value);
  86036. },
  86037. enumerable: true,
  86038. configurable: true
  86039. });
  86040. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  86041. /**
  86042. * Gets or sets the maximum pitch angle that the bone can look to
  86043. */
  86044. get: function () {
  86045. return this._maxPitch;
  86046. },
  86047. set: function (value) {
  86048. this._maxPitch = value;
  86049. this._maxPitchTan = Math.tan(value);
  86050. },
  86051. enumerable: true,
  86052. configurable: true
  86053. });
  86054. /**
  86055. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  86056. */
  86057. BoneLookController.prototype.update = function () {
  86058. //skip the first frame when slerping so that the mesh rotation is correct
  86059. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  86060. this._firstFrameSkipped = true;
  86061. return;
  86062. }
  86063. var bone = this.bone;
  86064. var bonePos = BoneLookController._tmpVecs[0];
  86065. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  86066. var target = this.target;
  86067. var _tmpMat1 = BoneLookController._tmpMats[0];
  86068. var _tmpMat2 = BoneLookController._tmpMats[1];
  86069. var mesh = this.mesh;
  86070. var parentBone = bone.getParent();
  86071. var upAxis = BoneLookController._tmpVecs[1];
  86072. upAxis.copyFrom(this.upAxis);
  86073. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  86074. if (this._transformYawPitch) {
  86075. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  86076. }
  86077. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  86078. }
  86079. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  86080. mesh.getDirectionToRef(upAxis, upAxis);
  86081. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  86082. upAxis.normalize();
  86083. }
  86084. }
  86085. var checkYaw = false;
  86086. var checkPitch = false;
  86087. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  86088. checkYaw = true;
  86089. }
  86090. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  86091. checkPitch = true;
  86092. }
  86093. if (checkYaw || checkPitch) {
  86094. var spaceMat = BoneLookController._tmpMats[2];
  86095. var spaceMatInv = BoneLookController._tmpMats[3];
  86096. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  86097. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  86098. }
  86099. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  86100. spaceMat.copyFrom(mesh.getWorldMatrix());
  86101. }
  86102. else {
  86103. var forwardAxis = BoneLookController._tmpVecs[2];
  86104. forwardAxis.copyFrom(this._fowardAxis);
  86105. if (this._transformYawPitch) {
  86106. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  86107. }
  86108. if (parentBone) {
  86109. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  86110. }
  86111. else {
  86112. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  86113. }
  86114. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  86115. rightAxis.normalize();
  86116. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  86117. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  86118. }
  86119. spaceMat.invertToRef(spaceMatInv);
  86120. var xzlen = null;
  86121. if (checkPitch) {
  86122. var localTarget = BoneLookController._tmpVecs[3];
  86123. target.subtractToRef(bonePos, localTarget);
  86124. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  86125. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  86126. var pitch = Math.atan2(localTarget.y, xzlen);
  86127. var newPitch = pitch;
  86128. if (pitch > this._maxPitch) {
  86129. localTarget.y = this._maxPitchTan * xzlen;
  86130. newPitch = this._maxPitch;
  86131. }
  86132. else if (pitch < this._minPitch) {
  86133. localTarget.y = this._minPitchTan * xzlen;
  86134. newPitch = this._minPitch;
  86135. }
  86136. if (pitch != newPitch) {
  86137. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  86138. localTarget.addInPlace(bonePos);
  86139. target = localTarget;
  86140. }
  86141. }
  86142. if (checkYaw) {
  86143. var localTarget = BoneLookController._tmpVecs[4];
  86144. target.subtractToRef(bonePos, localTarget);
  86145. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  86146. var yaw = Math.atan2(localTarget.x, localTarget.z);
  86147. var newYaw = yaw;
  86148. if (yaw > this._maxYaw || yaw < this._minYaw) {
  86149. if (xzlen == null) {
  86150. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  86151. }
  86152. if (this._yawRange > Math.PI) {
  86153. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  86154. localTarget.z = this._maxYawCos * xzlen;
  86155. localTarget.x = this._maxYawSin * xzlen;
  86156. newYaw = this._maxYaw;
  86157. }
  86158. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  86159. localTarget.z = this._minYawCos * xzlen;
  86160. localTarget.x = this._minYawSin * xzlen;
  86161. newYaw = this._minYaw;
  86162. }
  86163. }
  86164. else {
  86165. if (yaw > this._maxYaw) {
  86166. localTarget.z = this._maxYawCos * xzlen;
  86167. localTarget.x = this._maxYawSin * xzlen;
  86168. newYaw = this._maxYaw;
  86169. }
  86170. else if (yaw < this._minYaw) {
  86171. localTarget.z = this._minYawCos * xzlen;
  86172. localTarget.x = this._minYawSin * xzlen;
  86173. newYaw = this._minYaw;
  86174. }
  86175. }
  86176. }
  86177. if (this._slerping && this._yawRange > Math.PI) {
  86178. //are we going to be crossing into the min/max region?
  86179. var boneFwd = BoneLookController._tmpVecs[8];
  86180. boneFwd.copyFrom(BABYLON.Axis.Z);
  86181. if (this._transformYawPitch) {
  86182. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  86183. }
  86184. var boneRotMat = BoneLookController._tmpMats[4];
  86185. this._boneQuat.toRotationMatrix(boneRotMat);
  86186. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  86187. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  86188. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  86189. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  86190. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  86191. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  86192. if (angBtwTar > angBtwMidYaw) {
  86193. if (xzlen == null) {
  86194. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  86195. }
  86196. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  86197. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  86198. if (angBtwMin < angBtwMax) {
  86199. newYaw = boneYaw + Math.PI * .75;
  86200. localTarget.z = Math.cos(newYaw) * xzlen;
  86201. localTarget.x = Math.sin(newYaw) * xzlen;
  86202. }
  86203. else {
  86204. newYaw = boneYaw - Math.PI * .75;
  86205. localTarget.z = Math.cos(newYaw) * xzlen;
  86206. localTarget.x = Math.sin(newYaw) * xzlen;
  86207. }
  86208. }
  86209. }
  86210. if (yaw != newYaw) {
  86211. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  86212. localTarget.addInPlace(bonePos);
  86213. target = localTarget;
  86214. }
  86215. }
  86216. }
  86217. var zaxis = BoneLookController._tmpVecs[5];
  86218. var xaxis = BoneLookController._tmpVecs[6];
  86219. var yaxis = BoneLookController._tmpVecs[7];
  86220. var _tmpQuat = BoneLookController._tmpQuat;
  86221. target.subtractToRef(bonePos, zaxis);
  86222. zaxis.normalize();
  86223. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  86224. xaxis.normalize();
  86225. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  86226. yaxis.normalize();
  86227. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  86228. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  86229. return;
  86230. }
  86231. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  86232. return;
  86233. }
  86234. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  86235. return;
  86236. }
  86237. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  86238. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  86239. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  86240. }
  86241. if (this.slerpAmount < 1) {
  86242. if (!this._slerping) {
  86243. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  86244. }
  86245. if (this._transformYawPitch) {
  86246. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  86247. }
  86248. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  86249. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  86250. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  86251. this._slerping = true;
  86252. }
  86253. else {
  86254. if (this._transformYawPitch) {
  86255. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  86256. }
  86257. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  86258. this._slerping = false;
  86259. }
  86260. };
  86261. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  86262. var angDiff = ang2 - ang1;
  86263. angDiff %= Math.PI * 2;
  86264. if (angDiff > Math.PI) {
  86265. angDiff -= Math.PI * 2;
  86266. }
  86267. else if (angDiff < -Math.PI) {
  86268. angDiff += Math.PI * 2;
  86269. }
  86270. return angDiff;
  86271. };
  86272. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  86273. ang1 %= (2 * Math.PI);
  86274. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  86275. ang2 %= (2 * Math.PI);
  86276. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  86277. var ab = 0;
  86278. if (ang1 < ang2) {
  86279. ab = ang2 - ang1;
  86280. }
  86281. else {
  86282. ab = ang1 - ang2;
  86283. }
  86284. if (ab > Math.PI) {
  86285. ab = Math.PI * 2 - ab;
  86286. }
  86287. return ab;
  86288. };
  86289. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  86290. ang %= (2 * Math.PI);
  86291. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  86292. ang1 %= (2 * Math.PI);
  86293. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  86294. ang2 %= (2 * Math.PI);
  86295. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  86296. if (ang1 < ang2) {
  86297. if (ang > ang1 && ang < ang2) {
  86298. return true;
  86299. }
  86300. }
  86301. else {
  86302. if (ang > ang2 && ang < ang1) {
  86303. return true;
  86304. }
  86305. }
  86306. return false;
  86307. };
  86308. 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()];
  86309. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  86310. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  86311. return BoneLookController;
  86312. }());
  86313. BABYLON.BoneLookController = BoneLookController;
  86314. })(BABYLON || (BABYLON = {}));
  86315. //# sourceMappingURL=babylon.boneLookController.js.map
  86316. var BABYLON;
  86317. (function (BABYLON) {
  86318. /**
  86319. * Class used to handle skinning animations
  86320. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  86321. */
  86322. var Skeleton = /** @class */ (function () {
  86323. /**
  86324. * Creates a new skeleton
  86325. * @param name defines the skeleton name
  86326. * @param id defines the skeleton Id
  86327. * @param scene defines the hosting scene
  86328. */
  86329. function Skeleton(
  86330. /** defines the skeleton name */
  86331. name,
  86332. /** defines the skeleton Id */
  86333. id, scene) {
  86334. this.name = name;
  86335. this.id = id;
  86336. /**
  86337. * Gets the list of child bones
  86338. */
  86339. this.bones = new Array();
  86340. /**
  86341. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  86342. */
  86343. this.needInitialSkinMatrix = false;
  86344. this._isDirty = true;
  86345. this._meshesWithPoseMatrix = new Array();
  86346. this._identity = BABYLON.Matrix.Identity();
  86347. this._ranges = {};
  86348. this._lastAbsoluteTransformsUpdateId = -1;
  86349. /**
  86350. * Specifies if the skeleton should be serialized
  86351. */
  86352. this.doNotSerialize = false;
  86353. this._animationPropertiesOverride = null;
  86354. // Events
  86355. /**
  86356. * An observable triggered before computing the skeleton's matrices
  86357. */
  86358. this.onBeforeComputeObservable = new BABYLON.Observable();
  86359. this.bones = [];
  86360. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86361. scene.skeletons.push(this);
  86362. //make sure it will recalculate the matrix next time prepare is called.
  86363. this._isDirty = true;
  86364. }
  86365. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  86366. /**
  86367. * Gets or sets the animation properties override
  86368. */
  86369. get: function () {
  86370. if (!this._animationPropertiesOverride) {
  86371. return this._scene.animationPropertiesOverride;
  86372. }
  86373. return this._animationPropertiesOverride;
  86374. },
  86375. set: function (value) {
  86376. this._animationPropertiesOverride = value;
  86377. },
  86378. enumerable: true,
  86379. configurable: true
  86380. });
  86381. // Members
  86382. /**
  86383. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  86384. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  86385. * @returns a Float32Array containing matrices data
  86386. */
  86387. Skeleton.prototype.getTransformMatrices = function (mesh) {
  86388. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  86389. return mesh._bonesTransformMatrices;
  86390. }
  86391. if (!this._transformMatrices) {
  86392. this.prepare();
  86393. }
  86394. return this._transformMatrices;
  86395. };
  86396. /**
  86397. * Gets the current hosting scene
  86398. * @returns a scene object
  86399. */
  86400. Skeleton.prototype.getScene = function () {
  86401. return this._scene;
  86402. };
  86403. // Methods
  86404. /**
  86405. * Gets a string representing the current skeleton data
  86406. * @param fullDetails defines a boolean indicating if we want a verbose version
  86407. * @returns a string representing the current skeleton data
  86408. */
  86409. Skeleton.prototype.toString = function (fullDetails) {
  86410. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  86411. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  86412. if (fullDetails) {
  86413. ret += ", Ranges: {";
  86414. var first = true;
  86415. for (var name_1 in this._ranges) {
  86416. if (first) {
  86417. ret += ", ";
  86418. first = false;
  86419. }
  86420. ret += name_1;
  86421. }
  86422. ret += "}";
  86423. }
  86424. return ret;
  86425. };
  86426. /**
  86427. * Get bone's index searching by name
  86428. * @param name defines bone's name to search for
  86429. * @return the indice of the bone. Returns -1 if not found
  86430. */
  86431. Skeleton.prototype.getBoneIndexByName = function (name) {
  86432. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  86433. if (this.bones[boneIndex].name === name) {
  86434. return boneIndex;
  86435. }
  86436. }
  86437. return -1;
  86438. };
  86439. /**
  86440. * Creater a new animation range
  86441. * @param name defines the name of the range
  86442. * @param from defines the start key
  86443. * @param to defines the end key
  86444. */
  86445. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  86446. // check name not already in use
  86447. if (!this._ranges[name]) {
  86448. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  86449. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86450. if (this.bones[i].animations[0]) {
  86451. this.bones[i].animations[0].createRange(name, from, to);
  86452. }
  86453. }
  86454. }
  86455. };
  86456. /**
  86457. * Delete a specific animation range
  86458. * @param name defines the name of the range
  86459. * @param deleteFrames defines if frames must be removed as well
  86460. */
  86461. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  86462. if (deleteFrames === void 0) { deleteFrames = true; }
  86463. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86464. if (this.bones[i].animations[0]) {
  86465. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  86466. }
  86467. }
  86468. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  86469. };
  86470. /**
  86471. * Gets a specific animation range
  86472. * @param name defines the name of the range to look for
  86473. * @returns the requested animation range or null if not found
  86474. */
  86475. Skeleton.prototype.getAnimationRange = function (name) {
  86476. return this._ranges[name];
  86477. };
  86478. /**
  86479. * Gets the list of all animation ranges defined on this skeleton
  86480. * @returns an array
  86481. */
  86482. Skeleton.prototype.getAnimationRanges = function () {
  86483. var animationRanges = [];
  86484. var name;
  86485. var i = 0;
  86486. for (name in this._ranges) {
  86487. animationRanges[i] = this._ranges[name];
  86488. i++;
  86489. }
  86490. return animationRanges;
  86491. };
  86492. /**
  86493. * Copy animation range from a source skeleton.
  86494. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  86495. * @param source defines the source skeleton
  86496. * @param name defines the name of the range to copy
  86497. * @param rescaleAsRequired defines if rescaling must be applied if required
  86498. * @returns true if operation was successful
  86499. */
  86500. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  86501. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  86502. if (this._ranges[name] || !source.getAnimationRange(name)) {
  86503. return false;
  86504. }
  86505. var ret = true;
  86506. var frameOffset = this._getHighestAnimationFrame() + 1;
  86507. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  86508. var boneDict = {};
  86509. var sourceBones = source.bones;
  86510. var nBones;
  86511. var i;
  86512. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  86513. boneDict[sourceBones[i].name] = sourceBones[i];
  86514. }
  86515. if (this.bones.length !== sourceBones.length) {
  86516. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  86517. ret = false;
  86518. }
  86519. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  86520. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  86521. var boneName = this.bones[i].name;
  86522. var sourceBone = boneDict[boneName];
  86523. if (sourceBone) {
  86524. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  86525. }
  86526. else {
  86527. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  86528. ret = false;
  86529. }
  86530. }
  86531. // do not call createAnimationRange(), since it also is done to bones, which was already done
  86532. var range = source.getAnimationRange(name);
  86533. if (range) {
  86534. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  86535. }
  86536. return ret;
  86537. };
  86538. /**
  86539. * Forces the skeleton to go to rest pose
  86540. */
  86541. Skeleton.prototype.returnToRest = function () {
  86542. for (var index = 0; index < this.bones.length; index++) {
  86543. this.bones[index].returnToRest();
  86544. }
  86545. };
  86546. Skeleton.prototype._getHighestAnimationFrame = function () {
  86547. var ret = 0;
  86548. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86549. if (this.bones[i].animations[0]) {
  86550. var highest = this.bones[i].animations[0].getHighestFrame();
  86551. if (ret < highest) {
  86552. ret = highest;
  86553. }
  86554. }
  86555. }
  86556. return ret;
  86557. };
  86558. /**
  86559. * Begin a specific animation range
  86560. * @param name defines the name of the range to start
  86561. * @param loop defines if looping must be turned on (false by default)
  86562. * @param speedRatio defines the speed ratio to apply (1 by default)
  86563. * @param onAnimationEnd defines a callback which will be called when animation will end
  86564. * @returns a new animatable
  86565. */
  86566. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  86567. var range = this.getAnimationRange(name);
  86568. if (!range) {
  86569. return null;
  86570. }
  86571. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  86572. };
  86573. /** @hidden */
  86574. Skeleton.prototype._markAsDirty = function () {
  86575. this._isDirty = true;
  86576. };
  86577. /** @hidden */
  86578. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  86579. this._meshesWithPoseMatrix.push(mesh);
  86580. };
  86581. /** @hidden */
  86582. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  86583. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  86584. if (index > -1) {
  86585. this._meshesWithPoseMatrix.splice(index, 1);
  86586. }
  86587. };
  86588. /** @hidden */
  86589. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  86590. this.onBeforeComputeObservable.notifyObservers(this);
  86591. for (var index = 0; index < this.bones.length; index++) {
  86592. var bone = this.bones[index];
  86593. var parentBone = bone.getParent();
  86594. if (parentBone) {
  86595. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  86596. }
  86597. else {
  86598. if (initialSkinMatrix) {
  86599. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  86600. }
  86601. else {
  86602. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  86603. }
  86604. }
  86605. if (bone._index !== -1) {
  86606. var mappedIndex = bone._index === null ? index : bone._index;
  86607. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  86608. }
  86609. }
  86610. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  86611. };
  86612. /**
  86613. * Build all resources required to render a skeleton
  86614. */
  86615. Skeleton.prototype.prepare = function () {
  86616. if (!this._isDirty) {
  86617. return;
  86618. }
  86619. if (this.needInitialSkinMatrix) {
  86620. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  86621. var mesh = this._meshesWithPoseMatrix[index];
  86622. var poseMatrix = mesh.getPoseMatrix();
  86623. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  86624. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86625. }
  86626. if (this._synchronizedWithMesh !== mesh) {
  86627. this._synchronizedWithMesh = mesh;
  86628. // Prepare bones
  86629. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  86630. var bone = this.bones[boneIndex];
  86631. if (!bone.getParent()) {
  86632. var matrix = bone.getBaseMatrix();
  86633. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  86634. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  86635. }
  86636. }
  86637. }
  86638. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  86639. }
  86640. }
  86641. else {
  86642. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  86643. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86644. }
  86645. this._computeTransformMatrices(this._transformMatrices, null);
  86646. }
  86647. this._isDirty = false;
  86648. this._scene._activeBones.addCount(this.bones.length, false);
  86649. };
  86650. /**
  86651. * Gets the list of animatables currently running for this skeleton
  86652. * @returns an array of animatables
  86653. */
  86654. Skeleton.prototype.getAnimatables = function () {
  86655. if (!this._animatables || this._animatables.length !== this.bones.length) {
  86656. this._animatables = [];
  86657. for (var index = 0; index < this.bones.length; index++) {
  86658. this._animatables.push(this.bones[index]);
  86659. }
  86660. }
  86661. return this._animatables;
  86662. };
  86663. /**
  86664. * Clone the current skeleton
  86665. * @param name defines the name of the new skeleton
  86666. * @param id defines the id of the enw skeleton
  86667. * @returns the new skeleton
  86668. */
  86669. Skeleton.prototype.clone = function (name, id) {
  86670. var result = new Skeleton(name, id || name, this._scene);
  86671. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86672. for (var index = 0; index < this.bones.length; index++) {
  86673. var source = this.bones[index];
  86674. var parentBone = null;
  86675. var parent_1 = source.getParent();
  86676. if (parent_1) {
  86677. var parentIndex = this.bones.indexOf(parent_1);
  86678. parentBone = result.bones[parentIndex];
  86679. }
  86680. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  86681. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  86682. }
  86683. if (this._ranges) {
  86684. result._ranges = {};
  86685. for (var rangeName in this._ranges) {
  86686. var range = this._ranges[rangeName];
  86687. if (range) {
  86688. result._ranges[rangeName] = range.clone();
  86689. }
  86690. }
  86691. }
  86692. this._isDirty = true;
  86693. return result;
  86694. };
  86695. /**
  86696. * Enable animation blending for this skeleton
  86697. * @param blendingSpeed defines the blending speed to apply
  86698. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  86699. */
  86700. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  86701. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  86702. this.bones.forEach(function (bone) {
  86703. bone.animations.forEach(function (animation) {
  86704. animation.enableBlending = true;
  86705. animation.blendingSpeed = blendingSpeed;
  86706. });
  86707. });
  86708. };
  86709. /**
  86710. * Releases all resources associated with the current skeleton
  86711. */
  86712. Skeleton.prototype.dispose = function () {
  86713. this._meshesWithPoseMatrix = [];
  86714. // Animations
  86715. this.getScene().stopAnimation(this);
  86716. // Remove from scene
  86717. this.getScene().removeSkeleton(this);
  86718. };
  86719. /**
  86720. * Serialize the skeleton in a JSON object
  86721. * @returns a JSON object
  86722. */
  86723. Skeleton.prototype.serialize = function () {
  86724. var serializationObject = {};
  86725. serializationObject.name = this.name;
  86726. serializationObject.id = this.id;
  86727. if (this.dimensionsAtRest) {
  86728. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  86729. }
  86730. serializationObject.bones = [];
  86731. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86732. for (var index = 0; index < this.bones.length; index++) {
  86733. var bone = this.bones[index];
  86734. var parent_2 = bone.getParent();
  86735. var serializedBone = {
  86736. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  86737. name: bone.name,
  86738. matrix: bone.getBaseMatrix().toArray(),
  86739. rest: bone.getRestPose().toArray()
  86740. };
  86741. serializationObject.bones.push(serializedBone);
  86742. if (bone.length) {
  86743. serializedBone.length = bone.length;
  86744. }
  86745. if (bone.metadata) {
  86746. serializedBone.metadata = bone.metadata;
  86747. }
  86748. if (bone.animations && bone.animations.length > 0) {
  86749. serializedBone.animation = bone.animations[0].serialize();
  86750. }
  86751. serializationObject.ranges = [];
  86752. for (var name in this._ranges) {
  86753. var source = this._ranges[name];
  86754. if (!source) {
  86755. continue;
  86756. }
  86757. var range = {};
  86758. range.name = name;
  86759. range.from = source.from;
  86760. range.to = source.to;
  86761. serializationObject.ranges.push(range);
  86762. }
  86763. }
  86764. return serializationObject;
  86765. };
  86766. /**
  86767. * Creates a new skeleton from serialized data
  86768. * @param parsedSkeleton defines the serialized data
  86769. * @param scene defines the hosting scene
  86770. * @returns a new skeleton
  86771. */
  86772. Skeleton.Parse = function (parsedSkeleton, scene) {
  86773. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  86774. if (parsedSkeleton.dimensionsAtRest) {
  86775. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  86776. }
  86777. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  86778. var index;
  86779. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  86780. var parsedBone = parsedSkeleton.bones[index];
  86781. var parentBone = null;
  86782. if (parsedBone.parentBoneIndex > -1) {
  86783. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  86784. }
  86785. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  86786. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  86787. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  86788. bone.id = parsedBone.id;
  86789. }
  86790. if (parsedBone.length) {
  86791. bone.length = parsedBone.length;
  86792. }
  86793. if (parsedBone.metadata) {
  86794. bone.metadata = parsedBone.metadata;
  86795. }
  86796. if (parsedBone.animation) {
  86797. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  86798. }
  86799. }
  86800. // placed after bones, so createAnimationRange can cascade down
  86801. if (parsedSkeleton.ranges) {
  86802. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  86803. var data = parsedSkeleton.ranges[index];
  86804. skeleton.createAnimationRange(data.name, data.from, data.to);
  86805. }
  86806. }
  86807. return skeleton;
  86808. };
  86809. /**
  86810. * Compute all node absolute transforms
  86811. * @param forceUpdate defines if computation must be done even if cache is up to date
  86812. */
  86813. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  86814. if (forceUpdate === void 0) { forceUpdate = false; }
  86815. var renderId = this._scene.getRenderId();
  86816. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  86817. this.bones[0].computeAbsoluteTransforms();
  86818. this._lastAbsoluteTransformsUpdateId = renderId;
  86819. }
  86820. };
  86821. /**
  86822. * Gets the root pose matrix
  86823. * @returns a matrix
  86824. */
  86825. Skeleton.prototype.getPoseMatrix = function () {
  86826. var poseMatrix = null;
  86827. if (this._meshesWithPoseMatrix.length > 0) {
  86828. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  86829. }
  86830. return poseMatrix;
  86831. };
  86832. /**
  86833. * Sorts bones per internal index
  86834. */
  86835. Skeleton.prototype.sortBones = function () {
  86836. var bones = new Array();
  86837. var visited = new Array(this.bones.length);
  86838. for (var index = 0; index < this.bones.length; index++) {
  86839. this._sortBones(index, bones, visited);
  86840. }
  86841. this.bones = bones;
  86842. };
  86843. Skeleton.prototype._sortBones = function (index, bones, visited) {
  86844. if (visited[index]) {
  86845. return;
  86846. }
  86847. visited[index] = true;
  86848. var bone = this.bones[index];
  86849. if (bone._index === undefined) {
  86850. bone._index = index;
  86851. }
  86852. var parentBone = bone.getParent();
  86853. if (parentBone) {
  86854. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  86855. }
  86856. bones.push(bone);
  86857. };
  86858. return Skeleton;
  86859. }());
  86860. BABYLON.Skeleton = Skeleton;
  86861. })(BABYLON || (BABYLON = {}));
  86862. //# sourceMappingURL=babylon.skeleton.js.map
  86863. var BABYLON;
  86864. (function (BABYLON) {
  86865. ;
  86866. /**
  86867. * This groups tools to convert HDR texture to native colors array.
  86868. */
  86869. var HDRTools = /** @class */ (function () {
  86870. function HDRTools() {
  86871. }
  86872. HDRTools.Ldexp = function (mantissa, exponent) {
  86873. if (exponent > 1023) {
  86874. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  86875. }
  86876. if (exponent < -1074) {
  86877. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  86878. }
  86879. return mantissa * Math.pow(2, exponent);
  86880. };
  86881. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  86882. if (exponent > 0) { /*nonzero pixel*/
  86883. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  86884. float32array[index + 0] = red * exponent;
  86885. float32array[index + 1] = green * exponent;
  86886. float32array[index + 2] = blue * exponent;
  86887. }
  86888. else {
  86889. float32array[index + 0] = 0;
  86890. float32array[index + 1] = 0;
  86891. float32array[index + 2] = 0;
  86892. }
  86893. };
  86894. HDRTools.readStringLine = function (uint8array, startIndex) {
  86895. var line = "";
  86896. var character = "";
  86897. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  86898. character = String.fromCharCode(uint8array[i]);
  86899. if (character == "\n") {
  86900. break;
  86901. }
  86902. line += character;
  86903. }
  86904. return line;
  86905. };
  86906. /**
  86907. * Reads header information from an RGBE texture stored in a native array.
  86908. * More information on this format are available here:
  86909. * https://en.wikipedia.org/wiki/RGBE_image_format
  86910. *
  86911. * @param uint8array The binary file stored in native array.
  86912. * @return The header information.
  86913. */
  86914. HDRTools.RGBE_ReadHeader = function (uint8array) {
  86915. var height = 0;
  86916. var width = 0;
  86917. var line = this.readStringLine(uint8array, 0);
  86918. if (line[0] != '#' || line[1] != '?') {
  86919. throw "Bad HDR Format.";
  86920. }
  86921. var endOfHeader = false;
  86922. var findFormat = false;
  86923. var lineIndex = 0;
  86924. do {
  86925. lineIndex += (line.length + 1);
  86926. line = this.readStringLine(uint8array, lineIndex);
  86927. if (line == "FORMAT=32-bit_rle_rgbe") {
  86928. findFormat = true;
  86929. }
  86930. else if (line.length == 0) {
  86931. endOfHeader = true;
  86932. }
  86933. } while (!endOfHeader);
  86934. if (!findFormat) {
  86935. throw "HDR Bad header format, unsupported FORMAT";
  86936. }
  86937. lineIndex += (line.length + 1);
  86938. line = this.readStringLine(uint8array, lineIndex);
  86939. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  86940. var match = sizeRegexp.exec(line);
  86941. // TODO. Support +Y and -X if needed.
  86942. if (!match || match.length < 3) {
  86943. throw "HDR Bad header format, no size";
  86944. }
  86945. width = parseInt(match[2]);
  86946. height = parseInt(match[1]);
  86947. if (width < 8 || width > 0x7fff) {
  86948. throw "HDR Bad header format, unsupported size";
  86949. }
  86950. lineIndex += (line.length + 1);
  86951. return {
  86952. height: height,
  86953. width: width,
  86954. dataPosition: lineIndex
  86955. };
  86956. };
  86957. /**
  86958. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  86959. * This RGBE texture needs to store the information as a panorama.
  86960. *
  86961. * More information on this format are available here:
  86962. * https://en.wikipedia.org/wiki/RGBE_image_format
  86963. *
  86964. * @param buffer The binary file stored in an array buffer.
  86965. * @param size The expected size of the extracted cubemap.
  86966. * @return The Cube Map information.
  86967. */
  86968. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  86969. var uint8array = new Uint8Array(buffer);
  86970. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  86971. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86972. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  86973. return cubeMapData;
  86974. };
  86975. /**
  86976. * Returns the pixels data extracted from an RGBE texture.
  86977. * This pixels will be stored left to right up to down in the R G B order in one array.
  86978. *
  86979. * More information on this format are available here:
  86980. * https://en.wikipedia.org/wiki/RGBE_image_format
  86981. *
  86982. * @param uint8array The binary file stored in an array buffer.
  86983. * @param hdrInfo The header information of the file.
  86984. * @return The pixels data in RGB right to left up to down order.
  86985. */
  86986. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  86987. // Keep for multi format supports.
  86988. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86989. };
  86990. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  86991. var num_scanlines = hdrInfo.height;
  86992. var scanline_width = hdrInfo.width;
  86993. var a, b, c, d, count;
  86994. var dataIndex = hdrInfo.dataPosition;
  86995. var index = 0, endIndex = 0, i = 0;
  86996. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  86997. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  86998. // 3 channels of 4 bytes per pixel in float.
  86999. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  87000. var resultArray = new Float32Array(resultBuffer);
  87001. // read in each successive scanline
  87002. while (num_scanlines > 0) {
  87003. a = uint8array[dataIndex++];
  87004. b = uint8array[dataIndex++];
  87005. c = uint8array[dataIndex++];
  87006. d = uint8array[dataIndex++];
  87007. if (a != 2 || b != 2 || (c & 0x80)) {
  87008. // this file is not run length encoded
  87009. throw "HDR Bad header format, not RLE";
  87010. }
  87011. if (((c << 8) | d) != scanline_width) {
  87012. throw "HDR Bad header format, wrong scan line width";
  87013. }
  87014. index = 0;
  87015. // read each of the four channels for the scanline into the buffer
  87016. for (i = 0; i < 4; i++) {
  87017. endIndex = (i + 1) * scanline_width;
  87018. while (index < endIndex) {
  87019. a = uint8array[dataIndex++];
  87020. b = uint8array[dataIndex++];
  87021. if (a > 128) {
  87022. // a run of the same value
  87023. count = a - 128;
  87024. if ((count == 0) || (count > endIndex - index)) {
  87025. throw "HDR Bad Format, bad scanline data (run)";
  87026. }
  87027. while (count-- > 0) {
  87028. scanLineArray[index++] = b;
  87029. }
  87030. }
  87031. else {
  87032. // a non-run
  87033. count = a;
  87034. if ((count == 0) || (count > endIndex - index)) {
  87035. throw "HDR Bad Format, bad scanline data (non-run)";
  87036. }
  87037. scanLineArray[index++] = b;
  87038. if (--count > 0) {
  87039. for (var j = 0; j < count; j++) {
  87040. scanLineArray[index++] = uint8array[dataIndex++];
  87041. }
  87042. }
  87043. }
  87044. }
  87045. }
  87046. // now convert data from buffer into floats
  87047. for (i = 0; i < scanline_width; i++) {
  87048. a = scanLineArray[i];
  87049. b = scanLineArray[i + scanline_width];
  87050. c = scanLineArray[i + 2 * scanline_width];
  87051. d = scanLineArray[i + 3 * scanline_width];
  87052. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  87053. }
  87054. num_scanlines--;
  87055. }
  87056. return resultArray;
  87057. };
  87058. return HDRTools;
  87059. }());
  87060. BABYLON.HDRTools = HDRTools;
  87061. })(BABYLON || (BABYLON = {}));
  87062. //# sourceMappingURL=babylon.hdr.js.map
  87063. var BABYLON;
  87064. (function (BABYLON) {
  87065. /**
  87066. * This represents a texture coming from an HDR input.
  87067. *
  87068. * The only supported format is currently panorama picture stored in RGBE format.
  87069. * Example of such files can be found on HDRLib: http://hdrlib.com/
  87070. */
  87071. var HDRCubeTexture = /** @class */ (function (_super) {
  87072. __extends(HDRCubeTexture, _super);
  87073. /**
  87074. * Instantiates an HDRTexture from the following parameters.
  87075. *
  87076. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  87077. * @param scene The scene the texture will be used in
  87078. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  87079. * @param noMipmap Forces to not generate the mipmap if true
  87080. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  87081. * @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)
  87082. * @param reserved Reserved flag for internal use.
  87083. */
  87084. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  87085. if (noMipmap === void 0) { noMipmap = false; }
  87086. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87087. if (gammaSpace === void 0) { gammaSpace = false; }
  87088. if (reserved === void 0) { reserved = false; }
  87089. if (onLoad === void 0) { onLoad = null; }
  87090. if (onError === void 0) { onError = null; }
  87091. var _this = _super.call(this, scene) || this;
  87092. _this._generateHarmonics = true;
  87093. _this._onLoad = null;
  87094. _this._onError = null;
  87095. /**
  87096. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  87097. */
  87098. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  87099. _this._isBlocking = true;
  87100. _this._rotationY = 0;
  87101. /**
  87102. * Gets or sets the center of the bounding box associated with the cube texture
  87103. * It must define where the camera used to render the texture was set
  87104. */
  87105. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  87106. if (!url) {
  87107. return _this;
  87108. }
  87109. _this.name = url;
  87110. _this.url = url;
  87111. _this.hasAlpha = false;
  87112. _this.isCube = true;
  87113. _this._textureMatrix = BABYLON.Matrix.Identity();
  87114. _this._onLoad = onLoad;
  87115. _this._onError = onError;
  87116. _this.gammaSpace = gammaSpace;
  87117. _this._noMipmap = noMipmap;
  87118. _this._size = size;
  87119. _this._texture = _this._getFromCache(url, _this._noMipmap);
  87120. if (!_this._texture) {
  87121. if (!scene.useDelayedTextureLoading) {
  87122. _this.loadTexture();
  87123. }
  87124. else {
  87125. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  87126. }
  87127. }
  87128. return _this;
  87129. }
  87130. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  87131. /**
  87132. * Gets wether or not the texture is blocking during loading.
  87133. */
  87134. get: function () {
  87135. return this._isBlocking;
  87136. },
  87137. /**
  87138. * Sets wether or not the texture is blocking during loading.
  87139. */
  87140. set: function (value) {
  87141. this._isBlocking = value;
  87142. },
  87143. enumerable: true,
  87144. configurable: true
  87145. });
  87146. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  87147. /**
  87148. * Gets texture matrix rotation angle around Y axis radians.
  87149. */
  87150. get: function () {
  87151. return this._rotationY;
  87152. },
  87153. /**
  87154. * Sets texture matrix rotation angle around Y axis in radians.
  87155. */
  87156. set: function (value) {
  87157. this._rotationY = value;
  87158. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  87159. },
  87160. enumerable: true,
  87161. configurable: true
  87162. });
  87163. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  87164. get: function () {
  87165. return this._boundingBoxSize;
  87166. },
  87167. /**
  87168. * Gets or sets the size of the bounding box associated with the cube texture
  87169. * When defined, the cubemap will switch to local mode
  87170. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  87171. * @example https://www.babylonjs-playground.com/#RNASML
  87172. */
  87173. set: function (value) {
  87174. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  87175. return;
  87176. }
  87177. this._boundingBoxSize = value;
  87178. var scene = this.getScene();
  87179. if (scene) {
  87180. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  87181. }
  87182. },
  87183. enumerable: true,
  87184. configurable: true
  87185. });
  87186. /**
  87187. * Occurs when the file is raw .hdr file.
  87188. */
  87189. HDRCubeTexture.prototype.loadTexture = function () {
  87190. var _this = this;
  87191. var callback = function (buffer) {
  87192. _this.lodGenerationOffset = 0.0;
  87193. _this.lodGenerationScale = 0.8;
  87194. var scene = _this.getScene();
  87195. if (!scene) {
  87196. return null;
  87197. }
  87198. // Extract the raw linear data.
  87199. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  87200. // Generate harmonics if needed.
  87201. if (_this._generateHarmonics) {
  87202. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  87203. _this.sphericalPolynomial = sphericalPolynomial;
  87204. }
  87205. var results = [];
  87206. var byteArray = null;
  87207. // Push each faces.
  87208. for (var j = 0; j < 6; j++) {
  87209. // Create uintarray fallback.
  87210. if (!scene.getEngine().getCaps().textureFloat) {
  87211. // 3 channels of 1 bytes per pixel in bytes.
  87212. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  87213. byteArray = new Uint8Array(byteBuffer);
  87214. }
  87215. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  87216. // If special cases.
  87217. if (_this.gammaSpace || byteArray) {
  87218. for (var i = 0; i < _this._size * _this._size; i++) {
  87219. // Put in gamma space if requested.
  87220. if (_this.gammaSpace) {
  87221. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  87222. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  87223. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  87224. }
  87225. // Convert to int texture for fallback.
  87226. if (byteArray) {
  87227. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  87228. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  87229. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  87230. // May use luminance instead if the result is not accurate.
  87231. var max = Math.max(Math.max(r, g), b);
  87232. if (max > 255) {
  87233. var scale = 255 / max;
  87234. r *= scale;
  87235. g *= scale;
  87236. b *= scale;
  87237. }
  87238. byteArray[(i * 3) + 0] = r;
  87239. byteArray[(i * 3) + 1] = g;
  87240. byteArray[(i * 3) + 2] = b;
  87241. }
  87242. }
  87243. }
  87244. if (byteArray) {
  87245. results.push(byteArray);
  87246. }
  87247. else {
  87248. results.push(dataFace);
  87249. }
  87250. }
  87251. return results;
  87252. };
  87253. var scene = this.getScene();
  87254. if (scene) {
  87255. 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);
  87256. }
  87257. };
  87258. HDRCubeTexture.prototype.clone = function () {
  87259. var scene = this.getScene();
  87260. if (!scene) {
  87261. return this;
  87262. }
  87263. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  87264. // Base texture
  87265. newTexture.level = this.level;
  87266. newTexture.wrapU = this.wrapU;
  87267. newTexture.wrapV = this.wrapV;
  87268. newTexture.coordinatesIndex = this.coordinatesIndex;
  87269. newTexture.coordinatesMode = this.coordinatesMode;
  87270. return newTexture;
  87271. };
  87272. // Methods
  87273. HDRCubeTexture.prototype.delayLoad = function () {
  87274. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  87275. return;
  87276. }
  87277. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  87278. this._texture = this._getFromCache(this.url, this._noMipmap);
  87279. if (!this._texture) {
  87280. this.loadTexture();
  87281. }
  87282. };
  87283. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  87284. return this._textureMatrix;
  87285. };
  87286. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  87287. this._textureMatrix = value;
  87288. };
  87289. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  87290. var texture = null;
  87291. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  87292. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  87293. texture.name = parsedTexture.name;
  87294. texture.hasAlpha = parsedTexture.hasAlpha;
  87295. texture.level = parsedTexture.level;
  87296. texture.coordinatesMode = parsedTexture.coordinatesMode;
  87297. texture.isBlocking = parsedTexture.isBlocking;
  87298. }
  87299. if (texture) {
  87300. if (parsedTexture.boundingBoxPosition) {
  87301. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  87302. }
  87303. if (parsedTexture.boundingBoxSize) {
  87304. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  87305. }
  87306. if (parsedTexture.rotationY) {
  87307. texture.rotationY = parsedTexture.rotationY;
  87308. }
  87309. }
  87310. return texture;
  87311. };
  87312. HDRCubeTexture.prototype.serialize = function () {
  87313. if (!this.name) {
  87314. return null;
  87315. }
  87316. var serializationObject = {};
  87317. serializationObject.name = this.name;
  87318. serializationObject.hasAlpha = this.hasAlpha;
  87319. serializationObject.isCube = true;
  87320. serializationObject.level = this.level;
  87321. serializationObject.size = this._size;
  87322. serializationObject.coordinatesMode = this.coordinatesMode;
  87323. serializationObject.useInGammaSpace = this.gammaSpace;
  87324. serializationObject.generateHarmonics = this._generateHarmonics;
  87325. serializationObject.customType = "BABYLON.HDRCubeTexture";
  87326. serializationObject.noMipmap = this._noMipmap;
  87327. serializationObject.isBlocking = this._isBlocking;
  87328. serializationObject.rotationY = this._rotationY;
  87329. return serializationObject;
  87330. };
  87331. HDRCubeTexture._facesMapping = [
  87332. "right",
  87333. "left",
  87334. "up",
  87335. "down",
  87336. "front",
  87337. "back"
  87338. ];
  87339. return HDRCubeTexture;
  87340. }(BABYLON.BaseTexture));
  87341. BABYLON.HDRCubeTexture = HDRCubeTexture;
  87342. })(BABYLON || (BABYLON = {}));
  87343. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  87344. var BABYLON;
  87345. (function (BABYLON) {
  87346. /**
  87347. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  87348. */
  87349. var PanoramaToCubeMapTools = /** @class */ (function () {
  87350. function PanoramaToCubeMapTools() {
  87351. }
  87352. /**
  87353. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  87354. *
  87355. * @param float32Array The source data.
  87356. * @param inputWidth The width of the input panorama.
  87357. * @param inputhHeight The height of the input panorama.
  87358. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  87359. * @return The cubemap data
  87360. */
  87361. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  87362. if (!float32Array) {
  87363. throw "ConvertPanoramaToCubemap: input cannot be null";
  87364. }
  87365. if (float32Array.length != inputWidth * inputHeight * 3) {
  87366. throw "ConvertPanoramaToCubemap: input size is wrong";
  87367. }
  87368. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  87369. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  87370. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  87371. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  87372. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  87373. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  87374. return {
  87375. front: textureFront,
  87376. back: textureBack,
  87377. left: textureLeft,
  87378. right: textureRight,
  87379. up: textureUp,
  87380. down: textureDown,
  87381. size: size,
  87382. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87383. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  87384. gammaSpace: false,
  87385. };
  87386. };
  87387. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  87388. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  87389. var textureArray = new Float32Array(buffer);
  87390. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  87391. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  87392. var dy = 1 / texSize;
  87393. var fy = 0;
  87394. for (var y = 0; y < texSize; y++) {
  87395. var xv1 = faceData[0];
  87396. var xv2 = faceData[2];
  87397. for (var x = 0; x < texSize; x++) {
  87398. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  87399. v.normalize();
  87400. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  87401. // 3 channels per pixels
  87402. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  87403. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  87404. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  87405. xv1 = xv1.add(rotDX1);
  87406. xv2 = xv2.add(rotDX2);
  87407. }
  87408. fy += dy;
  87409. }
  87410. return textureArray;
  87411. };
  87412. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  87413. var theta = Math.atan2(vDir.z, vDir.x);
  87414. var phi = Math.acos(vDir.y);
  87415. while (theta < -Math.PI)
  87416. theta += 2 * Math.PI;
  87417. while (theta > Math.PI)
  87418. theta -= 2 * Math.PI;
  87419. var dx = theta / Math.PI;
  87420. var dy = phi / Math.PI;
  87421. // recenter.
  87422. dx = dx * 0.5 + 0.5;
  87423. var px = Math.round(dx * inputWidth);
  87424. if (px < 0)
  87425. px = 0;
  87426. else if (px >= inputWidth)
  87427. px = inputWidth - 1;
  87428. var py = Math.round(dy * inputHeight);
  87429. if (py < 0)
  87430. py = 0;
  87431. else if (py >= inputHeight)
  87432. py = inputHeight - 1;
  87433. var inputY = (inputHeight - py - 1);
  87434. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  87435. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  87436. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  87437. return {
  87438. r: r,
  87439. g: g,
  87440. b: b
  87441. };
  87442. };
  87443. PanoramaToCubeMapTools.FACE_FRONT = [
  87444. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87445. new BABYLON.Vector3(1.0, -1.0, -1.0),
  87446. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  87447. new BABYLON.Vector3(1.0, 1.0, -1.0)
  87448. ];
  87449. PanoramaToCubeMapTools.FACE_BACK = [
  87450. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87451. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87452. new BABYLON.Vector3(1.0, 1.0, 1.0),
  87453. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  87454. ];
  87455. PanoramaToCubeMapTools.FACE_RIGHT = [
  87456. new BABYLON.Vector3(1.0, -1.0, -1.0),
  87457. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87458. new BABYLON.Vector3(1.0, 1.0, -1.0),
  87459. new BABYLON.Vector3(1.0, 1.0, 1.0)
  87460. ];
  87461. PanoramaToCubeMapTools.FACE_LEFT = [
  87462. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87463. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87464. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  87465. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  87466. ];
  87467. PanoramaToCubeMapTools.FACE_DOWN = [
  87468. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  87469. new BABYLON.Vector3(1.0, 1.0, -1.0),
  87470. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  87471. new BABYLON.Vector3(1.0, 1.0, 1.0)
  87472. ];
  87473. PanoramaToCubeMapTools.FACE_UP = [
  87474. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87475. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87476. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87477. new BABYLON.Vector3(1.0, -1.0, -1.0)
  87478. ];
  87479. return PanoramaToCubeMapTools;
  87480. }());
  87481. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  87482. })(BABYLON || (BABYLON = {}));
  87483. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  87484. var BABYLON;
  87485. (function (BABYLON) {
  87486. var IndexedVector2 = /** @class */ (function (_super) {
  87487. __extends(IndexedVector2, _super);
  87488. function IndexedVector2(original, index) {
  87489. var _this = _super.call(this, original.x, original.y) || this;
  87490. _this.index = index;
  87491. return _this;
  87492. }
  87493. return IndexedVector2;
  87494. }(BABYLON.Vector2));
  87495. var PolygonPoints = /** @class */ (function () {
  87496. function PolygonPoints() {
  87497. this.elements = new Array();
  87498. }
  87499. PolygonPoints.prototype.add = function (originalPoints) {
  87500. var _this = this;
  87501. var result = new Array();
  87502. originalPoints.forEach(function (point) {
  87503. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  87504. var newPoint = new IndexedVector2(point, _this.elements.length);
  87505. result.push(newPoint);
  87506. _this.elements.push(newPoint);
  87507. }
  87508. });
  87509. return result;
  87510. };
  87511. PolygonPoints.prototype.computeBounds = function () {
  87512. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  87513. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  87514. this.elements.forEach(function (point) {
  87515. // x
  87516. if (point.x < lmin.x) {
  87517. lmin.x = point.x;
  87518. }
  87519. else if (point.x > lmax.x) {
  87520. lmax.x = point.x;
  87521. }
  87522. // y
  87523. if (point.y < lmin.y) {
  87524. lmin.y = point.y;
  87525. }
  87526. else if (point.y > lmax.y) {
  87527. lmax.y = point.y;
  87528. }
  87529. });
  87530. return {
  87531. min: lmin,
  87532. max: lmax,
  87533. width: lmax.x - lmin.x,
  87534. height: lmax.y - lmin.y
  87535. };
  87536. };
  87537. return PolygonPoints;
  87538. }());
  87539. var Polygon = /** @class */ (function () {
  87540. function Polygon() {
  87541. }
  87542. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  87543. return [
  87544. new BABYLON.Vector2(xmin, ymin),
  87545. new BABYLON.Vector2(xmax, ymin),
  87546. new BABYLON.Vector2(xmax, ymax),
  87547. new BABYLON.Vector2(xmin, ymax)
  87548. ];
  87549. };
  87550. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  87551. if (cx === void 0) { cx = 0; }
  87552. if (cy === void 0) { cy = 0; }
  87553. if (numberOfSides === void 0) { numberOfSides = 32; }
  87554. var result = new Array();
  87555. var angle = 0;
  87556. var increment = (Math.PI * 2) / numberOfSides;
  87557. for (var i = 0; i < numberOfSides; i++) {
  87558. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  87559. angle -= increment;
  87560. }
  87561. return result;
  87562. };
  87563. Polygon.Parse = function (input) {
  87564. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  87565. var i, result = [];
  87566. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  87567. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  87568. }
  87569. return result;
  87570. };
  87571. Polygon.StartingAt = function (x, y) {
  87572. return BABYLON.Path2.StartingAt(x, y);
  87573. };
  87574. return Polygon;
  87575. }());
  87576. BABYLON.Polygon = Polygon;
  87577. var PolygonMeshBuilder = /** @class */ (function () {
  87578. function PolygonMeshBuilder(name, contours, scene) {
  87579. this._points = new PolygonPoints();
  87580. this._outlinepoints = new PolygonPoints();
  87581. this._holes = new Array();
  87582. this._epoints = new Array();
  87583. this._eholes = new Array();
  87584. this._name = name;
  87585. this._scene = scene;
  87586. var points;
  87587. if (contours instanceof BABYLON.Path2) {
  87588. points = contours.getPoints();
  87589. }
  87590. else {
  87591. points = contours;
  87592. }
  87593. this._addToepoint(points);
  87594. this._points.add(points);
  87595. this._outlinepoints.add(points);
  87596. if (typeof earcut === 'undefined') {
  87597. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  87598. }
  87599. }
  87600. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  87601. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  87602. var p = points_1[_i];
  87603. this._epoints.push(p.x, p.y);
  87604. }
  87605. };
  87606. PolygonMeshBuilder.prototype.addHole = function (hole) {
  87607. this._points.add(hole);
  87608. var holepoints = new PolygonPoints();
  87609. holepoints.add(hole);
  87610. this._holes.push(holepoints);
  87611. this._eholes.push(this._epoints.length / 2);
  87612. this._addToepoint(hole);
  87613. return this;
  87614. };
  87615. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  87616. var _this = this;
  87617. if (updatable === void 0) { updatable = false; }
  87618. if (depth === void 0) { depth = 0; }
  87619. var result = new BABYLON.Mesh(this._name, this._scene);
  87620. var normals = new Array();
  87621. var positions = new Array();
  87622. var uvs = new Array();
  87623. var bounds = this._points.computeBounds();
  87624. this._points.elements.forEach(function (p) {
  87625. normals.push(0, 1.0, 0);
  87626. positions.push(p.x, 0, p.y);
  87627. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  87628. });
  87629. var indices = new Array();
  87630. var res = earcut(this._epoints, this._eholes, 2);
  87631. for (var i = 0; i < res.length; i++) {
  87632. indices.push(res[i]);
  87633. }
  87634. if (depth > 0) {
  87635. var positionscount = (positions.length / 3); //get the current pointcount
  87636. this._points.elements.forEach(function (p) {
  87637. normals.push(0, -1.0, 0);
  87638. positions.push(p.x, -depth, p.y);
  87639. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  87640. });
  87641. var totalCount = indices.length;
  87642. for (var i = 0; i < totalCount; i += 3) {
  87643. var i0 = indices[i + 0];
  87644. var i1 = indices[i + 1];
  87645. var i2 = indices[i + 2];
  87646. indices.push(i2 + positionscount);
  87647. indices.push(i1 + positionscount);
  87648. indices.push(i0 + positionscount);
  87649. }
  87650. //Add the sides
  87651. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  87652. this._holes.forEach(function (hole) {
  87653. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  87654. });
  87655. }
  87656. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  87657. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  87658. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  87659. result.setIndices(indices);
  87660. return result;
  87661. };
  87662. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  87663. var StartIndex = positions.length / 3;
  87664. var ulength = 0;
  87665. for (var i = 0; i < points.elements.length; i++) {
  87666. var p = points.elements[i];
  87667. var p1;
  87668. if ((i + 1) > points.elements.length - 1) {
  87669. p1 = points.elements[0];
  87670. }
  87671. else {
  87672. p1 = points.elements[i + 1];
  87673. }
  87674. positions.push(p.x, 0, p.y);
  87675. positions.push(p.x, -depth, p.y);
  87676. positions.push(p1.x, 0, p1.y);
  87677. positions.push(p1.x, -depth, p1.y);
  87678. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  87679. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  87680. var v3 = v2.subtract(v1);
  87681. var v4 = new BABYLON.Vector3(0, 1, 0);
  87682. var vn = BABYLON.Vector3.Cross(v3, v4);
  87683. vn = vn.normalize();
  87684. uvs.push(ulength / bounds.width, 0);
  87685. uvs.push(ulength / bounds.width, 1);
  87686. ulength += v3.length();
  87687. uvs.push((ulength / bounds.width), 0);
  87688. uvs.push((ulength / bounds.width), 1);
  87689. if (!flip) {
  87690. normals.push(-vn.x, -vn.y, -vn.z);
  87691. normals.push(-vn.x, -vn.y, -vn.z);
  87692. normals.push(-vn.x, -vn.y, -vn.z);
  87693. normals.push(-vn.x, -vn.y, -vn.z);
  87694. indices.push(StartIndex);
  87695. indices.push(StartIndex + 1);
  87696. indices.push(StartIndex + 2);
  87697. indices.push(StartIndex + 1);
  87698. indices.push(StartIndex + 3);
  87699. indices.push(StartIndex + 2);
  87700. }
  87701. else {
  87702. normals.push(vn.x, vn.y, vn.z);
  87703. normals.push(vn.x, vn.y, vn.z);
  87704. normals.push(vn.x, vn.y, vn.z);
  87705. normals.push(vn.x, vn.y, vn.z);
  87706. indices.push(StartIndex);
  87707. indices.push(StartIndex + 2);
  87708. indices.push(StartIndex + 1);
  87709. indices.push(StartIndex + 1);
  87710. indices.push(StartIndex + 2);
  87711. indices.push(StartIndex + 3);
  87712. }
  87713. StartIndex += 4;
  87714. }
  87715. ;
  87716. };
  87717. return PolygonMeshBuilder;
  87718. }());
  87719. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  87720. })(BABYLON || (BABYLON = {}));
  87721. //# sourceMappingURL=babylon.polygonMesh.js.map
  87722. var BABYLON;
  87723. (function (BABYLON) {
  87724. // Unique ID when we import meshes from Babylon to CSG
  87725. var currentCSGMeshId = 0;
  87726. // # class Vertex
  87727. // Represents a vertex of a polygon. Use your own vertex class instead of this
  87728. // one to provide additional features like texture coordinates and vertex
  87729. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  87730. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  87731. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  87732. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  87733. // is not used anywhere else.
  87734. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  87735. var Vertex = /** @class */ (function () {
  87736. function Vertex(pos, normal, uv) {
  87737. this.pos = pos;
  87738. this.normal = normal;
  87739. this.uv = uv;
  87740. }
  87741. Vertex.prototype.clone = function () {
  87742. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  87743. };
  87744. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  87745. // orientation of a polygon is flipped.
  87746. Vertex.prototype.flip = function () {
  87747. this.normal = this.normal.scale(-1);
  87748. };
  87749. // Create a new vertex between this vertex and `other` by linearly
  87750. // interpolating all properties using a parameter of `t`. Subclasses should
  87751. // override this to interpolate additional properties.
  87752. Vertex.prototype.interpolate = function (other, t) {
  87753. 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));
  87754. };
  87755. return Vertex;
  87756. }());
  87757. // # class Plane
  87758. // Represents a plane in 3D space.
  87759. var Plane = /** @class */ (function () {
  87760. function Plane(normal, w) {
  87761. this.normal = normal;
  87762. this.w = w;
  87763. }
  87764. Plane.FromPoints = function (a, b, c) {
  87765. var v0 = c.subtract(a);
  87766. var v1 = b.subtract(a);
  87767. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  87768. return null;
  87769. }
  87770. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  87771. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  87772. };
  87773. Plane.prototype.clone = function () {
  87774. return new Plane(this.normal.clone(), this.w);
  87775. };
  87776. Plane.prototype.flip = function () {
  87777. this.normal.scaleInPlace(-1);
  87778. this.w = -this.w;
  87779. };
  87780. // Split `polygon` by this plane if needed, then put the polygon or polygon
  87781. // fragments in the appropriate lists. Coplanar polygons go into either
  87782. // `coplanarFront` or `coplanarBack` depending on their orientation with
  87783. // respect to this plane. Polygons in front or in back of this plane go into
  87784. // either `front` or `back`.
  87785. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  87786. var COPLANAR = 0;
  87787. var FRONT = 1;
  87788. var BACK = 2;
  87789. var SPANNING = 3;
  87790. // Classify each point as well as the entire polygon into one of the above
  87791. // four classes.
  87792. var polygonType = 0;
  87793. var types = [];
  87794. var i;
  87795. var t;
  87796. for (i = 0; i < polygon.vertices.length; i++) {
  87797. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  87798. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  87799. polygonType |= type;
  87800. types.push(type);
  87801. }
  87802. // Put the polygon in the correct list, splitting it when necessary.
  87803. switch (polygonType) {
  87804. case COPLANAR:
  87805. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  87806. break;
  87807. case FRONT:
  87808. front.push(polygon);
  87809. break;
  87810. case BACK:
  87811. back.push(polygon);
  87812. break;
  87813. case SPANNING:
  87814. var f = [], b = [];
  87815. for (i = 0; i < polygon.vertices.length; i++) {
  87816. var j = (i + 1) % polygon.vertices.length;
  87817. var ti = types[i], tj = types[j];
  87818. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  87819. if (ti !== BACK)
  87820. f.push(vi);
  87821. if (ti !== FRONT)
  87822. b.push(ti !== BACK ? vi.clone() : vi);
  87823. if ((ti | tj) === SPANNING) {
  87824. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  87825. var v = vi.interpolate(vj, t);
  87826. f.push(v);
  87827. b.push(v.clone());
  87828. }
  87829. }
  87830. var poly;
  87831. if (f.length >= 3) {
  87832. poly = new Polygon(f, polygon.shared);
  87833. if (poly.plane)
  87834. front.push(poly);
  87835. }
  87836. if (b.length >= 3) {
  87837. poly = new Polygon(b, polygon.shared);
  87838. if (poly.plane)
  87839. back.push(poly);
  87840. }
  87841. break;
  87842. }
  87843. };
  87844. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  87845. // point is on the plane.
  87846. Plane.EPSILON = 1e-5;
  87847. return Plane;
  87848. }());
  87849. // # class Polygon
  87850. // Represents a convex polygon. The vertices used to initialize a polygon must
  87851. // be coplanar and form a convex loop.
  87852. //
  87853. // Each convex polygon has a `shared` property, which is shared between all
  87854. // polygons that are clones of each other or were split from the same polygon.
  87855. // This can be used to define per-polygon properties (such as surface color).
  87856. var Polygon = /** @class */ (function () {
  87857. function Polygon(vertices, shared) {
  87858. this.vertices = vertices;
  87859. this.shared = shared;
  87860. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  87861. }
  87862. Polygon.prototype.clone = function () {
  87863. var vertices = this.vertices.map(function (v) { return v.clone(); });
  87864. return new Polygon(vertices, this.shared);
  87865. };
  87866. Polygon.prototype.flip = function () {
  87867. this.vertices.reverse().map(function (v) { v.flip(); });
  87868. this.plane.flip();
  87869. };
  87870. return Polygon;
  87871. }());
  87872. // # class Node
  87873. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  87874. // by picking a polygon to split along. That polygon (and all other coplanar
  87875. // polygons) are added directly to that node and the other polygons are added to
  87876. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  87877. // no distinction between internal and leaf nodes.
  87878. var Node = /** @class */ (function () {
  87879. function Node(polygons) {
  87880. this.plane = null;
  87881. this.front = null;
  87882. this.back = null;
  87883. this.polygons = new Array();
  87884. if (polygons) {
  87885. this.build(polygons);
  87886. }
  87887. }
  87888. Node.prototype.clone = function () {
  87889. var node = new Node();
  87890. node.plane = this.plane && this.plane.clone();
  87891. node.front = this.front && this.front.clone();
  87892. node.back = this.back && this.back.clone();
  87893. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  87894. return node;
  87895. };
  87896. // Convert solid space to empty space and empty space to solid space.
  87897. Node.prototype.invert = function () {
  87898. for (var i = 0; i < this.polygons.length; i++) {
  87899. this.polygons[i].flip();
  87900. }
  87901. if (this.plane) {
  87902. this.plane.flip();
  87903. }
  87904. if (this.front) {
  87905. this.front.invert();
  87906. }
  87907. if (this.back) {
  87908. this.back.invert();
  87909. }
  87910. var temp = this.front;
  87911. this.front = this.back;
  87912. this.back = temp;
  87913. };
  87914. // Recursively remove all polygons in `polygons` that are inside this BSP
  87915. // tree.
  87916. Node.prototype.clipPolygons = function (polygons) {
  87917. if (!this.plane)
  87918. return polygons.slice();
  87919. var front = new Array(), back = new Array();
  87920. for (var i = 0; i < polygons.length; i++) {
  87921. this.plane.splitPolygon(polygons[i], front, back, front, back);
  87922. }
  87923. if (this.front) {
  87924. front = this.front.clipPolygons(front);
  87925. }
  87926. if (this.back) {
  87927. back = this.back.clipPolygons(back);
  87928. }
  87929. else {
  87930. back = [];
  87931. }
  87932. return front.concat(back);
  87933. };
  87934. // Remove all polygons in this BSP tree that are inside the other BSP tree
  87935. // `bsp`.
  87936. Node.prototype.clipTo = function (bsp) {
  87937. this.polygons = bsp.clipPolygons(this.polygons);
  87938. if (this.front)
  87939. this.front.clipTo(bsp);
  87940. if (this.back)
  87941. this.back.clipTo(bsp);
  87942. };
  87943. // Return a list of all polygons in this BSP tree.
  87944. Node.prototype.allPolygons = function () {
  87945. var polygons = this.polygons.slice();
  87946. if (this.front)
  87947. polygons = polygons.concat(this.front.allPolygons());
  87948. if (this.back)
  87949. polygons = polygons.concat(this.back.allPolygons());
  87950. return polygons;
  87951. };
  87952. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  87953. // new polygons are filtered down to the bottom of the tree and become new
  87954. // nodes there. Each set of polygons is partitioned using the first polygon
  87955. // (no heuristic is used to pick a good split).
  87956. Node.prototype.build = function (polygons) {
  87957. if (!polygons.length)
  87958. return;
  87959. if (!this.plane)
  87960. this.plane = polygons[0].plane.clone();
  87961. var front = new Array(), back = new Array();
  87962. for (var i = 0; i < polygons.length; i++) {
  87963. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  87964. }
  87965. if (front.length) {
  87966. if (!this.front)
  87967. this.front = new Node();
  87968. this.front.build(front);
  87969. }
  87970. if (back.length) {
  87971. if (!this.back)
  87972. this.back = new Node();
  87973. this.back.build(back);
  87974. }
  87975. };
  87976. return Node;
  87977. }());
  87978. var CSG = /** @class */ (function () {
  87979. function CSG() {
  87980. this.polygons = new Array();
  87981. }
  87982. // Convert BABYLON.Mesh to BABYLON.CSG
  87983. CSG.FromMesh = function (mesh) {
  87984. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  87985. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  87986. if (mesh instanceof BABYLON.Mesh) {
  87987. mesh.computeWorldMatrix(true);
  87988. matrix = mesh.getWorldMatrix();
  87989. meshPosition = mesh.position.clone();
  87990. meshRotation = mesh.rotation.clone();
  87991. if (mesh.rotationQuaternion) {
  87992. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  87993. }
  87994. meshScaling = mesh.scaling.clone();
  87995. }
  87996. else {
  87997. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  87998. }
  87999. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  88000. var subMeshes = mesh.subMeshes;
  88001. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  88002. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  88003. vertices = [];
  88004. for (var j = 0; j < 3; j++) {
  88005. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  88006. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  88007. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  88008. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  88009. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  88010. vertex = new Vertex(position, normal, uv);
  88011. vertices.push(vertex);
  88012. }
  88013. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  88014. // To handle the case of degenerated triangle
  88015. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  88016. if (polygon.plane)
  88017. polygons.push(polygon);
  88018. }
  88019. }
  88020. var csg = CSG.FromPolygons(polygons);
  88021. csg.matrix = matrix;
  88022. csg.position = meshPosition;
  88023. csg.rotation = meshRotation;
  88024. csg.scaling = meshScaling;
  88025. csg.rotationQuaternion = meshRotationQuaternion;
  88026. currentCSGMeshId++;
  88027. return csg;
  88028. };
  88029. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  88030. CSG.FromPolygons = function (polygons) {
  88031. var csg = new CSG();
  88032. csg.polygons = polygons;
  88033. return csg;
  88034. };
  88035. CSG.prototype.clone = function () {
  88036. var csg = new CSG();
  88037. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  88038. csg.copyTransformAttributes(this);
  88039. return csg;
  88040. };
  88041. CSG.prototype.union = function (csg) {
  88042. var a = new Node(this.clone().polygons);
  88043. var b = new Node(csg.clone().polygons);
  88044. a.clipTo(b);
  88045. b.clipTo(a);
  88046. b.invert();
  88047. b.clipTo(a);
  88048. b.invert();
  88049. a.build(b.allPolygons());
  88050. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  88051. };
  88052. CSG.prototype.unionInPlace = function (csg) {
  88053. var a = new Node(this.polygons);
  88054. var b = new Node(csg.polygons);
  88055. a.clipTo(b);
  88056. b.clipTo(a);
  88057. b.invert();
  88058. b.clipTo(a);
  88059. b.invert();
  88060. a.build(b.allPolygons());
  88061. this.polygons = a.allPolygons();
  88062. };
  88063. CSG.prototype.subtract = function (csg) {
  88064. var a = new Node(this.clone().polygons);
  88065. var b = new Node(csg.clone().polygons);
  88066. a.invert();
  88067. a.clipTo(b);
  88068. b.clipTo(a);
  88069. b.invert();
  88070. b.clipTo(a);
  88071. b.invert();
  88072. a.build(b.allPolygons());
  88073. a.invert();
  88074. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  88075. };
  88076. CSG.prototype.subtractInPlace = function (csg) {
  88077. var a = new Node(this.polygons);
  88078. var b = new Node(csg.polygons);
  88079. a.invert();
  88080. a.clipTo(b);
  88081. b.clipTo(a);
  88082. b.invert();
  88083. b.clipTo(a);
  88084. b.invert();
  88085. a.build(b.allPolygons());
  88086. a.invert();
  88087. this.polygons = a.allPolygons();
  88088. };
  88089. CSG.prototype.intersect = function (csg) {
  88090. var a = new Node(this.clone().polygons);
  88091. var b = new Node(csg.clone().polygons);
  88092. a.invert();
  88093. b.clipTo(a);
  88094. b.invert();
  88095. a.clipTo(b);
  88096. b.clipTo(a);
  88097. a.build(b.allPolygons());
  88098. a.invert();
  88099. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  88100. };
  88101. CSG.prototype.intersectInPlace = function (csg) {
  88102. var a = new Node(this.polygons);
  88103. var b = new Node(csg.polygons);
  88104. a.invert();
  88105. b.clipTo(a);
  88106. b.invert();
  88107. a.clipTo(b);
  88108. b.clipTo(a);
  88109. a.build(b.allPolygons());
  88110. a.invert();
  88111. this.polygons = a.allPolygons();
  88112. };
  88113. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  88114. // not modified.
  88115. CSG.prototype.inverse = function () {
  88116. var csg = this.clone();
  88117. csg.inverseInPlace();
  88118. return csg;
  88119. };
  88120. CSG.prototype.inverseInPlace = function () {
  88121. this.polygons.map(function (p) { p.flip(); });
  88122. };
  88123. // This is used to keep meshes transformations so they can be restored
  88124. // when we build back a Babylon Mesh
  88125. // NB : All CSG operations are performed in world coordinates
  88126. CSG.prototype.copyTransformAttributes = function (csg) {
  88127. this.matrix = csg.matrix;
  88128. this.position = csg.position;
  88129. this.rotation = csg.rotation;
  88130. this.scaling = csg.scaling;
  88131. this.rotationQuaternion = csg.rotationQuaternion;
  88132. return this;
  88133. };
  88134. // Build Raw mesh from CSG
  88135. // Coordinates here are in world space
  88136. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  88137. var matrix = this.matrix.clone();
  88138. matrix.invert();
  88139. 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;
  88140. if (keepSubMeshes) {
  88141. // Sort Polygons, since subMeshes are indices range
  88142. polygons.sort(function (a, b) {
  88143. if (a.shared.meshId === b.shared.meshId) {
  88144. return a.shared.subMeshId - b.shared.subMeshId;
  88145. }
  88146. else {
  88147. return a.shared.meshId - b.shared.meshId;
  88148. }
  88149. });
  88150. }
  88151. for (var i = 0, il = polygons.length; i < il; i++) {
  88152. polygon = polygons[i];
  88153. // Building SubMeshes
  88154. if (!subMesh_dict[polygon.shared.meshId]) {
  88155. subMesh_dict[polygon.shared.meshId] = {};
  88156. }
  88157. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  88158. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  88159. indexStart: +Infinity,
  88160. indexEnd: -Infinity,
  88161. materialIndex: polygon.shared.materialIndex
  88162. };
  88163. }
  88164. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  88165. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  88166. polygonIndices[0] = 0;
  88167. polygonIndices[1] = j - 1;
  88168. polygonIndices[2] = j;
  88169. for (var k = 0; k < 3; k++) {
  88170. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  88171. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  88172. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  88173. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  88174. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  88175. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  88176. // Check if 2 points can be merged
  88177. if (!(typeof vertex_idx !== 'undefined' &&
  88178. normals[vertex_idx * 3] === localNormal.x &&
  88179. normals[vertex_idx * 3 + 1] === localNormal.y &&
  88180. normals[vertex_idx * 3 + 2] === localNormal.z &&
  88181. uvs[vertex_idx * 2] === uv.x &&
  88182. uvs[vertex_idx * 2 + 1] === uv.y)) {
  88183. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  88184. uvs.push(uv.x, uv.y);
  88185. normals.push(normal.x, normal.y, normal.z);
  88186. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  88187. }
  88188. indices.push(vertex_idx);
  88189. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  88190. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  88191. currentIndex++;
  88192. }
  88193. }
  88194. }
  88195. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  88196. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  88197. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  88198. mesh.setIndices(indices, null);
  88199. if (keepSubMeshes) {
  88200. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  88201. var materialIndexOffset = 0, materialMaxIndex;
  88202. mesh.subMeshes = new Array();
  88203. for (var m in subMesh_dict) {
  88204. materialMaxIndex = -1;
  88205. for (var sm in subMesh_dict[m]) {
  88206. subMesh_obj = subMesh_dict[m][sm];
  88207. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  88208. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  88209. }
  88210. materialIndexOffset += ++materialMaxIndex;
  88211. }
  88212. }
  88213. return mesh;
  88214. };
  88215. // Build Mesh from CSG taking material and transforms into account
  88216. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  88217. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  88218. mesh.material = material;
  88219. mesh.position.copyFrom(this.position);
  88220. mesh.rotation.copyFrom(this.rotation);
  88221. if (this.rotationQuaternion) {
  88222. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  88223. }
  88224. mesh.scaling.copyFrom(this.scaling);
  88225. mesh.computeWorldMatrix(true);
  88226. return mesh;
  88227. };
  88228. return CSG;
  88229. }());
  88230. BABYLON.CSG = CSG;
  88231. })(BABYLON || (BABYLON = {}));
  88232. //# sourceMappingURL=babylon.csg.js.map
  88233. var BABYLON;
  88234. (function (BABYLON) {
  88235. var LensFlare = /** @class */ (function () {
  88236. function LensFlare(size, position, color, imgUrl, system) {
  88237. this.size = size;
  88238. this.position = position;
  88239. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  88240. this.color = color || new BABYLON.Color3(1, 1, 1);
  88241. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  88242. this._system = system;
  88243. system.lensFlares.push(this);
  88244. }
  88245. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  88246. return new LensFlare(size, position, color, imgUrl, system);
  88247. };
  88248. LensFlare.prototype.dispose = function () {
  88249. if (this.texture) {
  88250. this.texture.dispose();
  88251. }
  88252. // Remove from scene
  88253. var index = this._system.lensFlares.indexOf(this);
  88254. this._system.lensFlares.splice(index, 1);
  88255. };
  88256. ;
  88257. return LensFlare;
  88258. }());
  88259. BABYLON.LensFlare = LensFlare;
  88260. })(BABYLON || (BABYLON = {}));
  88261. //# sourceMappingURL=babylon.lensFlare.js.map
  88262. var BABYLON;
  88263. (function (BABYLON) {
  88264. // Adds the parser to the scene parsers.
  88265. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  88266. // Lens flares
  88267. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  88268. if (!container.lensFlareSystems) {
  88269. container.lensFlareSystems = new Array();
  88270. }
  88271. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  88272. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  88273. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  88274. container.lensFlareSystems.push(lf);
  88275. }
  88276. }
  88277. });
  88278. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  88279. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  88280. if (this.lensFlareSystems[index].name === name) {
  88281. return this.lensFlareSystems[index];
  88282. }
  88283. }
  88284. return null;
  88285. };
  88286. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  88287. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  88288. if (this.lensFlareSystems[index].id === id) {
  88289. return this.lensFlareSystems[index];
  88290. }
  88291. }
  88292. return null;
  88293. };
  88294. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  88295. var index = this.lensFlareSystems.indexOf(toRemove);
  88296. if (index !== -1) {
  88297. this.lensFlareSystems.splice(index, 1);
  88298. }
  88299. return index;
  88300. };
  88301. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  88302. this.lensFlareSystems.push(newLensFlareSystem);
  88303. };
  88304. /**
  88305. * Defines the lens flare scene component responsible to manage any lens flares
  88306. * in a given scene.
  88307. */
  88308. var LensFlareSystemSceneComponent = /** @class */ (function () {
  88309. /**
  88310. * Creates a new instance of the component for the given scene
  88311. * @param scene Defines the scene to register the component in
  88312. */
  88313. function LensFlareSystemSceneComponent(scene) {
  88314. /**
  88315. * The component name helpfull to identify the component in the list of scene components.
  88316. */
  88317. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  88318. this.scene = scene;
  88319. scene.lensFlareSystems = new Array();
  88320. }
  88321. /**
  88322. * Registers the component in a given scene
  88323. */
  88324. LensFlareSystemSceneComponent.prototype.register = function () {
  88325. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  88326. };
  88327. /**
  88328. * Rebuilds the elements related to this component in case of
  88329. * context lost for instance.
  88330. */
  88331. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  88332. // Nothing to do for lens flare
  88333. };
  88334. /**
  88335. * Adds all the element from the container to the scene
  88336. * @param container the container holding the elements
  88337. */
  88338. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  88339. var _this = this;
  88340. if (!container.lensFlareSystems) {
  88341. return;
  88342. }
  88343. container.lensFlareSystems.forEach(function (o) {
  88344. _this.scene.addLensFlareSystem(o);
  88345. });
  88346. };
  88347. /**
  88348. * Removes all the elements in the container from the scene
  88349. * @param container contains the elements to remove
  88350. */
  88351. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  88352. var _this = this;
  88353. if (!container.lensFlareSystems) {
  88354. return;
  88355. }
  88356. container.lensFlareSystems.forEach(function (o) {
  88357. _this.scene.removeLensFlareSystem(o);
  88358. });
  88359. };
  88360. /**
  88361. * Serializes the component data to the specified json object
  88362. * @param serializationObject The object to serialize to
  88363. */
  88364. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  88365. // Lens flares
  88366. serializationObject.lensFlareSystems = [];
  88367. var lensFlareSystems = this.scene.lensFlareSystems;
  88368. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  88369. var lensFlareSystem = lensFlareSystems_1[_i];
  88370. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  88371. }
  88372. };
  88373. /**
  88374. * Disposes the component and the associated ressources.
  88375. */
  88376. LensFlareSystemSceneComponent.prototype.dispose = function () {
  88377. var lensFlareSystems = this.scene.lensFlareSystems;
  88378. while (lensFlareSystems.length) {
  88379. lensFlareSystems[0].dispose();
  88380. }
  88381. };
  88382. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  88383. // Lens flares
  88384. if (this.scene.lensFlaresEnabled) {
  88385. var lensFlareSystems = this.scene.lensFlareSystems;
  88386. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  88387. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  88388. var lensFlareSystem = lensFlareSystems_2[_i];
  88389. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  88390. lensFlareSystem.render();
  88391. }
  88392. }
  88393. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  88394. }
  88395. };
  88396. return LensFlareSystemSceneComponent;
  88397. }());
  88398. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  88399. })(BABYLON || (BABYLON = {}));
  88400. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  88401. var BABYLON;
  88402. (function (BABYLON) {
  88403. var LensFlareSystem = /** @class */ (function () {
  88404. function LensFlareSystem(name, emitter, scene) {
  88405. this.name = name;
  88406. this.lensFlares = new Array();
  88407. this.borderLimit = 300;
  88408. this.viewportBorder = 0;
  88409. this.layerMask = 0x0FFFFFFF;
  88410. this._vertexBuffers = {};
  88411. this._isEnabled = true;
  88412. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88413. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  88414. if (!component) {
  88415. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  88416. scene._addComponent(component);
  88417. }
  88418. this._emitter = emitter;
  88419. this.id = name;
  88420. scene.lensFlareSystems.push(this);
  88421. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  88422. var engine = scene.getEngine();
  88423. // VBO
  88424. var vertices = [];
  88425. vertices.push(1, 1);
  88426. vertices.push(-1, 1);
  88427. vertices.push(-1, -1);
  88428. vertices.push(1, -1);
  88429. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88430. // Indices
  88431. var indices = [];
  88432. indices.push(0);
  88433. indices.push(1);
  88434. indices.push(2);
  88435. indices.push(0);
  88436. indices.push(2);
  88437. indices.push(3);
  88438. this._indexBuffer = engine.createIndexBuffer(indices);
  88439. // Effects
  88440. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  88441. }
  88442. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  88443. get: function () {
  88444. return this._isEnabled;
  88445. },
  88446. set: function (value) {
  88447. this._isEnabled = value;
  88448. },
  88449. enumerable: true,
  88450. configurable: true
  88451. });
  88452. LensFlareSystem.prototype.getScene = function () {
  88453. return this._scene;
  88454. };
  88455. LensFlareSystem.prototype.getEmitter = function () {
  88456. return this._emitter;
  88457. };
  88458. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  88459. this._emitter = newEmitter;
  88460. };
  88461. LensFlareSystem.prototype.getEmitterPosition = function () {
  88462. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  88463. };
  88464. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  88465. var position = this.getEmitterPosition();
  88466. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  88467. this._positionX = position.x;
  88468. this._positionY = position.y;
  88469. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  88470. if (this.viewportBorder > 0) {
  88471. globalViewport.x -= this.viewportBorder;
  88472. globalViewport.y -= this.viewportBorder;
  88473. globalViewport.width += this.viewportBorder * 2;
  88474. globalViewport.height += this.viewportBorder * 2;
  88475. position.x += this.viewportBorder;
  88476. position.y += this.viewportBorder;
  88477. this._positionX += this.viewportBorder;
  88478. this._positionY += this.viewportBorder;
  88479. }
  88480. if (position.z > 0) {
  88481. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  88482. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  88483. return true;
  88484. }
  88485. return true;
  88486. }
  88487. return false;
  88488. };
  88489. /** @hidden */
  88490. LensFlareSystem.prototype._isVisible = function () {
  88491. if (!this._isEnabled || !this._scene.activeCamera) {
  88492. return false;
  88493. }
  88494. var emitterPosition = this.getEmitterPosition();
  88495. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  88496. var distance = direction.length();
  88497. direction.normalize();
  88498. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  88499. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  88500. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  88501. };
  88502. LensFlareSystem.prototype.render = function () {
  88503. if (!this._effect.isReady() || !this._scene.activeCamera)
  88504. return false;
  88505. var engine = this._scene.getEngine();
  88506. var viewport = this._scene.activeCamera.viewport;
  88507. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  88508. // Position
  88509. if (!this.computeEffectivePosition(globalViewport)) {
  88510. return false;
  88511. }
  88512. // Visibility
  88513. if (!this._isVisible()) {
  88514. return false;
  88515. }
  88516. // Intensity
  88517. var awayX;
  88518. var awayY;
  88519. if (this._positionX < this.borderLimit + globalViewport.x) {
  88520. awayX = this.borderLimit + globalViewport.x - this._positionX;
  88521. }
  88522. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  88523. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  88524. }
  88525. else {
  88526. awayX = 0;
  88527. }
  88528. if (this._positionY < this.borderLimit + globalViewport.y) {
  88529. awayY = this.borderLimit + globalViewport.y - this._positionY;
  88530. }
  88531. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  88532. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  88533. }
  88534. else {
  88535. awayY = 0;
  88536. }
  88537. var away = (awayX > awayY) ? awayX : awayY;
  88538. away -= this.viewportBorder;
  88539. if (away > this.borderLimit) {
  88540. away = this.borderLimit;
  88541. }
  88542. var intensity = 1.0 - (away / this.borderLimit);
  88543. if (intensity < 0) {
  88544. return false;
  88545. }
  88546. if (intensity > 1.0) {
  88547. intensity = 1.0;
  88548. }
  88549. if (this.viewportBorder > 0) {
  88550. globalViewport.x += this.viewportBorder;
  88551. globalViewport.y += this.viewportBorder;
  88552. globalViewport.width -= this.viewportBorder * 2;
  88553. globalViewport.height -= this.viewportBorder * 2;
  88554. this._positionX -= this.viewportBorder;
  88555. this._positionY -= this.viewportBorder;
  88556. }
  88557. // Position
  88558. var centerX = globalViewport.x + globalViewport.width / 2;
  88559. var centerY = globalViewport.y + globalViewport.height / 2;
  88560. var distX = centerX - this._positionX;
  88561. var distY = centerY - this._positionY;
  88562. // Effects
  88563. engine.enableEffect(this._effect);
  88564. engine.setState(false);
  88565. engine.setDepthBuffer(false);
  88566. // VBOs
  88567. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  88568. // Flares
  88569. for (var index = 0; index < this.lensFlares.length; index++) {
  88570. var flare = this.lensFlares[index];
  88571. engine.setAlphaMode(flare.alphaMode);
  88572. var x = centerX - (distX * flare.position);
  88573. var y = centerY - (distY * flare.position);
  88574. var cw = flare.size;
  88575. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  88576. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  88577. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  88578. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  88579. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  88580. // Texture
  88581. this._effect.setTexture("textureSampler", flare.texture);
  88582. // Color
  88583. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  88584. // Draw order
  88585. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88586. }
  88587. engine.setDepthBuffer(true);
  88588. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88589. return true;
  88590. };
  88591. LensFlareSystem.prototype.dispose = function () {
  88592. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88593. if (vertexBuffer) {
  88594. vertexBuffer.dispose();
  88595. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88596. }
  88597. if (this._indexBuffer) {
  88598. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88599. this._indexBuffer = null;
  88600. }
  88601. while (this.lensFlares.length) {
  88602. this.lensFlares[0].dispose();
  88603. }
  88604. // Remove from scene
  88605. var index = this._scene.lensFlareSystems.indexOf(this);
  88606. this._scene.lensFlareSystems.splice(index, 1);
  88607. };
  88608. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  88609. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  88610. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  88611. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  88612. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  88613. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  88614. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  88615. var parsedFlare = parsedLensFlareSystem.flares[index];
  88616. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  88617. }
  88618. return lensFlareSystem;
  88619. };
  88620. LensFlareSystem.prototype.serialize = function () {
  88621. var serializationObject = {};
  88622. serializationObject.id = this.id;
  88623. serializationObject.name = this.name;
  88624. serializationObject.emitterId = this.getEmitter().id;
  88625. serializationObject.borderLimit = this.borderLimit;
  88626. serializationObject.flares = [];
  88627. for (var index = 0; index < this.lensFlares.length; index++) {
  88628. var flare = this.lensFlares[index];
  88629. serializationObject.flares.push({
  88630. size: flare.size,
  88631. position: flare.position,
  88632. color: flare.color.asArray(),
  88633. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  88634. });
  88635. }
  88636. return serializationObject;
  88637. };
  88638. return LensFlareSystem;
  88639. }());
  88640. BABYLON.LensFlareSystem = LensFlareSystem;
  88641. })(BABYLON || (BABYLON = {}));
  88642. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  88643. var BABYLON;
  88644. (function (BABYLON) {
  88645. /**
  88646. * This is a holder class for the physics joint created by the physics plugin.
  88647. * It holds a set of functions to control the underlying joint.
  88648. */
  88649. var PhysicsJoint = /** @class */ (function () {
  88650. function PhysicsJoint(type, jointData) {
  88651. this.type = type;
  88652. this.jointData = jointData;
  88653. jointData.nativeParams = jointData.nativeParams || {};
  88654. }
  88655. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  88656. get: function () {
  88657. return this._physicsJoint;
  88658. },
  88659. set: function (newJoint) {
  88660. if (this._physicsJoint) {
  88661. //remove from the wolrd
  88662. }
  88663. this._physicsJoint = newJoint;
  88664. },
  88665. enumerable: true,
  88666. configurable: true
  88667. });
  88668. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  88669. set: function (physicsPlugin) {
  88670. this._physicsPlugin = physicsPlugin;
  88671. },
  88672. enumerable: true,
  88673. configurable: true
  88674. });
  88675. /**
  88676. * Execute a function that is physics-plugin specific.
  88677. * @param {Function} func the function that will be executed.
  88678. * It accepts two parameters: the physics world and the physics joint.
  88679. */
  88680. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  88681. func(this._physicsPlugin.world, this._physicsJoint);
  88682. };
  88683. //TODO check if the native joints are the same
  88684. //Joint Types
  88685. PhysicsJoint.DistanceJoint = 0;
  88686. PhysicsJoint.HingeJoint = 1;
  88687. PhysicsJoint.BallAndSocketJoint = 2;
  88688. PhysicsJoint.WheelJoint = 3;
  88689. PhysicsJoint.SliderJoint = 4;
  88690. //OIMO
  88691. PhysicsJoint.PrismaticJoint = 5;
  88692. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  88693. PhysicsJoint.UniversalJoint = 6;
  88694. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  88695. //Cannon
  88696. //Similar to a Ball-Joint. Different in params
  88697. PhysicsJoint.PointToPointJoint = 8;
  88698. //Cannon only at the moment
  88699. PhysicsJoint.SpringJoint = 9;
  88700. PhysicsJoint.LockJoint = 10;
  88701. return PhysicsJoint;
  88702. }());
  88703. BABYLON.PhysicsJoint = PhysicsJoint;
  88704. /**
  88705. * A class representing a physics distance joint.
  88706. */
  88707. var DistanceJoint = /** @class */ (function (_super) {
  88708. __extends(DistanceJoint, _super);
  88709. function DistanceJoint(jointData) {
  88710. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  88711. }
  88712. /**
  88713. * Update the predefined distance.
  88714. */
  88715. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  88716. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  88717. };
  88718. return DistanceJoint;
  88719. }(PhysicsJoint));
  88720. BABYLON.DistanceJoint = DistanceJoint;
  88721. var MotorEnabledJoint = /** @class */ (function (_super) {
  88722. __extends(MotorEnabledJoint, _super);
  88723. function MotorEnabledJoint(type, jointData) {
  88724. return _super.call(this, type, jointData) || this;
  88725. }
  88726. /**
  88727. * Set the motor values.
  88728. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88729. * @param {number} force the force to apply
  88730. * @param {number} maxForce max force for this motor.
  88731. */
  88732. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  88733. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88734. };
  88735. /**
  88736. * Set the motor's limits.
  88737. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88738. */
  88739. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88740. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88741. };
  88742. return MotorEnabledJoint;
  88743. }(PhysicsJoint));
  88744. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  88745. /**
  88746. * This class represents a single hinge physics joint
  88747. */
  88748. var HingeJoint = /** @class */ (function (_super) {
  88749. __extends(HingeJoint, _super);
  88750. function HingeJoint(jointData) {
  88751. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  88752. }
  88753. /**
  88754. * Set the motor values.
  88755. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88756. * @param {number} force the force to apply
  88757. * @param {number} maxForce max force for this motor.
  88758. */
  88759. HingeJoint.prototype.setMotor = function (force, maxForce) {
  88760. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88761. };
  88762. /**
  88763. * Set the motor's limits.
  88764. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88765. */
  88766. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88767. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88768. };
  88769. return HingeJoint;
  88770. }(MotorEnabledJoint));
  88771. BABYLON.HingeJoint = HingeJoint;
  88772. /**
  88773. * This class represents a dual hinge physics joint (same as wheel joint)
  88774. */
  88775. var Hinge2Joint = /** @class */ (function (_super) {
  88776. __extends(Hinge2Joint, _super);
  88777. function Hinge2Joint(jointData) {
  88778. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  88779. }
  88780. /**
  88781. * Set the motor values.
  88782. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88783. * @param {number} force the force to apply
  88784. * @param {number} maxForce max force for this motor.
  88785. * @param {motorIndex} the motor's index, 0 or 1.
  88786. */
  88787. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  88788. if (motorIndex === void 0) { motorIndex = 0; }
  88789. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  88790. };
  88791. /**
  88792. * Set the motor limits.
  88793. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88794. * @param {number} upperLimit the upper limit
  88795. * @param {number} lowerLimit lower limit
  88796. * @param {motorIndex} the motor's index, 0 or 1.
  88797. */
  88798. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  88799. if (motorIndex === void 0) { motorIndex = 0; }
  88800. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  88801. };
  88802. return Hinge2Joint;
  88803. }(MotorEnabledJoint));
  88804. BABYLON.Hinge2Joint = Hinge2Joint;
  88805. })(BABYLON || (BABYLON = {}));
  88806. //# sourceMappingURL=babylon.physicsJoint.js.map
  88807. var BABYLON;
  88808. (function (BABYLON) {
  88809. var PhysicsImpostor = /** @class */ (function () {
  88810. function PhysicsImpostor(object, type, _options, _scene) {
  88811. if (_options === void 0) { _options = { mass: 0 }; }
  88812. var _this = this;
  88813. this.object = object;
  88814. this.type = type;
  88815. this._options = _options;
  88816. this._scene = _scene;
  88817. this._bodyUpdateRequired = false;
  88818. this._onBeforePhysicsStepCallbacks = new Array();
  88819. this._onAfterPhysicsStepCallbacks = new Array();
  88820. this._onPhysicsCollideCallbacks = [];
  88821. this._deltaPosition = BABYLON.Vector3.Zero();
  88822. this._isDisposed = false;
  88823. //temp variables for parent rotation calculations
  88824. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  88825. this._tmpQuat = new BABYLON.Quaternion();
  88826. this._tmpQuat2 = new BABYLON.Quaternion();
  88827. /**
  88828. * this function is executed by the physics engine.
  88829. */
  88830. this.beforeStep = function () {
  88831. if (!_this._physicsEngine) {
  88832. return;
  88833. }
  88834. _this.object.translate(_this._deltaPosition, -1);
  88835. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  88836. _this.object.computeWorldMatrix(false);
  88837. if (_this.object.parent && _this.object.rotationQuaternion) {
  88838. _this.getParentsRotation();
  88839. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  88840. }
  88841. else {
  88842. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  88843. }
  88844. if (!_this._options.disableBidirectionalTransformation) {
  88845. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  88846. }
  88847. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  88848. func(_this);
  88849. });
  88850. };
  88851. /**
  88852. * this function is executed by the physics engine.
  88853. */
  88854. this.afterStep = function () {
  88855. if (!_this._physicsEngine) {
  88856. return;
  88857. }
  88858. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  88859. func(_this);
  88860. });
  88861. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  88862. // object has now its world rotation. needs to be converted to local.
  88863. if (_this.object.parent && _this.object.rotationQuaternion) {
  88864. _this.getParentsRotation();
  88865. _this._tmpQuat.conjugateInPlace();
  88866. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  88867. }
  88868. // take the position set and make it the absolute position of this object.
  88869. _this.object.setAbsolutePosition(_this.object.position);
  88870. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  88871. _this.object.translate(_this._deltaPosition, 1);
  88872. };
  88873. /**
  88874. * Legacy collision detection event support
  88875. */
  88876. this.onCollideEvent = null;
  88877. //event and body object due to cannon's event-based architecture.
  88878. this.onCollide = function (e) {
  88879. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  88880. return;
  88881. }
  88882. if (!_this._physicsEngine) {
  88883. return;
  88884. }
  88885. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  88886. if (otherImpostor) {
  88887. // Legacy collision detection event support
  88888. if (_this.onCollideEvent) {
  88889. _this.onCollideEvent(_this, otherImpostor);
  88890. }
  88891. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  88892. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  88893. }).forEach(function (obj) {
  88894. obj.callback(_this, otherImpostor);
  88895. });
  88896. }
  88897. };
  88898. //sanity check!
  88899. if (!this.object) {
  88900. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  88901. return;
  88902. }
  88903. //legacy support for old syntax.
  88904. if (!this._scene && object.getScene) {
  88905. this._scene = object.getScene();
  88906. }
  88907. if (!this._scene) {
  88908. return;
  88909. }
  88910. this._physicsEngine = this._scene.getPhysicsEngine();
  88911. if (!this._physicsEngine) {
  88912. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  88913. }
  88914. else {
  88915. //set the object's quaternion, if not set
  88916. if (!this.object.rotationQuaternion) {
  88917. if (this.object.rotation) {
  88918. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  88919. }
  88920. else {
  88921. this.object.rotationQuaternion = new BABYLON.Quaternion();
  88922. }
  88923. }
  88924. //default options params
  88925. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  88926. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  88927. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  88928. this._joints = [];
  88929. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  88930. if (!this.object.parent || this._options.ignoreParent) {
  88931. this._init();
  88932. }
  88933. else if (this.object.parent.physicsImpostor) {
  88934. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  88935. }
  88936. }
  88937. }
  88938. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  88939. get: function () {
  88940. return this._isDisposed;
  88941. },
  88942. enumerable: true,
  88943. configurable: true
  88944. });
  88945. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  88946. get: function () {
  88947. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  88948. },
  88949. set: function (value) {
  88950. this.setMass(value);
  88951. },
  88952. enumerable: true,
  88953. configurable: true
  88954. });
  88955. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  88956. get: function () {
  88957. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  88958. },
  88959. set: function (value) {
  88960. if (!this._physicsEngine) {
  88961. return;
  88962. }
  88963. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  88964. },
  88965. enumerable: true,
  88966. configurable: true
  88967. });
  88968. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  88969. get: function () {
  88970. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  88971. },
  88972. set: function (value) {
  88973. if (!this._physicsEngine) {
  88974. return;
  88975. }
  88976. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  88977. },
  88978. enumerable: true,
  88979. configurable: true
  88980. });
  88981. /**
  88982. * This function will completly initialize this impostor.
  88983. * It will create a new body - but only if this mesh has no parent.
  88984. * If it has, this impostor will not be used other than to define the impostor
  88985. * of the child mesh.
  88986. * @hidden
  88987. */
  88988. PhysicsImpostor.prototype._init = function () {
  88989. if (!this._physicsEngine) {
  88990. return;
  88991. }
  88992. this._physicsEngine.removeImpostor(this);
  88993. this.physicsBody = null;
  88994. this._parent = this._parent || this._getPhysicsParent();
  88995. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  88996. this._physicsEngine.addImpostor(this);
  88997. }
  88998. };
  88999. PhysicsImpostor.prototype._getPhysicsParent = function () {
  89000. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  89001. var parentMesh = this.object.parent;
  89002. return parentMesh.physicsImpostor;
  89003. }
  89004. return null;
  89005. };
  89006. /**
  89007. * Should a new body be generated.
  89008. */
  89009. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  89010. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  89011. };
  89012. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  89013. this.forceUpdate();
  89014. };
  89015. /**
  89016. * Force a regeneration of this or the parent's impostor's body.
  89017. * Use under cautious - This will remove all joints already implemented.
  89018. */
  89019. PhysicsImpostor.prototype.forceUpdate = function () {
  89020. this._init();
  89021. if (this.parent && !this._options.ignoreParent) {
  89022. this.parent.forceUpdate();
  89023. }
  89024. };
  89025. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  89026. /*public get mesh(): AbstractMesh {
  89027. return this._mesh;
  89028. }*/
  89029. /**
  89030. * Gets the body that holds this impostor. Either its own, or its parent.
  89031. */
  89032. get: function () {
  89033. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  89034. },
  89035. /**
  89036. * Set the physics body. Used mainly by the physics engine/plugin
  89037. */
  89038. set: function (physicsBody) {
  89039. if (this._physicsBody && this._physicsEngine) {
  89040. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  89041. }
  89042. this._physicsBody = physicsBody;
  89043. this.resetUpdateFlags();
  89044. },
  89045. enumerable: true,
  89046. configurable: true
  89047. });
  89048. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  89049. get: function () {
  89050. return !this._options.ignoreParent && this._parent ? this._parent : null;
  89051. },
  89052. set: function (value) {
  89053. this._parent = value;
  89054. },
  89055. enumerable: true,
  89056. configurable: true
  89057. });
  89058. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  89059. this._bodyUpdateRequired = false;
  89060. };
  89061. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  89062. if (this.object.getBoundingInfo) {
  89063. var q = this.object.rotationQuaternion;
  89064. //reset rotation
  89065. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  89066. //calculate the world matrix with no rotation
  89067. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  89068. var boundingInfo = this.object.getBoundingInfo();
  89069. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  89070. //bring back the rotation
  89071. this.object.rotationQuaternion = q;
  89072. //calculate the world matrix with the new rotation
  89073. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  89074. return size;
  89075. }
  89076. else {
  89077. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  89078. }
  89079. };
  89080. PhysicsImpostor.prototype.getObjectCenter = function () {
  89081. if (this.object.getBoundingInfo) {
  89082. var boundingInfo = this.object.getBoundingInfo();
  89083. return boundingInfo.boundingBox.centerWorld;
  89084. }
  89085. else {
  89086. return this.object.position;
  89087. }
  89088. };
  89089. /**
  89090. * Get a specific parametes from the options parameter.
  89091. */
  89092. PhysicsImpostor.prototype.getParam = function (paramName) {
  89093. return this._options[paramName];
  89094. };
  89095. /**
  89096. * Sets a specific parameter in the options given to the physics plugin
  89097. */
  89098. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  89099. this._options[paramName] = value;
  89100. this._bodyUpdateRequired = true;
  89101. };
  89102. /**
  89103. * Specifically change the body's mass option. Won't recreate the physics body object
  89104. */
  89105. PhysicsImpostor.prototype.setMass = function (mass) {
  89106. if (this.getParam("mass") !== mass) {
  89107. this.setParam("mass", mass);
  89108. }
  89109. if (this._physicsEngine) {
  89110. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  89111. }
  89112. };
  89113. PhysicsImpostor.prototype.getLinearVelocity = function () {
  89114. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  89115. };
  89116. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  89117. if (this._physicsEngine) {
  89118. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  89119. }
  89120. };
  89121. PhysicsImpostor.prototype.getAngularVelocity = function () {
  89122. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  89123. };
  89124. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  89125. if (this._physicsEngine) {
  89126. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  89127. }
  89128. };
  89129. /**
  89130. * Execute a function with the physics plugin native code.
  89131. * Provide a function the will have two variables - the world object and the physics body object.
  89132. */
  89133. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  89134. if (this._physicsEngine) {
  89135. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  89136. }
  89137. };
  89138. /**
  89139. * Register a function that will be executed before the physics world is stepping forward.
  89140. */
  89141. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  89142. this._onBeforePhysicsStepCallbacks.push(func);
  89143. };
  89144. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  89145. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  89146. if (index > -1) {
  89147. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  89148. }
  89149. else {
  89150. BABYLON.Tools.Warn("Function to remove was not found");
  89151. }
  89152. };
  89153. /**
  89154. * Register a function that will be executed after the physics step
  89155. */
  89156. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  89157. this._onAfterPhysicsStepCallbacks.push(func);
  89158. };
  89159. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  89160. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  89161. if (index > -1) {
  89162. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  89163. }
  89164. else {
  89165. BABYLON.Tools.Warn("Function to remove was not found");
  89166. }
  89167. };
  89168. /**
  89169. * register a function that will be executed when this impostor collides against a different body.
  89170. */
  89171. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  89172. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  89173. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  89174. };
  89175. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  89176. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  89177. var index = -1;
  89178. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  89179. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  89180. // chcek the arrays match
  89181. var sameList = cbDef.otherImpostors.every(function (impostor) {
  89182. return collidedAgainstList.indexOf(impostor) > -1;
  89183. });
  89184. if (sameList) {
  89185. index = idx;
  89186. }
  89187. return sameList;
  89188. }
  89189. return false;
  89190. });
  89191. if (found) {
  89192. this._onPhysicsCollideCallbacks.splice(index, 1);
  89193. }
  89194. else {
  89195. BABYLON.Tools.Warn("Function to remove was not found");
  89196. }
  89197. };
  89198. PhysicsImpostor.prototype.getParentsRotation = function () {
  89199. var parent = this.object.parent;
  89200. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  89201. while (parent) {
  89202. if (parent.rotationQuaternion) {
  89203. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  89204. }
  89205. else {
  89206. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  89207. }
  89208. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  89209. parent = parent.parent;
  89210. }
  89211. return this._tmpQuat;
  89212. };
  89213. /**
  89214. * Apply a force
  89215. */
  89216. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  89217. if (this._physicsEngine) {
  89218. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  89219. }
  89220. return this;
  89221. };
  89222. /**
  89223. * Apply an impulse
  89224. */
  89225. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  89226. if (this._physicsEngine) {
  89227. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  89228. }
  89229. return this;
  89230. };
  89231. /**
  89232. * A help function to create a joint.
  89233. */
  89234. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  89235. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  89236. this.addJoint(otherImpostor, joint);
  89237. return this;
  89238. };
  89239. /**
  89240. * Add a joint to this impostor with a different impostor.
  89241. */
  89242. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  89243. this._joints.push({
  89244. otherImpostor: otherImpostor,
  89245. joint: joint
  89246. });
  89247. if (this._physicsEngine) {
  89248. this._physicsEngine.addJoint(this, otherImpostor, joint);
  89249. }
  89250. return this;
  89251. };
  89252. /**
  89253. * Will keep this body still, in a sleep mode.
  89254. */
  89255. PhysicsImpostor.prototype.sleep = function () {
  89256. if (this._physicsEngine) {
  89257. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  89258. }
  89259. return this;
  89260. };
  89261. /**
  89262. * Wake the body up.
  89263. */
  89264. PhysicsImpostor.prototype.wakeUp = function () {
  89265. if (this._physicsEngine) {
  89266. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  89267. }
  89268. return this;
  89269. };
  89270. PhysicsImpostor.prototype.clone = function (newObject) {
  89271. if (!newObject)
  89272. return null;
  89273. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  89274. };
  89275. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  89276. var _this = this;
  89277. //no dispose if no physics engine is available.
  89278. if (!this._physicsEngine) {
  89279. return;
  89280. }
  89281. this._joints.forEach(function (j) {
  89282. if (_this._physicsEngine) {
  89283. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  89284. }
  89285. });
  89286. //dispose the physics body
  89287. this._physicsEngine.removeImpostor(this);
  89288. if (this.parent) {
  89289. this.parent.forceUpdate();
  89290. }
  89291. else {
  89292. /*this._object.getChildMeshes().forEach(function(mesh) {
  89293. if (mesh.physicsImpostor) {
  89294. if (disposeChildren) {
  89295. mesh.physicsImpostor.dispose();
  89296. mesh.physicsImpostor = null;
  89297. }
  89298. }
  89299. })*/
  89300. }
  89301. this._isDisposed = true;
  89302. };
  89303. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  89304. this._deltaPosition.copyFrom(position);
  89305. };
  89306. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  89307. if (!this._deltaRotation) {
  89308. this._deltaRotation = new BABYLON.Quaternion();
  89309. }
  89310. this._deltaRotation.copyFrom(rotation);
  89311. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  89312. };
  89313. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  89314. if (this._physicsEngine) {
  89315. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  89316. }
  89317. return this;
  89318. };
  89319. PhysicsImpostor.prototype.getRadius = function () {
  89320. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  89321. };
  89322. /**
  89323. * Sync a bone with this impostor
  89324. * @param bone The bone to sync to the impostor.
  89325. * @param boneMesh The mesh that the bone is influencing.
  89326. * @param jointPivot The pivot of the joint / bone in local space.
  89327. * @param distToJoint Optional distance from the impostor to the joint.
  89328. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  89329. */
  89330. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  89331. var tempVec = PhysicsImpostor._tmpVecs[0];
  89332. var mesh = this.object;
  89333. if (mesh.rotationQuaternion) {
  89334. if (adjustRotation) {
  89335. var tempQuat = PhysicsImpostor._tmpQuat;
  89336. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  89337. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  89338. }
  89339. else {
  89340. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  89341. }
  89342. }
  89343. tempVec.x = 0;
  89344. tempVec.y = 0;
  89345. tempVec.z = 0;
  89346. if (jointPivot) {
  89347. tempVec.x = jointPivot.x;
  89348. tempVec.y = jointPivot.y;
  89349. tempVec.z = jointPivot.z;
  89350. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  89351. if (distToJoint === undefined || distToJoint === null) {
  89352. distToJoint = jointPivot.length();
  89353. }
  89354. tempVec.x *= distToJoint;
  89355. tempVec.y *= distToJoint;
  89356. tempVec.z *= distToJoint;
  89357. }
  89358. if (bone.getParent()) {
  89359. tempVec.addInPlace(mesh.getAbsolutePosition());
  89360. bone.setAbsolutePosition(tempVec, boneMesh);
  89361. }
  89362. else {
  89363. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  89364. boneMesh.position.x -= tempVec.x;
  89365. boneMesh.position.y -= tempVec.y;
  89366. boneMesh.position.z -= tempVec.z;
  89367. }
  89368. };
  89369. /**
  89370. * Sync impostor to a bone
  89371. * @param bone The bone that the impostor will be synced to.
  89372. * @param boneMesh The mesh that the bone is influencing.
  89373. * @param jointPivot The pivot of the joint / bone in local space.
  89374. * @param distToJoint Optional distance from the impostor to the joint.
  89375. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  89376. * @param boneAxis Optional vector3 axis the bone is aligned with
  89377. */
  89378. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  89379. var mesh = this.object;
  89380. if (mesh.rotationQuaternion) {
  89381. if (adjustRotation) {
  89382. var tempQuat = PhysicsImpostor._tmpQuat;
  89383. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  89384. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  89385. }
  89386. else {
  89387. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  89388. }
  89389. }
  89390. var pos = PhysicsImpostor._tmpVecs[0];
  89391. var boneDir = PhysicsImpostor._tmpVecs[1];
  89392. if (!boneAxis) {
  89393. boneAxis = PhysicsImpostor._tmpVecs[2];
  89394. boneAxis.x = 0;
  89395. boneAxis.y = 1;
  89396. boneAxis.z = 0;
  89397. }
  89398. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  89399. bone.getAbsolutePositionToRef(boneMesh, pos);
  89400. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  89401. distToJoint = jointPivot.length();
  89402. }
  89403. if (distToJoint !== undefined && distToJoint !== null) {
  89404. pos.x += boneDir.x * distToJoint;
  89405. pos.y += boneDir.y * distToJoint;
  89406. pos.z += boneDir.z * distToJoint;
  89407. }
  89408. mesh.setAbsolutePosition(pos);
  89409. };
  89410. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  89411. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  89412. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  89413. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  89414. //Impostor types
  89415. PhysicsImpostor.NoImpostor = 0;
  89416. PhysicsImpostor.SphereImpostor = 1;
  89417. PhysicsImpostor.BoxImpostor = 2;
  89418. PhysicsImpostor.PlaneImpostor = 3;
  89419. PhysicsImpostor.MeshImpostor = 4;
  89420. PhysicsImpostor.CylinderImpostor = 7;
  89421. PhysicsImpostor.ParticleImpostor = 8;
  89422. PhysicsImpostor.HeightmapImpostor = 9;
  89423. return PhysicsImpostor;
  89424. }());
  89425. BABYLON.PhysicsImpostor = PhysicsImpostor;
  89426. })(BABYLON || (BABYLON = {}));
  89427. //# sourceMappingURL=babylon.physicsImpostor.js.map
  89428. var BABYLON;
  89429. (function (BABYLON) {
  89430. /**
  89431. * Class used to control physics engine
  89432. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  89433. */
  89434. var PhysicsEngine = /** @class */ (function () {
  89435. /**
  89436. * Creates a new Physics Engine
  89437. * @param gravity defines the gravity vector used by the simulation
  89438. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  89439. */
  89440. function PhysicsEngine(gravity, _physicsPlugin) {
  89441. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  89442. this._physicsPlugin = _physicsPlugin;
  89443. this._impostors = [];
  89444. this._joints = [];
  89445. if (!this._physicsPlugin.isSupported()) {
  89446. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  89447. + "Please make sure it is included.");
  89448. }
  89449. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  89450. this.setGravity(gravity);
  89451. this.setTimeStep();
  89452. }
  89453. /**
  89454. * Sets the gravity vector used by the simulation
  89455. * @param gravity defines the gravity vector to use
  89456. */
  89457. PhysicsEngine.prototype.setGravity = function (gravity) {
  89458. this.gravity = gravity;
  89459. this._physicsPlugin.setGravity(this.gravity);
  89460. };
  89461. /**
  89462. * Set the time step of the physics engine.
  89463. * Default is 1/60.
  89464. * To slow it down, enter 1/600 for example.
  89465. * To speed it up, 1/30
  89466. * @param newTimeStep defines the new timestep to apply to this world.
  89467. */
  89468. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  89469. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  89470. this._physicsPlugin.setTimeStep(newTimeStep);
  89471. };
  89472. /**
  89473. * Get the time step of the physics engine.
  89474. * @returns the current time step
  89475. */
  89476. PhysicsEngine.prototype.getTimeStep = function () {
  89477. return this._physicsPlugin.getTimeStep();
  89478. };
  89479. /**
  89480. * Release all resources
  89481. */
  89482. PhysicsEngine.prototype.dispose = function () {
  89483. this._impostors.forEach(function (impostor) {
  89484. impostor.dispose();
  89485. });
  89486. this._physicsPlugin.dispose();
  89487. };
  89488. /**
  89489. * Gets the name of the current physics plugin
  89490. * @returns the name of the plugin
  89491. */
  89492. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  89493. return this._physicsPlugin.name;
  89494. };
  89495. /**
  89496. * Adding a new impostor for the impostor tracking.
  89497. * This will be done by the impostor itself.
  89498. * @param impostor the impostor to add
  89499. */
  89500. PhysicsEngine.prototype.addImpostor = function (impostor) {
  89501. impostor.uniqueId = this._impostors.push(impostor);
  89502. //if no parent, generate the body
  89503. if (!impostor.parent) {
  89504. this._physicsPlugin.generatePhysicsBody(impostor);
  89505. }
  89506. };
  89507. /**
  89508. * Remove an impostor from the engine.
  89509. * This impostor and its mesh will not longer be updated by the physics engine.
  89510. * @param impostor the impostor to remove
  89511. */
  89512. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  89513. var index = this._impostors.indexOf(impostor);
  89514. if (index > -1) {
  89515. var removed = this._impostors.splice(index, 1);
  89516. //Is it needed?
  89517. if (removed.length) {
  89518. //this will also remove it from the world.
  89519. removed[0].physicsBody = null;
  89520. }
  89521. }
  89522. };
  89523. /**
  89524. * Add a joint to the physics engine
  89525. * @param mainImpostor defines the main impostor to which the joint is added.
  89526. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  89527. * @param joint defines the joint that will connect both impostors.
  89528. */
  89529. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  89530. var impostorJoint = {
  89531. mainImpostor: mainImpostor,
  89532. connectedImpostor: connectedImpostor,
  89533. joint: joint
  89534. };
  89535. joint.physicsPlugin = this._physicsPlugin;
  89536. this._joints.push(impostorJoint);
  89537. this._physicsPlugin.generateJoint(impostorJoint);
  89538. };
  89539. /**
  89540. * Removes a joint from the simulation
  89541. * @param mainImpostor defines the impostor used with the joint
  89542. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  89543. * @param joint defines the joint to remove
  89544. */
  89545. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  89546. var matchingJoints = this._joints.filter(function (impostorJoint) {
  89547. return (impostorJoint.connectedImpostor === connectedImpostor
  89548. && impostorJoint.joint === joint
  89549. && impostorJoint.mainImpostor === mainImpostor);
  89550. });
  89551. if (matchingJoints.length) {
  89552. this._physicsPlugin.removeJoint(matchingJoints[0]);
  89553. //TODO remove it from the list as well
  89554. }
  89555. };
  89556. /**
  89557. * Called by the scene. No need to call it.
  89558. * @param delta defines the timespam between frames
  89559. */
  89560. PhysicsEngine.prototype._step = function (delta) {
  89561. var _this = this;
  89562. //check if any mesh has no body / requires an update
  89563. this._impostors.forEach(function (impostor) {
  89564. if (impostor.isBodyInitRequired()) {
  89565. _this._physicsPlugin.generatePhysicsBody(impostor);
  89566. }
  89567. });
  89568. if (delta > 0.1) {
  89569. delta = 0.1;
  89570. }
  89571. else if (delta <= 0) {
  89572. delta = 1.0 / 60.0;
  89573. }
  89574. this._physicsPlugin.executeStep(delta, this._impostors);
  89575. };
  89576. /**
  89577. * Gets the current plugin used to run the simulation
  89578. * @returns current plugin
  89579. */
  89580. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  89581. return this._physicsPlugin;
  89582. };
  89583. /**
  89584. * Gets the list of physic impostors
  89585. * @returns an array of PhysicsImpostor
  89586. */
  89587. PhysicsEngine.prototype.getImpostors = function () {
  89588. return this._impostors;
  89589. };
  89590. /**
  89591. * Gets the impostor for a physics enabled object
  89592. * @param object defines the object impersonated by the impostor
  89593. * @returns the PhysicsImpostor or null if not found
  89594. */
  89595. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  89596. for (var i = 0; i < this._impostors.length; ++i) {
  89597. if (this._impostors[i].object === object) {
  89598. return this._impostors[i];
  89599. }
  89600. }
  89601. return null;
  89602. };
  89603. /**
  89604. * Gets the impostor for a physics body object
  89605. * @param body defines physics body used by the impostor
  89606. * @returns the PhysicsImpostor or null if not found
  89607. */
  89608. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  89609. for (var i = 0; i < this._impostors.length; ++i) {
  89610. if (this._impostors[i].physicsBody === body) {
  89611. return this._impostors[i];
  89612. }
  89613. }
  89614. return null;
  89615. };
  89616. /**
  89617. * Global value used to control the smallest number supported by the simulation
  89618. */
  89619. PhysicsEngine.Epsilon = 0.001;
  89620. return PhysicsEngine;
  89621. }());
  89622. BABYLON.PhysicsEngine = PhysicsEngine;
  89623. })(BABYLON || (BABYLON = {}));
  89624. //# sourceMappingURL=babylon.physicsEngine.js.map
  89625. var BABYLON;
  89626. (function (BABYLON) {
  89627. var PhysicsHelper = /** @class */ (function () {
  89628. function PhysicsHelper(scene) {
  89629. this._scene = scene;
  89630. this._physicsEngine = this._scene.getPhysicsEngine();
  89631. if (!this._physicsEngine) {
  89632. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  89633. }
  89634. }
  89635. /**
  89636. * @param {Vector3} origin the origin of the explosion
  89637. * @param {number} radius the explosion radius
  89638. * @param {number} strength the explosion strength
  89639. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89640. */
  89641. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  89642. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89643. if (!this._physicsEngine) {
  89644. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  89645. return null;
  89646. }
  89647. var impostors = this._physicsEngine.getImpostors();
  89648. if (impostors.length === 0) {
  89649. return null;
  89650. }
  89651. var event = new PhysicsRadialExplosionEvent(this._scene);
  89652. impostors.forEach(function (impostor) {
  89653. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89654. if (!impostorForceAndContactPoint) {
  89655. return;
  89656. }
  89657. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89658. });
  89659. event.dispose(false);
  89660. return event;
  89661. };
  89662. /**
  89663. * @param {Vector3} origin the origin of the explosion
  89664. * @param {number} radius the explosion radius
  89665. * @param {number} strength the explosion strength
  89666. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89667. */
  89668. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  89669. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89670. if (!this._physicsEngine) {
  89671. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89672. return null;
  89673. }
  89674. var impostors = this._physicsEngine.getImpostors();
  89675. if (impostors.length === 0) {
  89676. return null;
  89677. }
  89678. var event = new PhysicsRadialExplosionEvent(this._scene);
  89679. impostors.forEach(function (impostor) {
  89680. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89681. if (!impostorForceAndContactPoint) {
  89682. return;
  89683. }
  89684. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89685. });
  89686. event.dispose(false);
  89687. return event;
  89688. };
  89689. /**
  89690. * @param {Vector3} origin the origin of the explosion
  89691. * @param {number} radius the explosion radius
  89692. * @param {number} strength the explosion strength
  89693. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89694. */
  89695. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  89696. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89697. if (!this._physicsEngine) {
  89698. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89699. return null;
  89700. }
  89701. var impostors = this._physicsEngine.getImpostors();
  89702. if (impostors.length === 0) {
  89703. return null;
  89704. }
  89705. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  89706. event.dispose(false);
  89707. return event;
  89708. };
  89709. /**
  89710. * @param {Vector3} origin the origin of the updraft
  89711. * @param {number} radius the radius of the updraft
  89712. * @param {number} strength the strength of the updraft
  89713. * @param {number} height the height of the updraft
  89714. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  89715. */
  89716. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  89717. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  89718. if (!this._physicsEngine) {
  89719. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89720. return null;
  89721. }
  89722. if (this._physicsEngine.getImpostors().length === 0) {
  89723. return null;
  89724. }
  89725. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  89726. event.dispose(false);
  89727. return event;
  89728. };
  89729. /**
  89730. * @param {Vector3} origin the of the vortex
  89731. * @param {number} radius the radius of the vortex
  89732. * @param {number} strength the strength of the vortex
  89733. * @param {number} height the height of the vortex
  89734. */
  89735. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  89736. if (!this._physicsEngine) {
  89737. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89738. return null;
  89739. }
  89740. if (this._physicsEngine.getImpostors().length === 0) {
  89741. return null;
  89742. }
  89743. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  89744. event.dispose(false);
  89745. return event;
  89746. };
  89747. return PhysicsHelper;
  89748. }());
  89749. BABYLON.PhysicsHelper = PhysicsHelper;
  89750. /***** Radial explosion *****/
  89751. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  89752. function PhysicsRadialExplosionEvent(scene) {
  89753. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  89754. this._rays = [];
  89755. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  89756. this._scene = scene;
  89757. }
  89758. /**
  89759. * Returns the data related to the radial explosion event (sphere & rays).
  89760. * @returns {PhysicsRadialExplosionEventData}
  89761. */
  89762. PhysicsRadialExplosionEvent.prototype.getData = function () {
  89763. this._dataFetched = true;
  89764. return {
  89765. sphere: this._sphere,
  89766. rays: this._rays,
  89767. };
  89768. };
  89769. /**
  89770. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  89771. * @param impostor
  89772. * @param {Vector3} origin the origin of the explosion
  89773. * @param {number} radius the explosion radius
  89774. * @param {number} strength the explosion strength
  89775. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  89776. * @returns {Nullable<PhysicsForceAndContactPoint>}
  89777. */
  89778. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  89779. if (impostor.mass === 0) {
  89780. return null;
  89781. }
  89782. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  89783. return null;
  89784. }
  89785. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89786. return null;
  89787. }
  89788. var impostorObjectCenter = impostor.getObjectCenter();
  89789. var direction = impostorObjectCenter.subtract(origin);
  89790. var ray = new BABYLON.Ray(origin, direction, radius);
  89791. this._rays.push(ray);
  89792. var hit = ray.intersectsMesh(impostor.object);
  89793. var contactPoint = hit.pickedPoint;
  89794. if (!contactPoint) {
  89795. return null;
  89796. }
  89797. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  89798. if (distanceFromOrigin > radius) {
  89799. return null;
  89800. }
  89801. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  89802. ? strength
  89803. : strength * (1 - (distanceFromOrigin / radius));
  89804. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89805. return { force: force, contactPoint: contactPoint };
  89806. };
  89807. /**
  89808. * Disposes the sphere.
  89809. * @param {bolean} force
  89810. */
  89811. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  89812. var _this = this;
  89813. if (force === void 0) { force = true; }
  89814. if (force) {
  89815. this._sphere.dispose();
  89816. }
  89817. else {
  89818. setTimeout(function () {
  89819. if (!_this._dataFetched) {
  89820. _this._sphere.dispose();
  89821. }
  89822. }, 0);
  89823. }
  89824. };
  89825. /*** Helpers ***/
  89826. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  89827. if (!this._sphere) {
  89828. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  89829. this._sphere.isVisible = false;
  89830. }
  89831. };
  89832. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  89833. var impostorObject = impostor.object;
  89834. this._prepareSphere();
  89835. this._sphere.position = origin;
  89836. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  89837. this._sphere._updateBoundingInfo();
  89838. this._sphere.computeWorldMatrix(true);
  89839. return this._sphere.intersectsMesh(impostorObject, true);
  89840. };
  89841. return PhysicsRadialExplosionEvent;
  89842. }());
  89843. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  89844. /***** Gravitational Field *****/
  89845. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  89846. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  89847. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89848. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89849. this._physicsHelper = physicsHelper;
  89850. this._scene = scene;
  89851. this._origin = origin;
  89852. this._radius = radius;
  89853. this._strength = strength;
  89854. this._falloff = falloff;
  89855. this._tickCallback = this._tick.bind(this);
  89856. }
  89857. /**
  89858. * Returns the data related to the gravitational field event (sphere).
  89859. * @returns {PhysicsGravitationalFieldEventData}
  89860. */
  89861. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  89862. this._dataFetched = true;
  89863. return {
  89864. sphere: this._sphere,
  89865. };
  89866. };
  89867. /**
  89868. * Enables the gravitational field.
  89869. */
  89870. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  89871. this._tickCallback.call(this);
  89872. this._scene.registerBeforeRender(this._tickCallback);
  89873. };
  89874. /**
  89875. * Disables the gravitational field.
  89876. */
  89877. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  89878. this._scene.unregisterBeforeRender(this._tickCallback);
  89879. };
  89880. /**
  89881. * Disposes the sphere.
  89882. * @param {bolean} force
  89883. */
  89884. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  89885. var _this = this;
  89886. if (force === void 0) { force = true; }
  89887. if (force) {
  89888. this._sphere.dispose();
  89889. }
  89890. else {
  89891. setTimeout(function () {
  89892. if (!_this._dataFetched) {
  89893. _this._sphere.dispose();
  89894. }
  89895. }, 0);
  89896. }
  89897. };
  89898. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  89899. // Since the params won't change, we fetch the event only once
  89900. if (this._sphere) {
  89901. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89902. }
  89903. else {
  89904. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89905. if (radialExplosionEvent) {
  89906. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  89907. }
  89908. }
  89909. };
  89910. return PhysicsGravitationalFieldEvent;
  89911. }());
  89912. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  89913. /***** Updraft *****/
  89914. var PhysicsUpdraftEvent = /** @class */ (function () {
  89915. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  89916. this._scene = _scene;
  89917. this._origin = _origin;
  89918. this._radius = _radius;
  89919. this._strength = _strength;
  89920. this._height = _height;
  89921. this._updraftMode = _updraftMode;
  89922. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89923. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  89924. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89925. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89926. this._physicsEngine = this._scene.getPhysicsEngine();
  89927. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89928. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89929. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89930. this._originDirection = this._origin.subtract(this._originTop).normalize();
  89931. }
  89932. this._tickCallback = this._tick.bind(this);
  89933. }
  89934. /**
  89935. * Returns the data related to the updraft event (cylinder).
  89936. * @returns {PhysicsUpdraftEventData}
  89937. */
  89938. PhysicsUpdraftEvent.prototype.getData = function () {
  89939. this._dataFetched = true;
  89940. return {
  89941. cylinder: this._cylinder,
  89942. };
  89943. };
  89944. /**
  89945. * Enables the updraft.
  89946. */
  89947. PhysicsUpdraftEvent.prototype.enable = function () {
  89948. this._tickCallback.call(this);
  89949. this._scene.registerBeforeRender(this._tickCallback);
  89950. };
  89951. /**
  89952. * Disables the cortex.
  89953. */
  89954. PhysicsUpdraftEvent.prototype.disable = function () {
  89955. this._scene.unregisterBeforeRender(this._tickCallback);
  89956. };
  89957. /**
  89958. * Disposes the sphere.
  89959. * @param {bolean} force
  89960. */
  89961. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  89962. var _this = this;
  89963. if (force === void 0) { force = true; }
  89964. if (force) {
  89965. this._cylinder.dispose();
  89966. }
  89967. else {
  89968. setTimeout(function () {
  89969. if (!_this._dataFetched) {
  89970. _this._cylinder.dispose();
  89971. }
  89972. }, 0);
  89973. }
  89974. };
  89975. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89976. if (impostor.mass === 0) {
  89977. return null;
  89978. }
  89979. if (!this._intersectsWithCylinder(impostor)) {
  89980. return null;
  89981. }
  89982. var impostorObjectCenter = impostor.getObjectCenter();
  89983. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89984. var direction = this._originDirection;
  89985. }
  89986. else {
  89987. var direction = impostorObjectCenter.subtract(this._originTop);
  89988. }
  89989. var multiplier = this._strength * -1;
  89990. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89991. return { force: force, contactPoint: impostorObjectCenter };
  89992. };
  89993. PhysicsUpdraftEvent.prototype._tick = function () {
  89994. var _this = this;
  89995. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89996. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89997. if (!impostorForceAndContactPoint) {
  89998. return;
  89999. }
  90000. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  90001. });
  90002. };
  90003. /*** Helpers ***/
  90004. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  90005. if (!this._cylinder) {
  90006. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  90007. height: this._height,
  90008. diameter: this._radius * 2,
  90009. }, this._scene);
  90010. this._cylinder.isVisible = false;
  90011. }
  90012. };
  90013. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  90014. var impostorObject = impostor.object;
  90015. this._prepareCylinder();
  90016. this._cylinder.position = this._cylinderPosition;
  90017. return this._cylinder.intersectsMesh(impostorObject, true);
  90018. };
  90019. return PhysicsUpdraftEvent;
  90020. }());
  90021. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  90022. /***** Vortex *****/
  90023. var PhysicsVortexEvent = /** @class */ (function () {
  90024. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  90025. this._scene = _scene;
  90026. this._origin = _origin;
  90027. this._radius = _radius;
  90028. this._strength = _strength;
  90029. this._height = _height;
  90030. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  90031. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  90032. this._updraftMultiplier = 0.02;
  90033. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  90034. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  90035. this._physicsEngine = this._scene.getPhysicsEngine();
  90036. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  90037. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  90038. this._tickCallback = this._tick.bind(this);
  90039. }
  90040. /**
  90041. * Returns the data related to the vortex event (cylinder).
  90042. * @returns {PhysicsVortexEventData}
  90043. */
  90044. PhysicsVortexEvent.prototype.getData = function () {
  90045. this._dataFetched = true;
  90046. return {
  90047. cylinder: this._cylinder,
  90048. };
  90049. };
  90050. /**
  90051. * Enables the vortex.
  90052. */
  90053. PhysicsVortexEvent.prototype.enable = function () {
  90054. this._tickCallback.call(this);
  90055. this._scene.registerBeforeRender(this._tickCallback);
  90056. };
  90057. /**
  90058. * Disables the cortex.
  90059. */
  90060. PhysicsVortexEvent.prototype.disable = function () {
  90061. this._scene.unregisterBeforeRender(this._tickCallback);
  90062. };
  90063. /**
  90064. * Disposes the sphere.
  90065. * @param {bolean} force
  90066. */
  90067. PhysicsVortexEvent.prototype.dispose = function (force) {
  90068. var _this = this;
  90069. if (force === void 0) { force = true; }
  90070. if (force) {
  90071. this._cylinder.dispose();
  90072. }
  90073. else {
  90074. setTimeout(function () {
  90075. if (!_this._dataFetched) {
  90076. _this._cylinder.dispose();
  90077. }
  90078. }, 0);
  90079. }
  90080. };
  90081. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  90082. if (impostor.mass === 0) {
  90083. return null;
  90084. }
  90085. if (!this._intersectsWithCylinder(impostor)) {
  90086. return null;
  90087. }
  90088. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  90089. return null;
  90090. }
  90091. var impostorObjectCenter = impostor.getObjectCenter();
  90092. 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)
  90093. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  90094. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  90095. var hit = ray.intersectsMesh(impostor.object);
  90096. var contactPoint = hit.pickedPoint;
  90097. if (!contactPoint) {
  90098. return null;
  90099. }
  90100. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  90101. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  90102. var directionToOrigin = contactPoint.normalize();
  90103. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  90104. directionToOrigin = directionToOrigin.negate();
  90105. }
  90106. // TODO: find a more physically based solution
  90107. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  90108. var forceX = directionToOrigin.x * this._strength / 8;
  90109. var forceY = directionToOrigin.y * this._updraftMultiplier;
  90110. var forceZ = directionToOrigin.z * this._strength / 8;
  90111. }
  90112. else {
  90113. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  90114. var forceY = this._originTop.y * this._updraftMultiplier;
  90115. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  90116. }
  90117. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  90118. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  90119. return { force: force, contactPoint: impostorObjectCenter };
  90120. };
  90121. PhysicsVortexEvent.prototype._tick = function () {
  90122. var _this = this;
  90123. this._physicsEngine.getImpostors().forEach(function (impostor) {
  90124. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  90125. if (!impostorForceAndContactPoint) {
  90126. return;
  90127. }
  90128. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  90129. });
  90130. };
  90131. /*** Helpers ***/
  90132. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  90133. if (!this._cylinder) {
  90134. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  90135. height: this._height,
  90136. diameter: this._radius * 2,
  90137. }, this._scene);
  90138. this._cylinder.isVisible = false;
  90139. }
  90140. };
  90141. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  90142. var impostorObject = impostor.object;
  90143. this._prepareCylinder();
  90144. this._cylinder.position = this._cylinderPosition;
  90145. return this._cylinder.intersectsMesh(impostorObject, true);
  90146. };
  90147. return PhysicsVortexEvent;
  90148. }());
  90149. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  90150. /***** Enums *****/
  90151. /**
  90152. * The strenght of the force in correspondence to the distance of the affected object
  90153. */
  90154. var PhysicsRadialImpulseFalloff;
  90155. (function (PhysicsRadialImpulseFalloff) {
  90156. /** Defines that impulse is constant in strength across it's whole radius */
  90157. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  90158. /** DEfines that impulse gets weaker if it's further from the origin */
  90159. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  90160. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  90161. /**
  90162. * The strenght of the force in correspondence to the distance of the affected object
  90163. */
  90164. var PhysicsUpdraftMode;
  90165. (function (PhysicsUpdraftMode) {
  90166. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  90167. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  90168. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  90169. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  90170. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  90171. })(BABYLON || (BABYLON = {}));
  90172. //# sourceMappingURL=babylon.physicsHelper.js.map
  90173. var BABYLON;
  90174. (function (BABYLON) {
  90175. var CannonJSPlugin = /** @class */ (function () {
  90176. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  90177. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  90178. if (iterations === void 0) { iterations = 10; }
  90179. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  90180. this.name = "CannonJSPlugin";
  90181. this._physicsMaterials = new Array();
  90182. this._fixedTimeStep = 1 / 60;
  90183. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  90184. this.BJSCANNON = CANNON;
  90185. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  90186. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  90187. this._tmpPosition = BABYLON.Vector3.Zero();
  90188. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  90189. this._tmpUnityRotation = new BABYLON.Quaternion();
  90190. if (!this.isSupported()) {
  90191. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  90192. return;
  90193. }
  90194. this._extendNamespace();
  90195. this.world = new this.BJSCANNON.World();
  90196. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  90197. this.world.solver.iterations = iterations;
  90198. }
  90199. CannonJSPlugin.prototype.setGravity = function (gravity) {
  90200. this.world.gravity.copy(gravity);
  90201. };
  90202. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  90203. this._fixedTimeStep = timeStep;
  90204. };
  90205. CannonJSPlugin.prototype.getTimeStep = function () {
  90206. return this._fixedTimeStep;
  90207. };
  90208. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  90209. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  90210. };
  90211. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  90212. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  90213. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  90214. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  90215. };
  90216. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  90217. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  90218. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  90219. impostor.physicsBody.applyForce(impulse, worldPoint);
  90220. };
  90221. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  90222. //parent-child relationship. Does this impostor has a parent impostor?
  90223. if (impostor.parent) {
  90224. if (impostor.physicsBody) {
  90225. this.removePhysicsBody(impostor);
  90226. //TODO is that needed?
  90227. impostor.forceUpdate();
  90228. }
  90229. return;
  90230. }
  90231. //should a new body be created for this impostor?
  90232. if (impostor.isBodyInitRequired()) {
  90233. var shape = this._createShape(impostor);
  90234. //unregister events, if body is being changed
  90235. var oldBody = impostor.physicsBody;
  90236. if (oldBody) {
  90237. this.removePhysicsBody(impostor);
  90238. }
  90239. //create the body and material
  90240. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  90241. var bodyCreationObject = {
  90242. mass: impostor.getParam("mass"),
  90243. material: material
  90244. };
  90245. // A simple extend, in case native options were used.
  90246. var nativeOptions = impostor.getParam("nativeOptions");
  90247. for (var key in nativeOptions) {
  90248. if (nativeOptions.hasOwnProperty(key)) {
  90249. bodyCreationObject[key] = nativeOptions[key];
  90250. }
  90251. }
  90252. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  90253. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  90254. this.world.addEventListener("preStep", impostor.beforeStep);
  90255. this.world.addEventListener("postStep", impostor.afterStep);
  90256. impostor.physicsBody.addShape(shape);
  90257. this.world.add(impostor.physicsBody);
  90258. //try to keep the body moving in the right direction by taking old properties.
  90259. //Should be tested!
  90260. if (oldBody) {
  90261. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  90262. impostor.physicsBody[param].copy(oldBody[param]);
  90263. });
  90264. }
  90265. this._processChildMeshes(impostor);
  90266. }
  90267. //now update the body's transformation
  90268. this._updatePhysicsBodyTransformation(impostor);
  90269. };
  90270. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  90271. var _this = this;
  90272. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  90273. var currentRotation = mainImpostor.object.rotationQuaternion;
  90274. if (meshChildren.length) {
  90275. var processMesh = function (localPosition, mesh) {
  90276. if (!currentRotation || !mesh.rotationQuaternion) {
  90277. return;
  90278. }
  90279. var childImpostor = mesh.getPhysicsImpostor();
  90280. if (childImpostor) {
  90281. var parent = childImpostor.parent;
  90282. if (parent !== mainImpostor) {
  90283. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  90284. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  90285. if (childImpostor.physicsBody) {
  90286. _this.removePhysicsBody(childImpostor);
  90287. childImpostor.physicsBody = null;
  90288. }
  90289. childImpostor.parent = mainImpostor;
  90290. childImpostor.resetUpdateFlags();
  90291. 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));
  90292. //Add the mass of the children.
  90293. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  90294. }
  90295. }
  90296. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  90297. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  90298. };
  90299. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  90300. }
  90301. };
  90302. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  90303. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  90304. this.world.removeEventListener("preStep", impostor.beforeStep);
  90305. this.world.removeEventListener("postStep", impostor.afterStep);
  90306. this.world.remove(impostor.physicsBody);
  90307. };
  90308. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  90309. var mainBody = impostorJoint.mainImpostor.physicsBody;
  90310. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  90311. if (!mainBody || !connectedBody) {
  90312. return;
  90313. }
  90314. var constraint;
  90315. var jointData = impostorJoint.joint.jointData;
  90316. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  90317. var constraintData = {
  90318. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  90319. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  90320. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  90321. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  90322. maxForce: jointData.nativeParams.maxForce,
  90323. collideConnected: !!jointData.collision
  90324. };
  90325. switch (impostorJoint.joint.type) {
  90326. case BABYLON.PhysicsJoint.HingeJoint:
  90327. case BABYLON.PhysicsJoint.Hinge2Joint:
  90328. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  90329. break;
  90330. case BABYLON.PhysicsJoint.DistanceJoint:
  90331. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  90332. break;
  90333. case BABYLON.PhysicsJoint.SpringJoint:
  90334. var springData = jointData;
  90335. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  90336. restLength: springData.length,
  90337. stiffness: springData.stiffness,
  90338. damping: springData.damping,
  90339. localAnchorA: constraintData.pivotA,
  90340. localAnchorB: constraintData.pivotB
  90341. });
  90342. break;
  90343. case BABYLON.PhysicsJoint.LockJoint:
  90344. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  90345. break;
  90346. case BABYLON.PhysicsJoint.PointToPointJoint:
  90347. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  90348. default:
  90349. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  90350. break;
  90351. }
  90352. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  90353. constraint.collideConnected = !!jointData.collision;
  90354. impostorJoint.joint.physicsJoint = constraint;
  90355. //don't add spring as constraint, as it is not one.
  90356. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  90357. this.world.addConstraint(constraint);
  90358. }
  90359. else {
  90360. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  90361. constraint.applyForce();
  90362. };
  90363. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  90364. }
  90365. };
  90366. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  90367. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  90368. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  90369. }
  90370. else {
  90371. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  90372. }
  90373. };
  90374. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  90375. var index;
  90376. var mat;
  90377. for (index = 0; index < this._physicsMaterials.length; index++) {
  90378. mat = this._physicsMaterials[index];
  90379. if (mat.friction === friction && mat.restitution === restitution) {
  90380. return mat;
  90381. }
  90382. }
  90383. var currentMat = new this.BJSCANNON.Material(name);
  90384. currentMat.friction = friction;
  90385. currentMat.restitution = restitution;
  90386. this._physicsMaterials.push(currentMat);
  90387. return currentMat;
  90388. };
  90389. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  90390. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  90391. };
  90392. CannonJSPlugin.prototype._createShape = function (impostor) {
  90393. var object = impostor.object;
  90394. var returnValue;
  90395. var extendSize = impostor.getObjectExtendSize();
  90396. switch (impostor.type) {
  90397. case BABYLON.PhysicsImpostor.SphereImpostor:
  90398. var radiusX = extendSize.x;
  90399. var radiusY = extendSize.y;
  90400. var radiusZ = extendSize.z;
  90401. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  90402. break;
  90403. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  90404. case BABYLON.PhysicsImpostor.CylinderImpostor:
  90405. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  90406. break;
  90407. case BABYLON.PhysicsImpostor.BoxImpostor:
  90408. var box = extendSize.scale(0.5);
  90409. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  90410. break;
  90411. case BABYLON.PhysicsImpostor.PlaneImpostor:
  90412. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  90413. returnValue = new this.BJSCANNON.Plane();
  90414. break;
  90415. case BABYLON.PhysicsImpostor.MeshImpostor:
  90416. // should transform the vertex data to world coordinates!!
  90417. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  90418. var rawFaces = object.getIndices ? object.getIndices() : [];
  90419. if (!rawVerts)
  90420. return;
  90421. // get only scale! so the object could transform correctly.
  90422. var oldPosition = object.position.clone();
  90423. var oldRotation = object.rotation && object.rotation.clone();
  90424. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  90425. object.position.copyFromFloats(0, 0, 0);
  90426. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  90427. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  90428. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  90429. var transform = object.computeWorldMatrix(true);
  90430. // convert rawVerts to object space
  90431. var temp = new Array();
  90432. var index;
  90433. for (index = 0; index < rawVerts.length; index += 3) {
  90434. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  90435. }
  90436. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  90437. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  90438. //now set back the transformation!
  90439. object.position.copyFrom(oldPosition);
  90440. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  90441. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  90442. break;
  90443. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  90444. var oldPosition2 = object.position.clone();
  90445. var oldRotation2 = object.rotation && object.rotation.clone();
  90446. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  90447. object.position.copyFromFloats(0, 0, 0);
  90448. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  90449. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  90450. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  90451. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  90452. returnValue = this._createHeightmap(object);
  90453. object.position.copyFrom(oldPosition2);
  90454. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  90455. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  90456. object.computeWorldMatrix(true);
  90457. break;
  90458. case BABYLON.PhysicsImpostor.ParticleImpostor:
  90459. returnValue = new this.BJSCANNON.Particle();
  90460. break;
  90461. }
  90462. return returnValue;
  90463. };
  90464. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  90465. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90466. var transform = object.computeWorldMatrix(true);
  90467. // convert rawVerts to object space
  90468. var temp = new Array();
  90469. var index;
  90470. for (index = 0; index < pos.length; index += 3) {
  90471. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  90472. }
  90473. pos = temp;
  90474. var matrix = new Array();
  90475. //For now pointDepth will not be used and will be automatically calculated.
  90476. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  90477. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  90478. var boundingInfo = object.getBoundingInfo();
  90479. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  90480. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  90481. var elementSize = dim * 2 / arraySize;
  90482. for (var i = 0; i < pos.length; i = i + 3) {
  90483. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  90484. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  90485. var y = -pos[i + 2] + minY;
  90486. if (!matrix[x]) {
  90487. matrix[x] = [];
  90488. }
  90489. if (!matrix[x][z]) {
  90490. matrix[x][z] = y;
  90491. }
  90492. matrix[x][z] = Math.max(y, matrix[x][z]);
  90493. }
  90494. for (var x = 0; x <= arraySize; ++x) {
  90495. if (!matrix[x]) {
  90496. var loc = 1;
  90497. while (!matrix[(x + loc) % arraySize]) {
  90498. loc++;
  90499. }
  90500. matrix[x] = matrix[(x + loc) % arraySize].slice();
  90501. //console.log("missing x", x);
  90502. }
  90503. for (var z = 0; z <= arraySize; ++z) {
  90504. if (!matrix[x][z]) {
  90505. var loc = 1;
  90506. var newValue;
  90507. while (newValue === undefined) {
  90508. newValue = matrix[x][(z + loc++) % arraySize];
  90509. }
  90510. matrix[x][z] = newValue;
  90511. }
  90512. }
  90513. }
  90514. var shape = new this.BJSCANNON.Heightfield(matrix, {
  90515. elementSize: elementSize
  90516. });
  90517. //For future reference, needed for body transformation
  90518. shape.minY = minY;
  90519. return shape;
  90520. };
  90521. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  90522. var object = impostor.object;
  90523. //make sure it is updated...
  90524. object.computeWorldMatrix && object.computeWorldMatrix(true);
  90525. // The delta between the mesh position and the mesh bounding box center
  90526. var bInfo = object.getBoundingInfo();
  90527. if (!bInfo)
  90528. return;
  90529. var center = impostor.getObjectCenter();
  90530. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  90531. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  90532. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  90533. this._tmpPosition.copyFrom(center);
  90534. var quaternion = object.rotationQuaternion;
  90535. if (!quaternion) {
  90536. return;
  90537. }
  90538. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  90539. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  90540. //-90 DEG in X, precalculated
  90541. quaternion = quaternion.multiply(this._minus90X);
  90542. //Invert! (Precalculated, 90 deg in X)
  90543. //No need to clone. this will never change.
  90544. impostor.setDeltaRotation(this._plus90X);
  90545. }
  90546. //If it is a heightfield, if should be centered.
  90547. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  90548. var mesh = object;
  90549. var boundingInfo = mesh.getBoundingInfo();
  90550. //calculate the correct body position:
  90551. var rotationQuaternion = mesh.rotationQuaternion;
  90552. mesh.rotationQuaternion = this._tmpUnityRotation;
  90553. mesh.computeWorldMatrix(true);
  90554. //get original center with no rotation
  90555. var c = center.clone();
  90556. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  90557. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  90558. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  90559. mesh.setPreTransformMatrix(p);
  90560. mesh.computeWorldMatrix(true);
  90561. //calculate the translation
  90562. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  90563. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  90564. //add it inverted to the delta
  90565. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  90566. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  90567. //rotation is back
  90568. mesh.rotationQuaternion = rotationQuaternion;
  90569. mesh.setPreTransformMatrix(oldPivot);
  90570. mesh.computeWorldMatrix(true);
  90571. }
  90572. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  90573. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  90574. //this._tmpPosition.copyFrom(object.position);
  90575. }
  90576. impostor.setDeltaPosition(this._tmpDeltaPosition);
  90577. //Now update the impostor object
  90578. impostor.physicsBody.position.copy(this._tmpPosition);
  90579. impostor.physicsBody.quaternion.copy(quaternion);
  90580. };
  90581. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  90582. impostor.object.position.copyFrom(impostor.physicsBody.position);
  90583. if (impostor.object.rotationQuaternion) {
  90584. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  90585. }
  90586. };
  90587. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  90588. impostor.physicsBody.position.copy(newPosition);
  90589. impostor.physicsBody.quaternion.copy(newRotation);
  90590. };
  90591. CannonJSPlugin.prototype.isSupported = function () {
  90592. return this.BJSCANNON !== undefined;
  90593. };
  90594. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  90595. impostor.physicsBody.velocity.copy(velocity);
  90596. };
  90597. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  90598. impostor.physicsBody.angularVelocity.copy(velocity);
  90599. };
  90600. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  90601. var v = impostor.physicsBody.velocity;
  90602. if (!v) {
  90603. return null;
  90604. }
  90605. return new BABYLON.Vector3(v.x, v.y, v.z);
  90606. };
  90607. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  90608. var v = impostor.physicsBody.angularVelocity;
  90609. if (!v) {
  90610. return null;
  90611. }
  90612. return new BABYLON.Vector3(v.x, v.y, v.z);
  90613. };
  90614. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  90615. impostor.physicsBody.mass = mass;
  90616. impostor.physicsBody.updateMassProperties();
  90617. };
  90618. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  90619. return impostor.physicsBody.mass;
  90620. };
  90621. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  90622. return impostor.physicsBody.material.friction;
  90623. };
  90624. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  90625. impostor.physicsBody.material.friction = friction;
  90626. };
  90627. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  90628. return impostor.physicsBody.material.restitution;
  90629. };
  90630. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  90631. impostor.physicsBody.material.restitution = restitution;
  90632. };
  90633. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  90634. impostor.physicsBody.sleep();
  90635. };
  90636. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  90637. impostor.physicsBody.wakeUp();
  90638. };
  90639. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  90640. joint.physicsJoint.distance = maxDistance;
  90641. };
  90642. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  90643. // if (!motorIndex) {
  90644. // joint.physicsJoint.enableMotor();
  90645. // }
  90646. // }
  90647. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  90648. // if (!motorIndex) {
  90649. // joint.physicsJoint.disableMotor();
  90650. // }
  90651. // }
  90652. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  90653. if (!motorIndex) {
  90654. joint.physicsJoint.enableMotor();
  90655. joint.physicsJoint.setMotorSpeed(speed);
  90656. if (maxForce) {
  90657. this.setLimit(joint, maxForce);
  90658. }
  90659. }
  90660. };
  90661. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  90662. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  90663. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  90664. };
  90665. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90666. var body = impostor.physicsBody;
  90667. mesh.position.x = body.position.x;
  90668. mesh.position.y = body.position.y;
  90669. mesh.position.z = body.position.z;
  90670. if (mesh.rotationQuaternion) {
  90671. mesh.rotationQuaternion.x = body.quaternion.x;
  90672. mesh.rotationQuaternion.y = body.quaternion.y;
  90673. mesh.rotationQuaternion.z = body.quaternion.z;
  90674. mesh.rotationQuaternion.w = body.quaternion.w;
  90675. }
  90676. };
  90677. CannonJSPlugin.prototype.getRadius = function (impostor) {
  90678. var shape = impostor.physicsBody.shapes[0];
  90679. return shape.boundingSphereRadius;
  90680. };
  90681. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90682. var shape = impostor.physicsBody.shapes[0];
  90683. result.x = shape.halfExtents.x * 2;
  90684. result.y = shape.halfExtents.y * 2;
  90685. result.z = shape.halfExtents.z * 2;
  90686. };
  90687. CannonJSPlugin.prototype.dispose = function () {
  90688. };
  90689. CannonJSPlugin.prototype._extendNamespace = function () {
  90690. //this will force cannon to execute at least one step when using interpolation
  90691. var step_tmp1 = new this.BJSCANNON.Vec3();
  90692. var Engine = this.BJSCANNON;
  90693. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  90694. maxSubSteps = maxSubSteps || 10;
  90695. timeSinceLastCalled = timeSinceLastCalled || 0;
  90696. if (timeSinceLastCalled === 0) {
  90697. this.internalStep(dt);
  90698. this.time += dt;
  90699. }
  90700. else {
  90701. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  90702. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  90703. var t0 = performance.now();
  90704. for (var i = 0; i !== internalSteps; i++) {
  90705. this.internalStep(dt);
  90706. if (performance.now() - t0 > dt * 1000) {
  90707. break;
  90708. }
  90709. }
  90710. this.time += timeSinceLastCalled;
  90711. var h = this.time % dt;
  90712. var h_div_dt = h / dt;
  90713. var interpvelo = step_tmp1;
  90714. var bodies = this.bodies;
  90715. for (var j = 0; j !== bodies.length; j++) {
  90716. var b = bodies[j];
  90717. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  90718. b.position.vsub(b.previousPosition, interpvelo);
  90719. interpvelo.scale(h_div_dt, interpvelo);
  90720. b.position.vadd(interpvelo, b.interpolatedPosition);
  90721. }
  90722. else {
  90723. b.interpolatedPosition.copy(b.position);
  90724. b.interpolatedQuaternion.copy(b.quaternion);
  90725. }
  90726. }
  90727. }
  90728. };
  90729. };
  90730. return CannonJSPlugin;
  90731. }());
  90732. BABYLON.CannonJSPlugin = CannonJSPlugin;
  90733. })(BABYLON || (BABYLON = {}));
  90734. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  90735. var BABYLON;
  90736. (function (BABYLON) {
  90737. var OimoJSPlugin = /** @class */ (function () {
  90738. function OimoJSPlugin(iterations) {
  90739. this.name = "OimoJSPlugin";
  90740. this._tmpImpostorsArray = [];
  90741. this._tmpPositionVector = BABYLON.Vector3.Zero();
  90742. this.BJSOIMO = OIMO;
  90743. this.world = new this.BJSOIMO.World({
  90744. iterations: iterations
  90745. });
  90746. this.world.clear();
  90747. }
  90748. OimoJSPlugin.prototype.setGravity = function (gravity) {
  90749. this.world.gravity.copy(gravity);
  90750. };
  90751. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  90752. this.world.timeStep = timeStep;
  90753. };
  90754. OimoJSPlugin.prototype.getTimeStep = function () {
  90755. return this.world.timeStep;
  90756. };
  90757. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  90758. var _this = this;
  90759. impostors.forEach(function (impostor) {
  90760. impostor.beforeStep();
  90761. });
  90762. this.world.step();
  90763. impostors.forEach(function (impostor) {
  90764. impostor.afterStep();
  90765. //update the ordered impostors array
  90766. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  90767. });
  90768. //check for collisions
  90769. var contact = this.world.contacts;
  90770. while (contact !== null) {
  90771. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  90772. contact = contact.next;
  90773. continue;
  90774. }
  90775. //is this body colliding with any other? get the impostor
  90776. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  90777. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  90778. if (!mainImpostor || !collidingImpostor) {
  90779. contact = contact.next;
  90780. continue;
  90781. }
  90782. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  90783. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  90784. contact = contact.next;
  90785. }
  90786. };
  90787. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  90788. var mass = impostor.physicsBody.mass;
  90789. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  90790. };
  90791. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  90792. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  90793. this.applyImpulse(impostor, force, contactPoint);
  90794. };
  90795. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  90796. var _this = this;
  90797. //parent-child relationship. Does this impostor has a parent impostor?
  90798. if (impostor.parent) {
  90799. if (impostor.physicsBody) {
  90800. this.removePhysicsBody(impostor);
  90801. //TODO is that needed?
  90802. impostor.forceUpdate();
  90803. }
  90804. return;
  90805. }
  90806. if (impostor.isBodyInitRequired()) {
  90807. var bodyConfig = {
  90808. name: impostor.uniqueId,
  90809. //Oimo must have mass, also for static objects.
  90810. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  90811. size: [],
  90812. type: [],
  90813. pos: [],
  90814. posShape: [],
  90815. rot: [],
  90816. rotShape: [],
  90817. move: impostor.getParam("mass") !== 0,
  90818. density: impostor.getParam("mass"),
  90819. friction: impostor.getParam("friction"),
  90820. restitution: impostor.getParam("restitution"),
  90821. //Supporting older versions of Oimo
  90822. world: this.world
  90823. };
  90824. var impostors = [impostor];
  90825. var addToArray = function (parent) {
  90826. if (!parent.getChildMeshes)
  90827. return;
  90828. parent.getChildMeshes().forEach(function (m) {
  90829. if (m.physicsImpostor) {
  90830. impostors.push(m.physicsImpostor);
  90831. //m.physicsImpostor._init();
  90832. }
  90833. });
  90834. };
  90835. addToArray(impostor.object);
  90836. var checkWithEpsilon_1 = function (value) {
  90837. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  90838. };
  90839. var globalQuaternion_1 = new BABYLON.Quaternion();
  90840. impostors.forEach(function (i) {
  90841. if (!i.object.rotationQuaternion) {
  90842. return;
  90843. }
  90844. //get the correct bounding box
  90845. var oldQuaternion = i.object.rotationQuaternion;
  90846. globalQuaternion_1 = oldQuaternion.clone();
  90847. var rot = oldQuaternion.toEulerAngles();
  90848. var extendSize = i.getObjectExtendSize();
  90849. var radToDeg = 57.295779513082320876;
  90850. if (i === impostor) {
  90851. var center = impostor.getObjectCenter();
  90852. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  90853. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  90854. //Can also use Array.prototype.push.apply
  90855. bodyConfig.pos.push(center.x);
  90856. bodyConfig.pos.push(center.y);
  90857. bodyConfig.pos.push(center.z);
  90858. bodyConfig.posShape.push(0, 0, 0);
  90859. //tmp solution
  90860. bodyConfig.rot.push(0);
  90861. bodyConfig.rot.push(0);
  90862. bodyConfig.rot.push(0);
  90863. bodyConfig.rotShape.push(0, 0, 0);
  90864. }
  90865. else {
  90866. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  90867. bodyConfig.posShape.push(localPosition.x);
  90868. bodyConfig.posShape.push(localPosition.y);
  90869. bodyConfig.posShape.push(localPosition.z);
  90870. bodyConfig.pos.push(0, 0, 0);
  90871. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  90872. bodyConfig.rot.push(0);
  90873. bodyConfig.rot.push(0);
  90874. bodyConfig.rot.push(0);
  90875. bodyConfig.rotShape.push(rot.x * radToDeg);
  90876. bodyConfig.rotShape.push(rot.y * radToDeg);
  90877. bodyConfig.rotShape.push(rot.z * radToDeg);
  90878. }
  90879. // register mesh
  90880. switch (i.type) {
  90881. case BABYLON.PhysicsImpostor.ParticleImpostor:
  90882. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  90883. case BABYLON.PhysicsImpostor.SphereImpostor:
  90884. var radiusX = extendSize.x;
  90885. var radiusY = extendSize.y;
  90886. var radiusZ = extendSize.z;
  90887. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  90888. bodyConfig.type.push('sphere');
  90889. //due to the way oimo works with compounds, add 3 times
  90890. bodyConfig.size.push(size);
  90891. bodyConfig.size.push(size);
  90892. bodyConfig.size.push(size);
  90893. break;
  90894. case BABYLON.PhysicsImpostor.CylinderImpostor:
  90895. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  90896. var sizeY = checkWithEpsilon_1(extendSize.y);
  90897. bodyConfig.type.push('cylinder');
  90898. bodyConfig.size.push(sizeX);
  90899. bodyConfig.size.push(sizeY);
  90900. //due to the way oimo works with compounds, add one more value.
  90901. bodyConfig.size.push(sizeY);
  90902. break;
  90903. case BABYLON.PhysicsImpostor.PlaneImpostor:
  90904. case BABYLON.PhysicsImpostor.BoxImpostor:
  90905. default:
  90906. var sizeX = checkWithEpsilon_1(extendSize.x);
  90907. var sizeY = checkWithEpsilon_1(extendSize.y);
  90908. var sizeZ = checkWithEpsilon_1(extendSize.z);
  90909. bodyConfig.type.push('box');
  90910. //if (i === impostor) {
  90911. bodyConfig.size.push(sizeX);
  90912. bodyConfig.size.push(sizeY);
  90913. bodyConfig.size.push(sizeZ);
  90914. //} else {
  90915. // bodyConfig.size.push(0,0,0);
  90916. //}
  90917. break;
  90918. }
  90919. //actually not needed, but hey...
  90920. i.object.rotationQuaternion = oldQuaternion;
  90921. });
  90922. impostor.physicsBody = this.world.add(bodyConfig);
  90923. // set the quaternion, ignoring the previously defined (euler) rotation
  90924. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  90925. // update with delta 0, so the body will reveive the new rotation.
  90926. impostor.physicsBody.updatePosition(0);
  90927. }
  90928. else {
  90929. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  90930. }
  90931. impostor.setDeltaPosition(this._tmpPositionVector);
  90932. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  90933. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  90934. };
  90935. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  90936. //impostor.physicsBody.dispose();
  90937. //Same as : (older oimo versions)
  90938. this.world.removeRigidBody(impostor.physicsBody);
  90939. };
  90940. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  90941. var mainBody = impostorJoint.mainImpostor.physicsBody;
  90942. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  90943. if (!mainBody || !connectedBody) {
  90944. return;
  90945. }
  90946. var jointData = impostorJoint.joint.jointData;
  90947. var options = jointData.nativeParams || {};
  90948. var type;
  90949. var nativeJointData = {
  90950. body1: mainBody,
  90951. body2: connectedBody,
  90952. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  90953. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  90954. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  90955. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  90956. min: options.min,
  90957. max: options.max,
  90958. collision: options.collision || jointData.collision,
  90959. spring: options.spring,
  90960. //supporting older version of Oimo
  90961. world: this.world
  90962. };
  90963. switch (impostorJoint.joint.type) {
  90964. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  90965. type = "jointBall";
  90966. break;
  90967. case BABYLON.PhysicsJoint.SpringJoint:
  90968. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  90969. var springData = jointData;
  90970. nativeJointData.min = springData.length || nativeJointData.min;
  90971. //Max should also be set, just make sure it is at least min
  90972. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  90973. case BABYLON.PhysicsJoint.DistanceJoint:
  90974. type = "jointDistance";
  90975. nativeJointData.max = jointData.maxDistance;
  90976. break;
  90977. case BABYLON.PhysicsJoint.PrismaticJoint:
  90978. type = "jointPrisme";
  90979. break;
  90980. case BABYLON.PhysicsJoint.SliderJoint:
  90981. type = "jointSlide";
  90982. break;
  90983. case BABYLON.PhysicsJoint.WheelJoint:
  90984. type = "jointWheel";
  90985. break;
  90986. case BABYLON.PhysicsJoint.HingeJoint:
  90987. default:
  90988. type = "jointHinge";
  90989. break;
  90990. }
  90991. nativeJointData.type = type;
  90992. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  90993. };
  90994. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  90995. //Bug in Oimo prevents us from disposing a joint in the playground
  90996. //joint.joint.physicsJoint.dispose();
  90997. //So we will bruteforce it!
  90998. try {
  90999. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  91000. }
  91001. catch (e) {
  91002. BABYLON.Tools.Warn(e);
  91003. }
  91004. };
  91005. OimoJSPlugin.prototype.isSupported = function () {
  91006. return this.BJSOIMO !== undefined;
  91007. };
  91008. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  91009. if (!impostor.physicsBody.sleeping) {
  91010. //TODO check that
  91011. /*if (impostor.physicsBody.shapes.next) {
  91012. var parentShape = this._getLastShape(impostor.physicsBody);
  91013. impostor.object.position.copyFrom(parentShape.position);
  91014. console.log(parentShape.position);
  91015. } else {*/
  91016. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  91017. //}
  91018. if (impostor.object.rotationQuaternion) {
  91019. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  91020. }
  91021. }
  91022. };
  91023. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  91024. var body = impostor.physicsBody;
  91025. body.position.copy(newPosition);
  91026. body.orientation.copy(newRotation);
  91027. body.syncShapes();
  91028. body.awake();
  91029. };
  91030. /*private _getLastShape(body: any): any {
  91031. var lastShape = body.shapes;
  91032. while (lastShape.next) {
  91033. lastShape = lastShape.next;
  91034. }
  91035. return lastShape;
  91036. }*/
  91037. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  91038. impostor.physicsBody.linearVelocity.copy(velocity);
  91039. };
  91040. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  91041. impostor.physicsBody.angularVelocity.copy(velocity);
  91042. };
  91043. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  91044. var v = impostor.physicsBody.linearVelocity;
  91045. if (!v) {
  91046. return null;
  91047. }
  91048. return new BABYLON.Vector3(v.x, v.y, v.z);
  91049. };
  91050. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  91051. var v = impostor.physicsBody.angularVelocity;
  91052. if (!v) {
  91053. return null;
  91054. }
  91055. return new BABYLON.Vector3(v.x, v.y, v.z);
  91056. };
  91057. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  91058. var staticBody = mass === 0;
  91059. //this will actually set the body's density and not its mass.
  91060. //But this is how oimo treats the mass variable.
  91061. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  91062. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  91063. };
  91064. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  91065. return impostor.physicsBody.shapes.density;
  91066. };
  91067. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  91068. return impostor.physicsBody.shapes.friction;
  91069. };
  91070. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  91071. impostor.physicsBody.shapes.friction = friction;
  91072. };
  91073. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  91074. return impostor.physicsBody.shapes.restitution;
  91075. };
  91076. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  91077. impostor.physicsBody.shapes.restitution = restitution;
  91078. };
  91079. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  91080. impostor.physicsBody.sleep();
  91081. };
  91082. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  91083. impostor.physicsBody.awake();
  91084. };
  91085. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  91086. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  91087. if (minDistance !== void 0) {
  91088. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  91089. }
  91090. };
  91091. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  91092. //TODO separate rotational and transational motors.
  91093. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  91094. if (motor) {
  91095. motor.setMotor(speed, maxForce);
  91096. }
  91097. };
  91098. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  91099. //TODO separate rotational and transational motors.
  91100. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  91101. if (motor) {
  91102. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  91103. }
  91104. };
  91105. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  91106. var body = impostor.physicsBody;
  91107. mesh.position.x = body.position.x;
  91108. mesh.position.y = body.position.y;
  91109. mesh.position.z = body.position.z;
  91110. if (mesh.rotationQuaternion) {
  91111. mesh.rotationQuaternion.x = body.orientation.x;
  91112. mesh.rotationQuaternion.y = body.orientation.y;
  91113. mesh.rotationQuaternion.z = body.orientation.z;
  91114. mesh.rotationQuaternion.w = body.orientation.s;
  91115. }
  91116. };
  91117. OimoJSPlugin.prototype.getRadius = function (impostor) {
  91118. return impostor.physicsBody.shapes.radius;
  91119. };
  91120. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  91121. var shape = impostor.physicsBody.shapes;
  91122. result.x = shape.halfWidth * 2;
  91123. result.y = shape.halfHeight * 2;
  91124. result.z = shape.halfDepth * 2;
  91125. };
  91126. OimoJSPlugin.prototype.dispose = function () {
  91127. this.world.clear();
  91128. };
  91129. return OimoJSPlugin;
  91130. }());
  91131. BABYLON.OimoJSPlugin = OimoJSPlugin;
  91132. })(BABYLON || (BABYLON = {}));
  91133. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  91134. var BABYLON;
  91135. (function (BABYLON) {
  91136. /**
  91137. * Gets the current physics engine
  91138. * @returns a IPhysicsEngine or null if none attached
  91139. */
  91140. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  91141. return this._physicsEngine;
  91142. };
  91143. /**
  91144. * Enables physics to the current scene
  91145. * @param gravity defines the scene's gravity for the physics engine
  91146. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  91147. * @return a boolean indicating if the physics engine was initialized
  91148. */
  91149. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  91150. if (gravity === void 0) { gravity = null; }
  91151. if (this._physicsEngine) {
  91152. return true;
  91153. }
  91154. // Register the component to the scene
  91155. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  91156. if (!component) {
  91157. component = new PhysicsEngineSceneComponent(this);
  91158. this._addComponent(component);
  91159. }
  91160. try {
  91161. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  91162. return true;
  91163. }
  91164. catch (e) {
  91165. BABYLON.Tools.Error(e.message);
  91166. return false;
  91167. }
  91168. };
  91169. /**
  91170. * Disables and disposes the physics engine associated with the scene
  91171. */
  91172. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  91173. if (!this._physicsEngine) {
  91174. return;
  91175. }
  91176. this._physicsEngine.dispose();
  91177. this._physicsEngine = null;
  91178. };
  91179. /**
  91180. * Gets a boolean indicating if there is an active physics engine
  91181. * @returns a boolean indicating if there is an active physics engine
  91182. */
  91183. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  91184. return this._physicsEngine !== undefined;
  91185. };
  91186. /**
  91187. * Deletes a physics compound impostor
  91188. * @param compound defines the compound to delete
  91189. */
  91190. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  91191. var mesh = compound.parts[0].mesh;
  91192. if (mesh.physicsImpostor) {
  91193. mesh.physicsImpostor.dispose( /*true*/);
  91194. mesh.physicsImpostor = null;
  91195. }
  91196. };
  91197. /** @hidden */
  91198. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  91199. if (this._physicsEngine) {
  91200. this.onBeforePhysicsObservable.notifyObservers(this);
  91201. this._physicsEngine._step(step / 1000);
  91202. this.onAfterPhysicsObservable.notifyObservers(this);
  91203. }
  91204. };
  91205. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  91206. get: function () {
  91207. return this._physicsImpostor;
  91208. },
  91209. set: function (value) {
  91210. var _this = this;
  91211. if (this._physicsImpostor === value) {
  91212. return;
  91213. }
  91214. if (this._disposePhysicsObserver) {
  91215. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  91216. }
  91217. this._physicsImpostor = value;
  91218. if (value) {
  91219. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  91220. // Physics
  91221. if (_this.physicsImpostor) {
  91222. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  91223. _this.physicsImpostor = null;
  91224. }
  91225. });
  91226. }
  91227. },
  91228. enumerable: true,
  91229. configurable: true
  91230. });
  91231. /**
  91232. * Gets the current physics impostor
  91233. * @see http://doc.babylonjs.com/features/physics_engine
  91234. * @returns a physics impostor or null
  91235. */
  91236. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  91237. return this.physicsImpostor;
  91238. };
  91239. /**
  91240. * Apply a physic impulse to the mesh
  91241. * @param force defines the force to apply
  91242. * @param contactPoint defines where to apply the force
  91243. * @returns the current mesh
  91244. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  91245. */
  91246. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  91247. if (!this.physicsImpostor) {
  91248. return this;
  91249. }
  91250. this.physicsImpostor.applyImpulse(force, contactPoint);
  91251. return this;
  91252. };
  91253. /**
  91254. * Creates a physic joint between two meshes
  91255. * @param otherMesh defines the other mesh to use
  91256. * @param pivot1 defines the pivot to use on this mesh
  91257. * @param pivot2 defines the pivot to use on the other mesh
  91258. * @param options defines additional options (can be plugin dependent)
  91259. * @returns the current mesh
  91260. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  91261. */
  91262. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  91263. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  91264. return this;
  91265. }
  91266. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  91267. mainPivot: pivot1,
  91268. connectedPivot: pivot2,
  91269. nativeParams: options
  91270. });
  91271. return this;
  91272. };
  91273. /**
  91274. * Defines the physics engine scene component responsible to manage a physics engine
  91275. */
  91276. var PhysicsEngineSceneComponent = /** @class */ (function () {
  91277. /**
  91278. * Creates a new instance of the component for the given scene
  91279. * @param scene Defines the scene to register the component in
  91280. */
  91281. function PhysicsEngineSceneComponent(scene) {
  91282. var _this = this;
  91283. /**
  91284. * The component name helpful to identify the component in the list of scene components.
  91285. */
  91286. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  91287. this.scene = scene;
  91288. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  91289. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  91290. // Replace the function used to get the deterministic frame time
  91291. this.scene.getDeterministicFrameTime = function () {
  91292. if (_this.scene._physicsEngine) {
  91293. return _this.scene._physicsEngine.getTimeStep() * 1000;
  91294. }
  91295. return 1000.0 / 60.0;
  91296. };
  91297. }
  91298. /**
  91299. * Registers the component in a given scene
  91300. */
  91301. PhysicsEngineSceneComponent.prototype.register = function () {
  91302. };
  91303. /**
  91304. * Rebuilds the elements related to this component in case of
  91305. * context lost for instance.
  91306. */
  91307. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  91308. // Nothing to do for this component
  91309. };
  91310. /**
  91311. * Disposes the component and the associated ressources
  91312. */
  91313. PhysicsEngineSceneComponent.prototype.dispose = function () {
  91314. this.scene.onBeforePhysicsObservable.clear();
  91315. this.scene.onAfterPhysicsObservable.clear();
  91316. if (this.scene._physicsEngine) {
  91317. this.scene.disablePhysicsEngine();
  91318. }
  91319. };
  91320. return PhysicsEngineSceneComponent;
  91321. }());
  91322. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  91323. })(BABYLON || (BABYLON = {}));
  91324. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  91325. var BABYLON;
  91326. (function (BABYLON) {
  91327. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  91328. // All values and structures referenced from:
  91329. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  91330. var DDS_MAGIC = 0x20534444;
  91331. var
  91332. //DDSD_CAPS = 0x1,
  91333. //DDSD_HEIGHT = 0x2,
  91334. //DDSD_WIDTH = 0x4,
  91335. //DDSD_PITCH = 0x8,
  91336. //DDSD_PIXELFORMAT = 0x1000,
  91337. DDSD_MIPMAPCOUNT = 0x20000;
  91338. //DDSD_LINEARSIZE = 0x80000,
  91339. //DDSD_DEPTH = 0x800000;
  91340. // var DDSCAPS_COMPLEX = 0x8,
  91341. // DDSCAPS_MIPMAP = 0x400000,
  91342. // DDSCAPS_TEXTURE = 0x1000;
  91343. var DDSCAPS2_CUBEMAP = 0x200;
  91344. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  91345. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  91346. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  91347. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  91348. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  91349. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  91350. // DDSCAPS2_VOLUME = 0x200000;
  91351. var
  91352. //DDPF_ALPHAPIXELS = 0x1,
  91353. //DDPF_ALPHA = 0x2,
  91354. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  91355. //DDPF_YUV = 0x200,
  91356. DDPF_LUMINANCE = 0x20000;
  91357. function FourCCToInt32(value) {
  91358. return value.charCodeAt(0) +
  91359. (value.charCodeAt(1) << 8) +
  91360. (value.charCodeAt(2) << 16) +
  91361. (value.charCodeAt(3) << 24);
  91362. }
  91363. function Int32ToFourCC(value) {
  91364. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  91365. }
  91366. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  91367. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  91368. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  91369. var FOURCC_DX10 = FourCCToInt32("DX10");
  91370. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  91371. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  91372. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  91373. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  91374. var headerLengthInt = 31; // The header length in 32 bit ints
  91375. // Offsets into the header array
  91376. var off_magic = 0;
  91377. var off_size = 1;
  91378. var off_flags = 2;
  91379. var off_height = 3;
  91380. var off_width = 4;
  91381. var off_mipmapCount = 7;
  91382. var off_pfFlags = 20;
  91383. var off_pfFourCC = 21;
  91384. var off_RGBbpp = 22;
  91385. var off_RMask = 23;
  91386. var off_GMask = 24;
  91387. var off_BMask = 25;
  91388. var off_AMask = 26;
  91389. // var off_caps1 = 27;
  91390. var off_caps2 = 28;
  91391. // var off_caps3 = 29;
  91392. // var off_caps4 = 30;
  91393. var off_dxgiFormat = 32;
  91394. ;
  91395. var DDSTools = /** @class */ (function () {
  91396. function DDSTools() {
  91397. }
  91398. DDSTools.GetDDSInfo = function (arrayBuffer) {
  91399. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  91400. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  91401. var mipmapCount = 1;
  91402. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  91403. mipmapCount = Math.max(1, header[off_mipmapCount]);
  91404. }
  91405. var fourCC = header[off_pfFourCC];
  91406. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  91407. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91408. switch (fourCC) {
  91409. case FOURCC_D3DFMT_R16G16B16A16F:
  91410. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91411. break;
  91412. case FOURCC_D3DFMT_R32G32B32A32F:
  91413. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91414. break;
  91415. case FOURCC_DX10:
  91416. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  91417. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91418. break;
  91419. }
  91420. }
  91421. return {
  91422. width: header[off_width],
  91423. height: header[off_height],
  91424. mipmapCount: mipmapCount,
  91425. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  91426. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  91427. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  91428. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  91429. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  91430. dxgiFormat: dxgiFormat,
  91431. textureType: textureType
  91432. };
  91433. };
  91434. DDSTools._ToHalfFloat = function (value) {
  91435. if (!DDSTools._FloatView) {
  91436. DDSTools._FloatView = new Float32Array(1);
  91437. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  91438. }
  91439. DDSTools._FloatView[0] = value;
  91440. var x = DDSTools._Int32View[0];
  91441. var bits = (x >> 16) & 0x8000; /* Get the sign */
  91442. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  91443. var e = (x >> 23) & 0xff; /* Using int is faster here */
  91444. /* If zero, or denormal, or exponent underflows too much for a denormal
  91445. * half, return signed zero. */
  91446. if (e < 103) {
  91447. return bits;
  91448. }
  91449. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  91450. if (e > 142) {
  91451. bits |= 0x7c00;
  91452. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  91453. * not Inf, so make sure we set one mantissa bit too. */
  91454. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  91455. return bits;
  91456. }
  91457. /* If exponent underflows but not too much, return a denormal */
  91458. if (e < 113) {
  91459. m |= 0x0800;
  91460. /* Extra rounding may overflow and set mantissa to 0 and exponent
  91461. * to 1, which is OK. */
  91462. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  91463. return bits;
  91464. }
  91465. bits |= ((e - 112) << 10) | (m >> 1);
  91466. bits += m & 1;
  91467. return bits;
  91468. };
  91469. DDSTools._FromHalfFloat = function (value) {
  91470. var s = (value & 0x8000) >> 15;
  91471. var e = (value & 0x7C00) >> 10;
  91472. var f = value & 0x03FF;
  91473. if (e === 0) {
  91474. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  91475. }
  91476. else if (e == 0x1F) {
  91477. return f ? NaN : ((s ? -1 : 1) * Infinity);
  91478. }
  91479. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  91480. };
  91481. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91482. var destArray = new Float32Array(dataLength);
  91483. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91484. var index = 0;
  91485. for (var y = 0; y < height; y++) {
  91486. for (var x = 0; x < width; x++) {
  91487. var srcPos = (x + y * width) * 4;
  91488. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  91489. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  91490. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  91491. if (DDSTools.StoreLODInAlphaChannel) {
  91492. destArray[index + 3] = lod;
  91493. }
  91494. else {
  91495. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  91496. }
  91497. index += 4;
  91498. }
  91499. }
  91500. return destArray;
  91501. };
  91502. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91503. if (DDSTools.StoreLODInAlphaChannel) {
  91504. var destArray = new Uint16Array(dataLength);
  91505. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91506. var index = 0;
  91507. for (var y = 0; y < height; y++) {
  91508. for (var x = 0; x < width; x++) {
  91509. var srcPos = (x + y * width) * 4;
  91510. destArray[index] = srcData[srcPos];
  91511. destArray[index + 1] = srcData[srcPos + 1];
  91512. destArray[index + 2] = srcData[srcPos + 2];
  91513. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  91514. index += 4;
  91515. }
  91516. }
  91517. return destArray;
  91518. }
  91519. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  91520. };
  91521. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91522. if (DDSTools.StoreLODInAlphaChannel) {
  91523. var destArray = new Float32Array(dataLength);
  91524. var srcData = new Float32Array(arrayBuffer, dataOffset);
  91525. var index = 0;
  91526. for (var y = 0; y < height; y++) {
  91527. for (var x = 0; x < width; x++) {
  91528. var srcPos = (x + y * width) * 4;
  91529. destArray[index] = srcData[srcPos];
  91530. destArray[index + 1] = srcData[srcPos + 1];
  91531. destArray[index + 2] = srcData[srcPos + 2];
  91532. destArray[index + 3] = lod;
  91533. index += 4;
  91534. }
  91535. }
  91536. return destArray;
  91537. }
  91538. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  91539. };
  91540. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91541. var destArray = new Uint8Array(dataLength);
  91542. var srcData = new Float32Array(arrayBuffer, dataOffset);
  91543. var index = 0;
  91544. for (var y = 0; y < height; y++) {
  91545. for (var x = 0; x < width; x++) {
  91546. var srcPos = (x + y * width) * 4;
  91547. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  91548. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  91549. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  91550. if (DDSTools.StoreLODInAlphaChannel) {
  91551. destArray[index + 3] = lod;
  91552. }
  91553. else {
  91554. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  91555. }
  91556. index += 4;
  91557. }
  91558. }
  91559. return destArray;
  91560. };
  91561. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91562. var destArray = new Uint8Array(dataLength);
  91563. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91564. var index = 0;
  91565. for (var y = 0; y < height; y++) {
  91566. for (var x = 0; x < width; x++) {
  91567. var srcPos = (x + y * width) * 4;
  91568. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  91569. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  91570. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  91571. if (DDSTools.StoreLODInAlphaChannel) {
  91572. destArray[index + 3] = lod;
  91573. }
  91574. else {
  91575. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  91576. }
  91577. index += 4;
  91578. }
  91579. }
  91580. return destArray;
  91581. };
  91582. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  91583. var byteArray = new Uint8Array(dataLength);
  91584. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91585. var index = 0;
  91586. for (var y = 0; y < height; y++) {
  91587. for (var x = 0; x < width; x++) {
  91588. var srcPos = (x + y * width) * 4;
  91589. byteArray[index] = srcData[srcPos + rOffset];
  91590. byteArray[index + 1] = srcData[srcPos + gOffset];
  91591. byteArray[index + 2] = srcData[srcPos + bOffset];
  91592. byteArray[index + 3] = srcData[srcPos + aOffset];
  91593. index += 4;
  91594. }
  91595. }
  91596. return byteArray;
  91597. };
  91598. DDSTools._ExtractLongWordOrder = function (value) {
  91599. if (value === 0 || value === 255 || value === -16777216) {
  91600. return 0;
  91601. }
  91602. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  91603. };
  91604. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  91605. var byteArray = new Uint8Array(dataLength);
  91606. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91607. var index = 0;
  91608. for (var y = 0; y < height; y++) {
  91609. for (var x = 0; x < width; x++) {
  91610. var srcPos = (x + y * width) * 3;
  91611. byteArray[index] = srcData[srcPos + rOffset];
  91612. byteArray[index + 1] = srcData[srcPos + gOffset];
  91613. byteArray[index + 2] = srcData[srcPos + bOffset];
  91614. index += 3;
  91615. }
  91616. }
  91617. return byteArray;
  91618. };
  91619. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  91620. var byteArray = new Uint8Array(dataLength);
  91621. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91622. var index = 0;
  91623. for (var y = 0; y < height; y++) {
  91624. for (var x = 0; x < width; x++) {
  91625. var srcPos = (x + y * width);
  91626. byteArray[index] = srcData[srcPos];
  91627. index++;
  91628. }
  91629. }
  91630. return byteArray;
  91631. };
  91632. /**
  91633. * Uploads DDS Levels to a Babylon Texture
  91634. * @hidden
  91635. */
  91636. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  91637. if (lodIndex === void 0) { lodIndex = -1; }
  91638. var sphericalPolynomialFaces = null;
  91639. if (info.sphericalPolynomial) {
  91640. sphericalPolynomialFaces = new Array();
  91641. }
  91642. var ext = engine.getCaps().s3tc;
  91643. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  91644. var fourCC, width, height, dataLength = 0, dataOffset;
  91645. var byteArray, mipmapCount, mip;
  91646. var internalCompressedFormat = 0;
  91647. var blockBytes = 1;
  91648. if (header[off_magic] !== DDS_MAGIC) {
  91649. BABYLON.Tools.Error("Invalid magic number in DDS header");
  91650. return;
  91651. }
  91652. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  91653. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  91654. return;
  91655. }
  91656. if (info.isCompressed && !ext) {
  91657. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  91658. return;
  91659. }
  91660. var bpp = header[off_RGBbpp];
  91661. dataOffset = header[off_size] + 4;
  91662. var computeFormats = false;
  91663. if (info.isFourCC) {
  91664. fourCC = header[off_pfFourCC];
  91665. switch (fourCC) {
  91666. case FOURCC_DXT1:
  91667. blockBytes = 8;
  91668. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  91669. break;
  91670. case FOURCC_DXT3:
  91671. blockBytes = 16;
  91672. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  91673. break;
  91674. case FOURCC_DXT5:
  91675. blockBytes = 16;
  91676. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  91677. break;
  91678. case FOURCC_D3DFMT_R16G16B16A16F:
  91679. computeFormats = true;
  91680. break;
  91681. case FOURCC_D3DFMT_R32G32B32A32F:
  91682. computeFormats = true;
  91683. break;
  91684. case FOURCC_DX10:
  91685. // There is an additionnal header so dataOffset need to be changed
  91686. dataOffset += 5 * 4; // 5 uints
  91687. var supported = false;
  91688. switch (info.dxgiFormat) {
  91689. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  91690. computeFormats = true;
  91691. supported = true;
  91692. break;
  91693. case DXGI_FORMAT_B8G8R8X8_UNORM:
  91694. info.isRGB = true;
  91695. info.isFourCC = false;
  91696. bpp = 32;
  91697. supported = true;
  91698. break;
  91699. }
  91700. if (supported) {
  91701. break;
  91702. }
  91703. default:
  91704. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  91705. return;
  91706. }
  91707. }
  91708. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  91709. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  91710. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  91711. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  91712. if (computeFormats) {
  91713. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  91714. }
  91715. mipmapCount = 1;
  91716. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  91717. mipmapCount = Math.max(1, header[off_mipmapCount]);
  91718. }
  91719. for (var face = 0; face < faces; face++) {
  91720. width = header[off_width];
  91721. height = header[off_height];
  91722. for (mip = 0; mip < mipmapCount; ++mip) {
  91723. if (lodIndex === -1 || lodIndex === mip) {
  91724. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  91725. var i = (lodIndex === -1) ? mip : 0;
  91726. if (!info.isCompressed && info.isFourCC) {
  91727. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91728. dataLength = width * height * 4;
  91729. var floatArray = null;
  91730. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  91731. if (bpp === 128) {
  91732. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91733. if (sphericalPolynomialFaces && i == 0) {
  91734. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91735. }
  91736. }
  91737. else if (bpp === 64) {
  91738. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91739. if (sphericalPolynomialFaces && i == 0) {
  91740. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91741. }
  91742. }
  91743. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91744. }
  91745. else {
  91746. if (bpp === 128) {
  91747. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91748. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91749. if (sphericalPolynomialFaces && i == 0) {
  91750. sphericalPolynomialFaces.push(floatArray);
  91751. }
  91752. }
  91753. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  91754. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91755. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91756. if (sphericalPolynomialFaces && i == 0) {
  91757. sphericalPolynomialFaces.push(floatArray);
  91758. }
  91759. }
  91760. else { // 64
  91761. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91762. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91763. if (sphericalPolynomialFaces && i == 0) {
  91764. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91765. }
  91766. }
  91767. }
  91768. if (floatArray) {
  91769. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  91770. }
  91771. }
  91772. else if (info.isRGB) {
  91773. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91774. if (bpp === 24) {
  91775. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  91776. dataLength = width * height * 3;
  91777. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  91778. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91779. }
  91780. else { // 32
  91781. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91782. dataLength = width * height * 4;
  91783. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  91784. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91785. }
  91786. }
  91787. else if (info.isLuminance) {
  91788. var unpackAlignment = engine._getUnpackAlignement();
  91789. var unpaddedRowSize = width;
  91790. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  91791. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  91792. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  91793. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  91794. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91795. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91796. }
  91797. else {
  91798. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  91799. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  91800. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91801. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  91802. }
  91803. }
  91804. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  91805. width *= 0.5;
  91806. height *= 0.5;
  91807. width = Math.max(1.0, width);
  91808. height = Math.max(1.0, height);
  91809. }
  91810. if (currentFace !== undefined) {
  91811. // Loading a single face
  91812. break;
  91813. }
  91814. }
  91815. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  91816. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  91817. size: header[off_width],
  91818. right: sphericalPolynomialFaces[0],
  91819. left: sphericalPolynomialFaces[1],
  91820. up: sphericalPolynomialFaces[2],
  91821. down: sphericalPolynomialFaces[3],
  91822. front: sphericalPolynomialFaces[4],
  91823. back: sphericalPolynomialFaces[5],
  91824. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  91825. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  91826. gammaSpace: false,
  91827. });
  91828. }
  91829. else {
  91830. info.sphericalPolynomial = undefined;
  91831. }
  91832. };
  91833. DDSTools.StoreLODInAlphaChannel = false;
  91834. return DDSTools;
  91835. }());
  91836. BABYLON.DDSTools = DDSTools;
  91837. })(BABYLON || (BABYLON = {}));
  91838. //# sourceMappingURL=babylon.dds.js.map
  91839. var BABYLON;
  91840. (function (BABYLON) {
  91841. /**
  91842. * Implementation of the DDS Texture Loader.
  91843. */
  91844. var DDSTextureLoader = /** @class */ (function () {
  91845. function DDSTextureLoader() {
  91846. /**
  91847. * Defines wether the loader supports cascade loading the different faces.
  91848. */
  91849. this.supportCascades = true;
  91850. }
  91851. /**
  91852. * This returns if the loader support the current file information.
  91853. * @param extension defines the file extension of the file being loaded
  91854. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91855. * @param fallback defines the fallback internal texture if any
  91856. * @param isBase64 defines whether the texture is encoded as a base64
  91857. * @param isBuffer defines whether the texture data are stored as a buffer
  91858. * @returns true if the loader can load the specified file
  91859. */
  91860. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91861. return extension.indexOf(".dds") === 0;
  91862. };
  91863. /**
  91864. * Transform the url before loading if required.
  91865. * @param rootUrl the url of the texture
  91866. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91867. * @returns the transformed texture
  91868. */
  91869. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91870. return rootUrl;
  91871. };
  91872. /**
  91873. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91874. * @param rootUrl the url of the texture
  91875. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91876. * @returns the fallback texture
  91877. */
  91878. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91879. return null;
  91880. };
  91881. /**
  91882. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91883. * @param data contains the texture data
  91884. * @param texture defines the BabylonJS internal texture
  91885. * @param createPolynomials will be true if polynomials have been requested
  91886. * @param onLoad defines the callback to trigger once the texture is ready
  91887. * @param onError defines the callback to trigger in case of error
  91888. */
  91889. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  91890. var engine = texture.getEngine();
  91891. var info;
  91892. var loadMipmap = false;
  91893. if (Array.isArray(imgs)) {
  91894. for (var index = 0; index < imgs.length; index++) {
  91895. var data_1 = imgs[index];
  91896. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  91897. texture.width = info.width;
  91898. texture.height = info.height;
  91899. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91900. engine._unpackFlipY(info.isCompressed);
  91901. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  91902. if (!info.isFourCC && info.mipmapCount === 1) {
  91903. engine.generateMipMapsForCubemap(texture);
  91904. }
  91905. }
  91906. }
  91907. else {
  91908. var data = imgs;
  91909. info = BABYLON.DDSTools.GetDDSInfo(data);
  91910. texture.width = info.width;
  91911. texture.height = info.height;
  91912. if (createPolynomials) {
  91913. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  91914. }
  91915. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91916. engine._unpackFlipY(info.isCompressed);
  91917. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  91918. if (!info.isFourCC && info.mipmapCount === 1) {
  91919. engine.generateMipMapsForCubemap(texture);
  91920. }
  91921. }
  91922. engine._setCubeMapTextureParams(loadMipmap);
  91923. texture.isReady = true;
  91924. if (onLoad) {
  91925. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  91926. }
  91927. };
  91928. /**
  91929. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91930. * @param data contains the texture data
  91931. * @param texture defines the BabylonJS internal texture
  91932. * @param callback defines the method to call once ready to upload
  91933. */
  91934. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  91935. var info = BABYLON.DDSTools.GetDDSInfo(data);
  91936. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  91937. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  91938. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  91939. });
  91940. };
  91941. return DDSTextureLoader;
  91942. }());
  91943. // Register the loader.
  91944. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  91945. })(BABYLON || (BABYLON = {}));
  91946. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  91947. var BABYLON;
  91948. (function (BABYLON) {
  91949. /*
  91950. * Based on jsTGALoader - Javascript loader for TGA file
  91951. * By Vincent Thibault
  91952. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  91953. */
  91954. var TGATools = /** @class */ (function () {
  91955. function TGATools() {
  91956. }
  91957. TGATools.GetTGAHeader = function (data) {
  91958. var offset = 0;
  91959. var header = {
  91960. id_length: data[offset++],
  91961. colormap_type: data[offset++],
  91962. image_type: data[offset++],
  91963. colormap_index: data[offset++] | data[offset++] << 8,
  91964. colormap_length: data[offset++] | data[offset++] << 8,
  91965. colormap_size: data[offset++],
  91966. origin: [
  91967. data[offset++] | data[offset++] << 8,
  91968. data[offset++] | data[offset++] << 8
  91969. ],
  91970. width: data[offset++] | data[offset++] << 8,
  91971. height: data[offset++] | data[offset++] << 8,
  91972. pixel_size: data[offset++],
  91973. flags: data[offset++]
  91974. };
  91975. return header;
  91976. };
  91977. /**
  91978. * Uploads TGA content to a Babylon Texture
  91979. * @hidden
  91980. */
  91981. TGATools.UploadContent = function (texture, data) {
  91982. // Not enough data to contain header ?
  91983. if (data.length < 19) {
  91984. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  91985. return;
  91986. }
  91987. // Read Header
  91988. var offset = 18;
  91989. var header = TGATools.GetTGAHeader(data);
  91990. // Assume it's a valid Targa file.
  91991. if (header.id_length + offset > data.length) {
  91992. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  91993. return;
  91994. }
  91995. // Skip not needed data
  91996. offset += header.id_length;
  91997. var use_rle = false;
  91998. var use_pal = false;
  91999. var use_grey = false;
  92000. // Get some informations.
  92001. switch (header.image_type) {
  92002. case TGATools._TYPE_RLE_INDEXED:
  92003. use_rle = true;
  92004. case TGATools._TYPE_INDEXED:
  92005. use_pal = true;
  92006. break;
  92007. case TGATools._TYPE_RLE_RGB:
  92008. use_rle = true;
  92009. case TGATools._TYPE_RGB:
  92010. // use_rgb = true;
  92011. break;
  92012. case TGATools._TYPE_RLE_GREY:
  92013. use_rle = true;
  92014. case TGATools._TYPE_GREY:
  92015. use_grey = true;
  92016. break;
  92017. }
  92018. var pixel_data;
  92019. // var numAlphaBits = header.flags & 0xf;
  92020. var pixel_size = header.pixel_size >> 3;
  92021. var pixel_total = header.width * header.height * pixel_size;
  92022. // Read palettes
  92023. var palettes;
  92024. if (use_pal) {
  92025. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  92026. }
  92027. // Read LRE
  92028. if (use_rle) {
  92029. pixel_data = new Uint8Array(pixel_total);
  92030. var c, count, i;
  92031. var localOffset = 0;
  92032. var pixels = new Uint8Array(pixel_size);
  92033. while (offset < pixel_total && localOffset < pixel_total) {
  92034. c = data[offset++];
  92035. count = (c & 0x7f) + 1;
  92036. // RLE pixels
  92037. if (c & 0x80) {
  92038. // Bind pixel tmp array
  92039. for (i = 0; i < pixel_size; ++i) {
  92040. pixels[i] = data[offset++];
  92041. }
  92042. // Copy pixel array
  92043. for (i = 0; i < count; ++i) {
  92044. pixel_data.set(pixels, localOffset + i * pixel_size);
  92045. }
  92046. localOffset += pixel_size * count;
  92047. }
  92048. // Raw pixels
  92049. else {
  92050. count *= pixel_size;
  92051. for (i = 0; i < count; ++i) {
  92052. pixel_data[localOffset + i] = data[offset++];
  92053. }
  92054. localOffset += count;
  92055. }
  92056. }
  92057. }
  92058. // RAW Pixels
  92059. else {
  92060. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  92061. }
  92062. // Load to texture
  92063. var x_start, y_start, x_step, y_step, y_end, x_end;
  92064. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  92065. default:
  92066. case TGATools._ORIGIN_UL:
  92067. x_start = 0;
  92068. x_step = 1;
  92069. x_end = header.width;
  92070. y_start = 0;
  92071. y_step = 1;
  92072. y_end = header.height;
  92073. break;
  92074. case TGATools._ORIGIN_BL:
  92075. x_start = 0;
  92076. x_step = 1;
  92077. x_end = header.width;
  92078. y_start = header.height - 1;
  92079. y_step = -1;
  92080. y_end = -1;
  92081. break;
  92082. case TGATools._ORIGIN_UR:
  92083. x_start = header.width - 1;
  92084. x_step = -1;
  92085. x_end = -1;
  92086. y_start = 0;
  92087. y_step = 1;
  92088. y_end = header.height;
  92089. break;
  92090. case TGATools._ORIGIN_BR:
  92091. x_start = header.width - 1;
  92092. x_step = -1;
  92093. x_end = -1;
  92094. y_start = header.height - 1;
  92095. y_step = -1;
  92096. y_end = -1;
  92097. break;
  92098. }
  92099. // Load the specify method
  92100. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  92101. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  92102. var engine = texture.getEngine();
  92103. engine._uploadDataToTextureDirectly(texture, imageData);
  92104. };
  92105. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  92106. var image = pixel_data, colormap = palettes;
  92107. var width = header.width, height = header.height;
  92108. var color, i = 0, x, y;
  92109. var imageData = new Uint8Array(width * height * 4);
  92110. for (y = y_start; y !== y_end; y += y_step) {
  92111. for (x = x_start; x !== x_end; x += x_step, i++) {
  92112. color = image[i];
  92113. imageData[(x + width * y) * 4 + 3] = 255;
  92114. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  92115. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  92116. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  92117. }
  92118. }
  92119. return imageData;
  92120. };
  92121. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  92122. var image = pixel_data;
  92123. var width = header.width, height = header.height;
  92124. var color, i = 0, x, y;
  92125. var imageData = new Uint8Array(width * height * 4);
  92126. for (y = y_start; y !== y_end; y += y_step) {
  92127. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  92128. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  92129. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  92130. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  92131. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  92132. imageData[(x + width * y) * 4 + 0] = r;
  92133. imageData[(x + width * y) * 4 + 1] = g;
  92134. imageData[(x + width * y) * 4 + 2] = b;
  92135. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  92136. }
  92137. }
  92138. return imageData;
  92139. };
  92140. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  92141. var image = pixel_data;
  92142. var width = header.width, height = header.height;
  92143. var i = 0, x, y;
  92144. var imageData = new Uint8Array(width * height * 4);
  92145. for (y = y_start; y !== y_end; y += y_step) {
  92146. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  92147. imageData[(x + width * y) * 4 + 3] = 255;
  92148. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  92149. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  92150. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  92151. }
  92152. }
  92153. return imageData;
  92154. };
  92155. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  92156. var image = pixel_data;
  92157. var width = header.width, height = header.height;
  92158. var i = 0, x, y;
  92159. var imageData = new Uint8Array(width * height * 4);
  92160. for (y = y_start; y !== y_end; y += y_step) {
  92161. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  92162. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  92163. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  92164. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  92165. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  92166. }
  92167. }
  92168. return imageData;
  92169. };
  92170. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  92171. var image = pixel_data;
  92172. var width = header.width, height = header.height;
  92173. var color, i = 0, x, y;
  92174. var imageData = new Uint8Array(width * height * 4);
  92175. for (y = y_start; y !== y_end; y += y_step) {
  92176. for (x = x_start; x !== x_end; x += x_step, i++) {
  92177. color = image[i];
  92178. imageData[(x + width * y) * 4 + 0] = color;
  92179. imageData[(x + width * y) * 4 + 1] = color;
  92180. imageData[(x + width * y) * 4 + 2] = color;
  92181. imageData[(x + width * y) * 4 + 3] = 255;
  92182. }
  92183. }
  92184. return imageData;
  92185. };
  92186. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  92187. var image = pixel_data;
  92188. var width = header.width, height = header.height;
  92189. var i = 0, x, y;
  92190. var imageData = new Uint8Array(width * height * 4);
  92191. for (y = y_start; y !== y_end; y += y_step) {
  92192. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  92193. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  92194. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  92195. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  92196. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  92197. }
  92198. }
  92199. return imageData;
  92200. };
  92201. //private static _TYPE_NO_DATA = 0;
  92202. TGATools._TYPE_INDEXED = 1;
  92203. TGATools._TYPE_RGB = 2;
  92204. TGATools._TYPE_GREY = 3;
  92205. TGATools._TYPE_RLE_INDEXED = 9;
  92206. TGATools._TYPE_RLE_RGB = 10;
  92207. TGATools._TYPE_RLE_GREY = 11;
  92208. TGATools._ORIGIN_MASK = 0x30;
  92209. TGATools._ORIGIN_SHIFT = 0x04;
  92210. TGATools._ORIGIN_BL = 0x00;
  92211. TGATools._ORIGIN_BR = 0x01;
  92212. TGATools._ORIGIN_UL = 0x02;
  92213. TGATools._ORIGIN_UR = 0x03;
  92214. return TGATools;
  92215. }());
  92216. BABYLON.TGATools = TGATools;
  92217. })(BABYLON || (BABYLON = {}));
  92218. //# sourceMappingURL=babylon.tga.js.map
  92219. var BABYLON;
  92220. (function (BABYLON) {
  92221. /**
  92222. * Implementation of the TGA Texture Loader.
  92223. */
  92224. var TGATextureLoader = /** @class */ (function () {
  92225. function TGATextureLoader() {
  92226. /**
  92227. * Defines wether the loader supports cascade loading the different faces.
  92228. */
  92229. this.supportCascades = false;
  92230. }
  92231. /**
  92232. * This returns if the loader support the current file information.
  92233. * @param extension defines the file extension of the file being loaded
  92234. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92235. * @param fallback defines the fallback internal texture if any
  92236. * @param isBase64 defines whether the texture is encoded as a base64
  92237. * @param isBuffer defines whether the texture data are stored as a buffer
  92238. * @returns true if the loader can load the specified file
  92239. */
  92240. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92241. return extension.indexOf(".tga") === 0;
  92242. };
  92243. /**
  92244. * Transform the url before loading if required.
  92245. * @param rootUrl the url of the texture
  92246. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92247. * @returns the transformed texture
  92248. */
  92249. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  92250. return rootUrl;
  92251. };
  92252. /**
  92253. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  92254. * @param rootUrl the url of the texture
  92255. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92256. * @returns the fallback texture
  92257. */
  92258. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  92259. return null;
  92260. };
  92261. /**
  92262. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  92263. * @param data contains the texture data
  92264. * @param texture defines the BabylonJS internal texture
  92265. * @param createPolynomials will be true if polynomials have been requested
  92266. * @param onLoad defines the callback to trigger once the texture is ready
  92267. * @param onError defines the callback to trigger in case of error
  92268. */
  92269. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  92270. throw ".env not supported in Cube.";
  92271. };
  92272. /**
  92273. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92274. * @param data contains the texture data
  92275. * @param texture defines the BabylonJS internal texture
  92276. * @param callback defines the method to call once ready to upload
  92277. */
  92278. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  92279. var uintData = new Uint8Array(data);
  92280. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  92281. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  92282. BABYLON.TGATools.UploadContent(texture, uintData);
  92283. });
  92284. };
  92285. return TGATextureLoader;
  92286. }());
  92287. // Register the loader.
  92288. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  92289. })(BABYLON || (BABYLON = {}));
  92290. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  92291. var BABYLON;
  92292. (function (BABYLON) {
  92293. /**
  92294. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  92295. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  92296. */
  92297. var KhronosTextureContainer = /** @class */ (function () {
  92298. /**
  92299. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  92300. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  92301. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  92302. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  92303. */
  92304. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  92305. this.arrayBuffer = arrayBuffer;
  92306. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  92307. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  92308. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  92309. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  92310. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  92311. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  92312. BABYLON.Tools.Error("texture missing KTX identifier");
  92313. return;
  92314. }
  92315. // load the reset of the header in native 32 bit int
  92316. var header = new Int32Array(this.arrayBuffer, 12, 13);
  92317. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  92318. var oppositeEndianess = header[0] === 0x01020304;
  92319. // read all the header elements in order they exist in the file, without modification (sans endainness)
  92320. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  92321. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  92322. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  92323. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  92324. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  92325. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  92326. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  92327. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  92328. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  92329. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  92330. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  92331. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  92332. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  92333. if (this.glType !== 0) {
  92334. BABYLON.Tools.Error("only compressed formats currently supported");
  92335. return;
  92336. }
  92337. else {
  92338. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  92339. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  92340. }
  92341. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  92342. BABYLON.Tools.Error("only 2D textures currently supported");
  92343. return;
  92344. }
  92345. if (this.numberOfArrayElements !== 0) {
  92346. BABYLON.Tools.Error("texture arrays not currently supported");
  92347. return;
  92348. }
  92349. if (this.numberOfFaces !== facesExpected) {
  92350. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  92351. return;
  92352. }
  92353. // we now have a completely validated file, so could use existence of loadType as success
  92354. // would need to make this more elaborate & adjust checks above to support more than one load type
  92355. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  92356. }
  92357. // not as fast hardware based, but will probably never need to use
  92358. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  92359. return ((val & 0xFF) << 24)
  92360. | ((val & 0xFF00) << 8)
  92361. | ((val >> 8) & 0xFF00)
  92362. | ((val >> 24) & 0xFF);
  92363. };
  92364. /**
  92365. * Uploads KTX content to a Babylon Texture.
  92366. * It is assumed that the texture has already been created & is currently bound
  92367. * @hidden
  92368. */
  92369. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  92370. switch (this.loadType) {
  92371. case KhronosTextureContainer.COMPRESSED_2D:
  92372. this._upload2DCompressedLevels(texture, loadMipmaps);
  92373. break;
  92374. case KhronosTextureContainer.TEX_2D:
  92375. case KhronosTextureContainer.COMPRESSED_3D:
  92376. case KhronosTextureContainer.TEX_3D:
  92377. }
  92378. };
  92379. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  92380. // initialize width & height for level 1
  92381. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  92382. var width = this.pixelWidth;
  92383. var height = this.pixelHeight;
  92384. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  92385. for (var level = 0; level < mipmapCount; level++) {
  92386. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  92387. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  92388. for (var face = 0; face < this.numberOfFaces; face++) {
  92389. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  92390. var engine = texture.getEngine();
  92391. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  92392. dataOffset += imageSize; // add size of the image for the next face/mipmap
  92393. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  92394. }
  92395. width = Math.max(1.0, width * 0.5);
  92396. height = Math.max(1.0, height * 0.5);
  92397. }
  92398. };
  92399. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  92400. // load types
  92401. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  92402. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  92403. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  92404. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  92405. return KhronosTextureContainer;
  92406. }());
  92407. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  92408. })(BABYLON || (BABYLON = {}));
  92409. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  92410. var BABYLON;
  92411. (function (BABYLON) {
  92412. /**
  92413. * Implementation of the KTX Texture Loader.
  92414. */
  92415. var KTXTextureLoader = /** @class */ (function () {
  92416. function KTXTextureLoader() {
  92417. /**
  92418. * Defines wether the loader supports cascade loading the different faces.
  92419. */
  92420. this.supportCascades = false;
  92421. }
  92422. /**
  92423. * This returns if the loader support the current file information.
  92424. * @param extension defines the file extension of the file being loaded
  92425. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92426. * @param fallback defines the fallback internal texture if any
  92427. * @param isBase64 defines whether the texture is encoded as a base64
  92428. * @param isBuffer defines whether the texture data are stored as a buffer
  92429. * @returns true if the loader can load the specified file
  92430. */
  92431. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92432. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  92433. return true;
  92434. }
  92435. return false;
  92436. };
  92437. /**
  92438. * Transform the url before loading if required.
  92439. * @param rootUrl the url of the texture
  92440. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92441. * @returns the transformed texture
  92442. */
  92443. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  92444. var lastDot = rootUrl.lastIndexOf('.');
  92445. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  92446. };
  92447. /**
  92448. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  92449. * @param rootUrl the url of the texture
  92450. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92451. * @returns the fallback texture
  92452. */
  92453. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  92454. // remove the format appended to the rootUrl in the original createCubeTexture call.
  92455. var exp = new RegExp("" + textureFormatInUse + "$");
  92456. return rootUrl.replace(exp, "");
  92457. };
  92458. /**
  92459. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  92460. * @param data contains the texture data
  92461. * @param texture defines the BabylonJS internal texture
  92462. * @param createPolynomials will be true if polynomials have been requested
  92463. * @param onLoad defines the callback to trigger once the texture is ready
  92464. * @param onError defines the callback to trigger in case of error
  92465. */
  92466. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  92467. if (Array.isArray(data)) {
  92468. return;
  92469. }
  92470. var engine = texture.getEngine();
  92471. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  92472. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  92473. engine._unpackFlipY(true);
  92474. ktx.uploadLevels(texture, texture.generateMipMaps);
  92475. texture.width = ktx.pixelWidth;
  92476. texture.height = ktx.pixelHeight;
  92477. engine._setCubeMapTextureParams(loadMipmap);
  92478. texture.isReady = true;
  92479. };
  92480. /**
  92481. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92482. * @param data contains the texture data
  92483. * @param texture defines the BabylonJS internal texture
  92484. * @param callback defines the method to call once ready to upload
  92485. */
  92486. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  92487. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  92488. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  92489. ktx.uploadLevels(texture, texture.generateMipMaps);
  92490. });
  92491. };
  92492. return KTXTextureLoader;
  92493. }());
  92494. // Register the loader.
  92495. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  92496. })(BABYLON || (BABYLON = {}));
  92497. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  92498. var BABYLON;
  92499. (function (BABYLON) {
  92500. /**
  92501. * Sets of helpers addressing the serialization and deserialization of environment texture
  92502. * stored in a BabylonJS env file.
  92503. * Those files are usually stored as .env files.
  92504. */
  92505. var EnvironmentTextureTools = /** @class */ (function () {
  92506. function EnvironmentTextureTools() {
  92507. }
  92508. /**
  92509. * Gets the environment info from an env file.
  92510. * @param data The array buffer containing the .env bytes.
  92511. * @returns the environment file info (the json header) if successfully parsed.
  92512. */
  92513. EnvironmentTextureTools.GetEnvInfo = function (data) {
  92514. var dataView = new DataView(data);
  92515. var pos = 0;
  92516. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  92517. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  92518. BABYLON.Tools.Error('Not a babylon environment map');
  92519. return null;
  92520. }
  92521. }
  92522. // Read json manifest - collect characters up to null terminator
  92523. var manifestString = '';
  92524. var charCode = 0x00;
  92525. while ((charCode = dataView.getUint8(pos++))) {
  92526. manifestString += String.fromCharCode(charCode);
  92527. }
  92528. var manifest = JSON.parse(manifestString);
  92529. if (manifest.specular) {
  92530. // Extend the header with the position of the payload.
  92531. manifest.specular.specularDataPosition = pos;
  92532. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  92533. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  92534. }
  92535. return manifest;
  92536. };
  92537. /**
  92538. * Creates an environment texture from a loaded cube texture.
  92539. * @param texture defines the cube texture to convert in env file
  92540. * @return a promise containing the environment data if succesfull.
  92541. */
  92542. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  92543. var _this = this;
  92544. var internalTexture = texture.getInternalTexture();
  92545. if (!internalTexture) {
  92546. return Promise.reject("The cube texture is invalid.");
  92547. }
  92548. if (!texture._prefiltered) {
  92549. return Promise.reject("The cube texture is invalid (not prefiltered).");
  92550. }
  92551. var engine = internalTexture.getEngine();
  92552. if (engine && engine.premultipliedAlpha) {
  92553. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  92554. }
  92555. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  92556. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  92557. }
  92558. var canvas = engine.getRenderingCanvas();
  92559. if (!canvas) {
  92560. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  92561. }
  92562. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  92563. if (!engine.getCaps().textureFloatRender) {
  92564. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92565. if (!engine.getCaps().textureHalfFloatRender) {
  92566. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  92567. }
  92568. }
  92569. var cubeWidth = internalTexture.width;
  92570. var hostingScene = new BABYLON.Scene(engine);
  92571. var specularTextures = {};
  92572. var promises = [];
  92573. // Read and collect all mipmaps data from the cube.
  92574. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  92575. mipmapsCount = Math.round(mipmapsCount);
  92576. var _loop_1 = function (i) {
  92577. var faceWidth = Math.pow(2, mipmapsCount - i);
  92578. var _loop_2 = function (face) {
  92579. var data = texture.readPixels(face, i);
  92580. // Creates a temp texture with the face data.
  92581. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  92582. // And rgbdEncode them.
  92583. var promise = new Promise(function (resolve, reject) {
  92584. 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);
  92585. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  92586. rgbdPostProcess.onApply = function (effect) {
  92587. effect._bindTexture("textureSampler", tempTexture);
  92588. };
  92589. // As the process needs to happen on the main canvas, keep track of the current size
  92590. var currentW = engine.getRenderWidth();
  92591. var currentH = engine.getRenderHeight();
  92592. // Set the desired size for the texture
  92593. engine.setSize(faceWidth, faceWidth);
  92594. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  92595. // Reading datas from WebGL
  92596. BABYLON.Tools.ToBlob(canvas, function (blob) {
  92597. var fileReader = new FileReader();
  92598. fileReader.onload = function (event) {
  92599. var arrayBuffer = event.target.result;
  92600. specularTextures[i * 6 + face] = arrayBuffer;
  92601. resolve();
  92602. };
  92603. fileReader.readAsArrayBuffer(blob);
  92604. });
  92605. // Reapply the previous canvas size
  92606. engine.setSize(currentW, currentH);
  92607. });
  92608. });
  92609. promises.push(promise);
  92610. };
  92611. // All faces of the cube.
  92612. for (var face = 0; face < 6; face++) {
  92613. _loop_2(face);
  92614. }
  92615. };
  92616. for (var i = 0; i <= mipmapsCount; i++) {
  92617. _loop_1(i);
  92618. }
  92619. // Once all the textures haves been collected as RGBD stored in PNGs
  92620. return Promise.all(promises).then(function () {
  92621. // We can delete the hosting scene keeping track of all the creation objects
  92622. hostingScene.dispose();
  92623. // Creates the json header for the env texture
  92624. var info = {
  92625. version: 1,
  92626. width: cubeWidth,
  92627. irradiance: _this._CreateEnvTextureIrradiance(texture),
  92628. specular: {
  92629. mipmaps: [],
  92630. lodGenerationScale: texture.lodGenerationScale
  92631. }
  92632. };
  92633. // Sets the specular image data information
  92634. var position = 0;
  92635. for (var i = 0; i <= mipmapsCount; i++) {
  92636. for (var face = 0; face < 6; face++) {
  92637. var byteLength = specularTextures[i * 6 + face].byteLength;
  92638. info.specular.mipmaps.push({
  92639. length: byteLength,
  92640. position: position
  92641. });
  92642. position += byteLength;
  92643. }
  92644. }
  92645. // Encode the JSON as an array buffer
  92646. var infoString = JSON.stringify(info);
  92647. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  92648. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  92649. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  92650. infoView[i] = infoString.charCodeAt(i);
  92651. }
  92652. // Ends up with a null terminator for easier parsing
  92653. infoView[infoString.length] = 0x00;
  92654. // Computes the final required size and creates the storage
  92655. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  92656. var finalBuffer = new ArrayBuffer(totalSize);
  92657. var finalBufferView = new Uint8Array(finalBuffer);
  92658. var dataView = new DataView(finalBuffer);
  92659. // Copy the magic bytes identifying the file in
  92660. var pos = 0;
  92661. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  92662. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  92663. }
  92664. // Add the json info
  92665. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  92666. pos += infoBuffer.byteLength;
  92667. // Finally inserts the texture data
  92668. for (var i = 0; i <= mipmapsCount; i++) {
  92669. for (var face = 0; face < 6; face++) {
  92670. var dataBuffer = specularTextures[i * 6 + face];
  92671. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  92672. pos += dataBuffer.byteLength;
  92673. }
  92674. }
  92675. // Voila
  92676. return finalBuffer;
  92677. });
  92678. };
  92679. /**
  92680. * Creates a JSON representation of the spherical data.
  92681. * @param texture defines the texture containing the polynomials
  92682. * @return the JSON representation of the spherical info
  92683. */
  92684. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  92685. var polynmials = texture.sphericalPolynomial;
  92686. if (polynmials == null) {
  92687. return null;
  92688. }
  92689. return {
  92690. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  92691. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  92692. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  92693. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  92694. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  92695. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  92696. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  92697. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  92698. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  92699. };
  92700. };
  92701. /**
  92702. * Uploads the texture info contained in the env file to the GPU.
  92703. * @param texture defines the internal texture to upload to
  92704. * @param arrayBuffer defines the buffer cotaining the data to load
  92705. * @param info defines the texture info retrieved through the GetEnvInfo method
  92706. * @returns a promise
  92707. */
  92708. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  92709. if (info.version !== 1) {
  92710. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  92711. }
  92712. var specularInfo = info.specular;
  92713. if (!specularInfo) {
  92714. // Nothing else parsed so far
  92715. return Promise.resolve();
  92716. }
  92717. // Double checks the enclosed info
  92718. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  92719. mipmapsCount = Math.round(mipmapsCount) + 1;
  92720. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  92721. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  92722. }
  92723. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  92724. var imageData = new Array(mipmapsCount);
  92725. for (var i = 0; i < mipmapsCount; i++) {
  92726. imageData[i] = new Array(6);
  92727. for (var face = 0; face < 6; face++) {
  92728. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  92729. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  92730. }
  92731. }
  92732. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  92733. };
  92734. /**
  92735. * Uploads the levels of image data to the GPU.
  92736. * @param texture defines the internal texture to upload to
  92737. * @param imageData defines the array buffer views of image data [mipmap][face]
  92738. * @returns a promise
  92739. */
  92740. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  92741. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  92742. throw new Error("Texture size must be a power of two");
  92743. }
  92744. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  92745. // Gets everything ready.
  92746. var engine = texture.getEngine();
  92747. var expandTexture = false;
  92748. var generateNonLODTextures = false;
  92749. var rgbdPostProcess = null;
  92750. var cubeRtt = null;
  92751. var lodTextures = null;
  92752. var caps = engine.getCaps();
  92753. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  92754. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92755. texture.generateMipMaps = true;
  92756. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  92757. // Add extra process if texture lod is not supported
  92758. if (!caps.textureLOD) {
  92759. expandTexture = false;
  92760. generateNonLODTextures = true;
  92761. lodTextures = {};
  92762. }
  92763. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  92764. else if (engine.webGLVersion < 2) {
  92765. expandTexture = false;
  92766. }
  92767. // If half float available we can uncompress the texture
  92768. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  92769. expandTexture = true;
  92770. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92771. }
  92772. // If full float available we can uncompress the texture
  92773. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  92774. expandTexture = true;
  92775. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  92776. }
  92777. // Expand the texture if possible
  92778. if (expandTexture) {
  92779. // Simply run through the decode PP
  92780. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  92781. texture._isRGBD = false;
  92782. texture.invertY = false;
  92783. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  92784. generateDepthBuffer: false,
  92785. generateMipMaps: true,
  92786. generateStencilBuffer: false,
  92787. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  92788. type: texture.type,
  92789. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  92790. });
  92791. }
  92792. else {
  92793. texture._isRGBD = true;
  92794. texture.invertY = true;
  92795. // In case of missing support, applies the same patch than DDS files.
  92796. if (generateNonLODTextures) {
  92797. var mipSlices = 3;
  92798. var scale = texture._lodGenerationScale;
  92799. var offset = texture._lodGenerationOffset;
  92800. for (var i = 0; i < mipSlices; i++) {
  92801. //compute LOD from even spacing in smoothness (matching shader calculation)
  92802. var smoothness = i / (mipSlices - 1);
  92803. var roughness = 1 - smoothness;
  92804. var minLODIndex = offset; // roughness = 0
  92805. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  92806. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  92807. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  92808. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  92809. glTextureFromLod.isCube = true;
  92810. glTextureFromLod.invertY = true;
  92811. glTextureFromLod.generateMipMaps = false;
  92812. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  92813. // Wrap in a base texture for easy binding.
  92814. var lodTexture = new BABYLON.BaseTexture(null);
  92815. lodTexture.isCube = true;
  92816. lodTexture._texture = glTextureFromLod;
  92817. lodTextures[mipmapIndex] = lodTexture;
  92818. switch (i) {
  92819. case 0:
  92820. texture._lodTextureLow = lodTexture;
  92821. break;
  92822. case 1:
  92823. texture._lodTextureMid = lodTexture;
  92824. break;
  92825. case 2:
  92826. texture._lodTextureHigh = lodTexture;
  92827. break;
  92828. }
  92829. }
  92830. }
  92831. }
  92832. var promises = [];
  92833. var _loop_3 = function (i) {
  92834. var _loop_4 = function (face) {
  92835. // Constructs an image element from image data
  92836. var bytes = imageData[i][face];
  92837. var blob = new Blob([bytes], { type: 'image/png' });
  92838. var url = URL.createObjectURL(blob);
  92839. var image = new Image();
  92840. image.src = url;
  92841. // Enqueue promise to upload to the texture.
  92842. var promise = new Promise(function (resolve, reject) {
  92843. image.onload = function () {
  92844. if (expandTexture) {
  92845. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  92846. reject(message);
  92847. }, image);
  92848. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  92849. // Uncompress the data to a RTT
  92850. rgbdPostProcess.onApply = function (effect) {
  92851. effect._bindTexture("textureSampler", tempTexture_1);
  92852. effect.setFloat2("scale", 1, 1);
  92853. };
  92854. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  92855. // Cleanup
  92856. engine.restoreDefaultFramebuffer();
  92857. tempTexture_1.dispose();
  92858. window.URL.revokeObjectURL(url);
  92859. resolve();
  92860. });
  92861. }
  92862. else {
  92863. engine._uploadImageToTexture(texture, image, face, i);
  92864. // Upload the face to the non lod texture support
  92865. if (generateNonLODTextures) {
  92866. var lodTexture = lodTextures[i];
  92867. if (lodTexture) {
  92868. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  92869. }
  92870. }
  92871. resolve();
  92872. }
  92873. };
  92874. image.onerror = function (error) {
  92875. reject(error);
  92876. };
  92877. });
  92878. promises.push(promise);
  92879. };
  92880. // All faces
  92881. for (var face = 0; face < 6; face++) {
  92882. _loop_4(face);
  92883. }
  92884. };
  92885. // All mipmaps up to provided number of images
  92886. for (var i = 0; i < imageData.length; i++) {
  92887. _loop_3(i);
  92888. }
  92889. // Fill remaining mipmaps with black textures.
  92890. if (imageData.length < mipmapsCount) {
  92891. var data = void 0;
  92892. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  92893. var dataLength = size * size * 4;
  92894. switch (texture.type) {
  92895. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  92896. data = new Uint8Array(dataLength);
  92897. break;
  92898. }
  92899. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  92900. data = new Uint16Array(dataLength);
  92901. break;
  92902. }
  92903. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  92904. data = new Float32Array(dataLength);
  92905. break;
  92906. }
  92907. }
  92908. for (var i = imageData.length; i < mipmapsCount; i++) {
  92909. for (var face = 0; face < 6; face++) {
  92910. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  92911. }
  92912. }
  92913. }
  92914. // Once all done, finishes the cleanup and return
  92915. return Promise.all(promises).then(function () {
  92916. // Release temp RTT.
  92917. if (cubeRtt) {
  92918. engine._releaseFramebufferObjects(cubeRtt);
  92919. cubeRtt._swapAndDie(texture);
  92920. }
  92921. // Release temp Post Process.
  92922. if (rgbdPostProcess) {
  92923. rgbdPostProcess.dispose();
  92924. }
  92925. // Flag internal texture as ready in case they are in use.
  92926. if (generateNonLODTextures) {
  92927. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  92928. texture._lodTextureHigh._texture.isReady = true;
  92929. }
  92930. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  92931. texture._lodTextureMid._texture.isReady = true;
  92932. }
  92933. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  92934. texture._lodTextureLow._texture.isReady = true;
  92935. }
  92936. }
  92937. });
  92938. };
  92939. /**
  92940. * Uploads spherical polynomials information to the texture.
  92941. * @param texture defines the texture we are trying to upload the information to
  92942. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  92943. */
  92944. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  92945. if (info.version !== 1) {
  92946. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  92947. }
  92948. var irradianceInfo = info.irradiance;
  92949. if (!irradianceInfo) {
  92950. return;
  92951. }
  92952. var sp = new BABYLON.SphericalPolynomial();
  92953. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  92954. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  92955. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  92956. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  92957. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  92958. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  92959. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  92960. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  92961. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  92962. texture._sphericalPolynomial = sp;
  92963. };
  92964. /**
  92965. * Magic number identifying the env file.
  92966. */
  92967. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  92968. return EnvironmentTextureTools;
  92969. }());
  92970. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  92971. })(BABYLON || (BABYLON = {}));
  92972. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  92973. var BABYLON;
  92974. (function (BABYLON) {
  92975. /**
  92976. * Implementation of the ENV Texture Loader.
  92977. */
  92978. var ENVTextureLoader = /** @class */ (function () {
  92979. function ENVTextureLoader() {
  92980. /**
  92981. * Defines wether the loader supports cascade loading the different faces.
  92982. */
  92983. this.supportCascades = false;
  92984. }
  92985. /**
  92986. * This returns if the loader support the current file information.
  92987. * @param extension defines the file extension of the file being loaded
  92988. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92989. * @param fallback defines the fallback internal texture if any
  92990. * @param isBase64 defines whether the texture is encoded as a base64
  92991. * @param isBuffer defines whether the texture data are stored as a buffer
  92992. * @returns true if the loader can load the specified file
  92993. */
  92994. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92995. return extension.indexOf(".env") === 0;
  92996. };
  92997. /**
  92998. * Transform the url before loading if required.
  92999. * @param rootUrl the url of the texture
  93000. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93001. * @returns the transformed texture
  93002. */
  93003. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  93004. return rootUrl;
  93005. };
  93006. /**
  93007. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  93008. * @param rootUrl the url of the texture
  93009. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93010. * @returns the fallback texture
  93011. */
  93012. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  93013. return null;
  93014. };
  93015. /**
  93016. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  93017. * @param data contains the texture data
  93018. * @param texture defines the BabylonJS internal texture
  93019. * @param createPolynomials will be true if polynomials have been requested
  93020. * @param onLoad defines the callback to trigger once the texture is ready
  93021. * @param onError defines the callback to trigger in case of error
  93022. */
  93023. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  93024. if (Array.isArray(data)) {
  93025. return;
  93026. }
  93027. data = data;
  93028. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  93029. if (info) {
  93030. texture.width = info.width;
  93031. texture.height = info.width;
  93032. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  93033. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  93034. texture.isReady = true;
  93035. if (onLoad) {
  93036. onLoad();
  93037. }
  93038. });
  93039. }
  93040. else if (onError) {
  93041. onError("Can not parse the environment file", null);
  93042. }
  93043. };
  93044. /**
  93045. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  93046. * @param data contains the texture data
  93047. * @param texture defines the BabylonJS internal texture
  93048. * @param callback defines the method to call once ready to upload
  93049. */
  93050. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  93051. throw ".env not supported in 2d.";
  93052. };
  93053. return ENVTextureLoader;
  93054. }());
  93055. // Register the loader.
  93056. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  93057. })(BABYLON || (BABYLON = {}));
  93058. //# sourceMappingURL=babylon.envTextureLoader.js.map
  93059. var BABYLON;
  93060. (function (BABYLON) {
  93061. /**
  93062. * Renders a layer on top of an existing scene
  93063. */
  93064. var UtilityLayerRenderer = /** @class */ (function () {
  93065. /**
  93066. * Instantiates a UtilityLayerRenderer
  93067. * @param originalScene the original scene that will be rendered on top of
  93068. */
  93069. function UtilityLayerRenderer(
  93070. /** the original scene that will be rendered on top of */
  93071. originalScene) {
  93072. var _this = this;
  93073. this.originalScene = originalScene;
  93074. this._pointerCaptures = {};
  93075. this._lastPointerEvents = {};
  93076. /**
  93077. * If the utility layer should automatically be rendered on top of existing scene
  93078. */
  93079. this.shouldRender = true;
  93080. /**
  93081. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  93082. */
  93083. this.onlyCheckPointerDownEvents = true;
  93084. /**
  93085. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  93086. */
  93087. this.processAllEvents = false;
  93088. /**
  93089. * Observable raised when the pointer move from the utility layer scene to the main scene
  93090. */
  93091. this.onPointerOutObservable = new BABYLON.Observable();
  93092. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  93093. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  93094. this.utilityLayerScene._allowPostProcessClearColor = false;
  93095. originalScene.getEngine().scenes.pop();
  93096. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  93097. this.utilityLayerScene.detachControl();
  93098. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  93099. if (!_this.processAllEvents) {
  93100. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  93101. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  93102. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  93103. return;
  93104. }
  93105. }
  93106. var pointerEvent = (prePointerInfo.event);
  93107. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  93108. _this._pointerCaptures[pointerEvent.pointerId] = false;
  93109. return;
  93110. }
  93111. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  93112. if (!prePointerInfo.ray && utilityScenePick) {
  93113. prePointerInfo.ray = utilityScenePick.ray;
  93114. }
  93115. // always fire the prepointer oversvable
  93116. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  93117. // allow every non pointer down event to flow to the utility layer
  93118. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  93119. if (!prePointerInfo.skipOnPointerObservable) {
  93120. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  93121. }
  93122. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  93123. _this._pointerCaptures[pointerEvent.pointerId] = false;
  93124. }
  93125. return;
  93126. }
  93127. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  93128. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  93129. if (utilityScenePick && utilityScenePick.hit) {
  93130. if (!prePointerInfo.skipOnPointerObservable) {
  93131. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  93132. }
  93133. prePointerInfo.skipOnPointerObservable = true;
  93134. }
  93135. }
  93136. else {
  93137. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  93138. var pointerEvent_1 = (prePointerInfo.event);
  93139. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  93140. if (originalScenePick && utilityScenePick) {
  93141. // No pick in utility scene
  93142. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  93143. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  93144. // We touched an utility mesh present in the main scene
  93145. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  93146. prePointerInfo.skipOnPointerObservable = true;
  93147. }
  93148. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  93149. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  93150. }
  93151. }
  93152. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  93153. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  93154. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  93155. // If a previous utility layer set this, do not unset this
  93156. if (!prePointerInfo.skipOnPointerObservable) {
  93157. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  93158. }
  93159. }
  93160. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  93161. // We have a pick in both scenes but main is closer than utility
  93162. // We touched an utility mesh present in the main scene
  93163. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  93164. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  93165. prePointerInfo.skipOnPointerObservable = true;
  93166. }
  93167. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  93168. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  93169. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  93170. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  93171. }
  93172. }
  93173. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  93174. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  93175. }
  93176. }
  93177. }
  93178. });
  93179. // Render directly on top of existing scene without clearing
  93180. this.utilityLayerScene.autoClear = false;
  93181. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  93182. if (_this.shouldRender) {
  93183. _this.render();
  93184. }
  93185. });
  93186. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  93187. _this.dispose();
  93188. });
  93189. this._updateCamera();
  93190. }
  93191. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  93192. /**
  93193. * 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)
  93194. */
  93195. get: function () {
  93196. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  93197. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  93198. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  93199. UtilityLayerRenderer._DefaultUtilityLayer = null;
  93200. });
  93201. }
  93202. return UtilityLayerRenderer._DefaultUtilityLayer;
  93203. },
  93204. enumerable: true,
  93205. configurable: true
  93206. });
  93207. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  93208. /**
  93209. * 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)
  93210. */
  93211. get: function () {
  93212. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  93213. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  93214. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  93215. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  93216. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  93217. });
  93218. }
  93219. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  93220. },
  93221. enumerable: true,
  93222. configurable: true
  93223. });
  93224. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  93225. if (!prePointerInfo.skipOnPointerObservable) {
  93226. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  93227. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  93228. }
  93229. };
  93230. /**
  93231. * Renders the utility layers scene on top of the original scene
  93232. */
  93233. UtilityLayerRenderer.prototype.render = function () {
  93234. this._updateCamera();
  93235. if (this.utilityLayerScene.activeCamera) {
  93236. // Set the camera's scene to utility layers scene
  93237. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  93238. var camera = this.utilityLayerScene.activeCamera;
  93239. camera._scene = this.utilityLayerScene;
  93240. if (camera.leftCamera) {
  93241. camera.leftCamera._scene = this.utilityLayerScene;
  93242. }
  93243. if (camera.rightCamera) {
  93244. camera.rightCamera._scene = this.utilityLayerScene;
  93245. }
  93246. this.utilityLayerScene.render(false);
  93247. // Reset camera's scene back to original
  93248. camera._scene = oldScene;
  93249. if (camera.leftCamera) {
  93250. camera.leftCamera._scene = oldScene;
  93251. }
  93252. if (camera.rightCamera) {
  93253. camera.rightCamera._scene = oldScene;
  93254. }
  93255. }
  93256. };
  93257. /**
  93258. * Disposes of the renderer
  93259. */
  93260. UtilityLayerRenderer.prototype.dispose = function () {
  93261. this.onPointerOutObservable.clear();
  93262. if (this._afterRenderObserver) {
  93263. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  93264. }
  93265. if (this._sceneDisposeObserver) {
  93266. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  93267. }
  93268. if (this._originalPointerObserver) {
  93269. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  93270. }
  93271. this.utilityLayerScene.dispose();
  93272. };
  93273. UtilityLayerRenderer.prototype._updateCamera = function () {
  93274. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  93275. };
  93276. UtilityLayerRenderer._DefaultUtilityLayer = null;
  93277. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  93278. return UtilityLayerRenderer;
  93279. }());
  93280. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  93281. })(BABYLON || (BABYLON = {}));
  93282. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  93283. //# sourceMappingURL=babylon.behavior.js.map
  93284. var BABYLON;
  93285. (function (BABYLON) {
  93286. /**
  93287. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  93288. */
  93289. var PointerDragBehavior = /** @class */ (function () {
  93290. /**
  93291. * Creates a pointer drag behavior that can be attached to a mesh
  93292. * @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)
  93293. */
  93294. function PointerDragBehavior(options) {
  93295. /**
  93296. * 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)
  93297. */
  93298. this.maxDragAngle = 0;
  93299. /**
  93300. * @hidden
  93301. */
  93302. this._useAlternatePickedPointAboveMaxDragAngle = false;
  93303. /**
  93304. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  93305. */
  93306. this.currentDraggingPointerID = -1;
  93307. /**
  93308. * If the behavior is currently in a dragging state
  93309. */
  93310. this.dragging = false;
  93311. /**
  93312. * 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)
  93313. */
  93314. this.dragDeltaRatio = 0.2;
  93315. /**
  93316. * If the drag plane orientation should be updated during the dragging (Default: true)
  93317. */
  93318. this.updateDragPlane = true;
  93319. // Debug mode will display drag planes to help visualize behavior
  93320. this._debugMode = false;
  93321. this._moving = false;
  93322. /**
  93323. * Fires each time the attached mesh is dragged with the pointer
  93324. * * delta between last drag position and current drag position in world space
  93325. * * dragDistance along the drag axis
  93326. * * dragPlaneNormal normal of the current drag plane used during the drag
  93327. * * dragPlanePoint in world space where the drag intersects the drag plane
  93328. */
  93329. this.onDragObservable = new BABYLON.Observable();
  93330. /**
  93331. * Fires each time a drag begins (eg. mouse down on mesh)
  93332. */
  93333. this.onDragStartObservable = new BABYLON.Observable();
  93334. /**
  93335. * Fires each time a drag ends (eg. mouse release after drag)
  93336. */
  93337. this.onDragEndObservable = new BABYLON.Observable();
  93338. /**
  93339. * If the attached mesh should be moved when dragged
  93340. */
  93341. this.moveAttached = true;
  93342. /**
  93343. * If the drag behavior will react to drag events (Default: true)
  93344. */
  93345. this.enabled = true;
  93346. /**
  93347. * If camera controls should be detached during the drag
  93348. */
  93349. this.detachCameraControls = true;
  93350. /**
  93351. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  93352. */
  93353. this.useObjectOrienationForDragging = true;
  93354. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  93355. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  93356. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  93357. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  93358. this._attachedElement = null;
  93359. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  93360. this._lastPointerRay = {};
  93361. this._dragDelta = new BABYLON.Vector3();
  93362. // Variables to avoid instantiation in the below method
  93363. this._pointA = new BABYLON.Vector3(0, 0, 0);
  93364. this._pointB = new BABYLON.Vector3(0, 0, 0);
  93365. this._pointC = new BABYLON.Vector3(0, 0, 0);
  93366. this._lineA = new BABYLON.Vector3(0, 0, 0);
  93367. this._lineB = new BABYLON.Vector3(0, 0, 0);
  93368. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  93369. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  93370. this._options = options ? options : {};
  93371. var optionCount = 0;
  93372. if (this._options.dragAxis) {
  93373. optionCount++;
  93374. }
  93375. if (this._options.dragPlaneNormal) {
  93376. optionCount++;
  93377. }
  93378. if (optionCount > 1) {
  93379. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  93380. }
  93381. }
  93382. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  93383. /**
  93384. * The name of the behavior
  93385. */
  93386. get: function () {
  93387. return "PointerDrag";
  93388. },
  93389. enumerable: true,
  93390. configurable: true
  93391. });
  93392. /**
  93393. * Initializes the behavior
  93394. */
  93395. PointerDragBehavior.prototype.init = function () { };
  93396. /**
  93397. * Attaches the drag behavior the passed in mesh
  93398. * @param ownerNode The mesh that will be dragged around once attached
  93399. */
  93400. PointerDragBehavior.prototype.attach = function (ownerNode) {
  93401. var _this = this;
  93402. this._scene = ownerNode.getScene();
  93403. this._attachedNode = ownerNode;
  93404. // Initialize drag plane to not interfere with existing scene
  93405. if (!PointerDragBehavior._planeScene) {
  93406. if (this._debugMode) {
  93407. PointerDragBehavior._planeScene = this._scene;
  93408. }
  93409. else {
  93410. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  93411. PointerDragBehavior._planeScene.detachControl();
  93412. this._scene.getEngine().scenes.pop();
  93413. this._scene.onDisposeObservable.addOnce(function () {
  93414. PointerDragBehavior._planeScene.dispose();
  93415. PointerDragBehavior._planeScene = null;
  93416. });
  93417. }
  93418. }
  93419. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  93420. // State of the drag
  93421. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  93422. var pickPredicate = function (m) {
  93423. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  93424. };
  93425. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  93426. if (!_this.enabled) {
  93427. return;
  93428. }
  93429. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93430. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  93431. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  93432. }
  93433. }
  93434. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  93435. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  93436. _this.releaseDrag();
  93437. }
  93438. }
  93439. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  93440. var pointerId = pointerInfo.event.pointerId;
  93441. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  93442. if (!_this._lastPointerRay[pointerId]) {
  93443. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  93444. }
  93445. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  93446. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  93447. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  93448. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  93449. _this._moveDrag(pointerInfo.pickInfo.ray);
  93450. }
  93451. }
  93452. }
  93453. });
  93454. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  93455. if (_this._moving && _this.moveAttached) {
  93456. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  93457. // Slowly move mesh to avoid jitter
  93458. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  93459. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  93460. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  93461. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  93462. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  93463. }
  93464. });
  93465. };
  93466. PointerDragBehavior.prototype.releaseDrag = function () {
  93467. this.dragging = false;
  93468. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  93469. this.currentDraggingPointerID = -1;
  93470. this._moving = false;
  93471. // Reattach camera controls
  93472. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  93473. this._scene.activeCamera.attachControl(this._attachedElement, true);
  93474. }
  93475. };
  93476. /**
  93477. * Simulates the start of a pointer drag event on the behavior
  93478. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  93479. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  93480. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  93481. */
  93482. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  93483. if (pointerId === void 0) { pointerId = 1; }
  93484. this._startDrag(pointerId, fromRay, startPickedPoint);
  93485. if (this._lastPointerRay[pointerId]) {
  93486. // if there was a last pointer ray drag the object there
  93487. this._moveDrag(this._lastPointerRay[pointerId]);
  93488. }
  93489. };
  93490. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  93491. if (pointerId === void 0) { pointerId = 1; }
  93492. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  93493. return;
  93494. }
  93495. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  93496. // Create start ray from the camera to the object
  93497. if (fromRay) {
  93498. this._startDragRay.direction.copyFrom(fromRay.direction);
  93499. this._startDragRay.origin.copyFrom(fromRay.origin);
  93500. }
  93501. else {
  93502. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  93503. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  93504. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  93505. }
  93506. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  93507. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  93508. if (pickedPoint) {
  93509. this.dragging = true;
  93510. this.currentDraggingPointerID = pointerId;
  93511. this.lastDragPosition.copyFrom(pickedPoint);
  93512. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  93513. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  93514. // Detatch camera controls
  93515. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  93516. if (this._scene.activeCamera.inputs.attachedElement) {
  93517. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  93518. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  93519. }
  93520. else {
  93521. this._attachedElement = null;
  93522. }
  93523. }
  93524. }
  93525. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  93526. };
  93527. PointerDragBehavior.prototype._moveDrag = function (ray) {
  93528. this._moving = true;
  93529. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  93530. if (pickedPoint) {
  93531. if (this.updateDragPlane) {
  93532. this._updateDragPlanePosition(ray, pickedPoint);
  93533. }
  93534. var dragLength = 0;
  93535. // depending on the drag mode option drag accordingly
  93536. if (this._options.dragAxis) {
  93537. // Convert local drag axis to world
  93538. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  93539. // Project delta drag from the drag plane onto the drag axis
  93540. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  93541. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  93542. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  93543. }
  93544. else {
  93545. dragLength = this._dragDelta.length();
  93546. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  93547. }
  93548. this._targetPosition.addInPlace(this._dragDelta);
  93549. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  93550. this.lastDragPosition.copyFrom(pickedPoint);
  93551. }
  93552. };
  93553. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  93554. var _this = this;
  93555. if (!ray) {
  93556. return null;
  93557. }
  93558. // Calculate angle between plane normal and ray
  93559. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  93560. // Correct if ray is casted from oposite side
  93561. if (angle > Math.PI / 2) {
  93562. angle = Math.PI - angle;
  93563. }
  93564. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  93565. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  93566. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  93567. // Invert ray direction along the towards object axis
  93568. this._tmpVector.copyFrom(ray.direction);
  93569. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  93570. this._alternatePickedPoint.normalize();
  93571. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  93572. this._tmpVector.addInPlace(this._alternatePickedPoint);
  93573. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  93574. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  93575. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  93576. this._alternatePickedPoint.addInPlace(this._tmpVector);
  93577. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  93578. return this._alternatePickedPoint;
  93579. }
  93580. else {
  93581. return null;
  93582. }
  93583. }
  93584. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  93585. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  93586. return pickResult.pickedPoint;
  93587. }
  93588. else {
  93589. return null;
  93590. }
  93591. };
  93592. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  93593. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  93594. this._pointA.copyFrom(dragPlanePosition);
  93595. if (this._options.dragAxis) {
  93596. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  93597. // Calculate plane normal in direction of camera but perpendicular to drag axis
  93598. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  93599. ray.origin.subtractToRef(this._pointA, this._pointC);
  93600. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  93601. // Get perpendicular line from direction to camera and drag axis
  93602. this._pointB.subtractToRef(this._pointA, this._lineA);
  93603. this._pointC.subtractToRef(this._pointA, this._lineB);
  93604. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  93605. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  93606. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  93607. this._lookAt.normalize();
  93608. this._dragPlane.position.copyFrom(this._pointA);
  93609. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  93610. this._dragPlane.lookAt(this._lookAt);
  93611. }
  93612. else if (this._options.dragPlaneNormal) {
  93613. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  93614. this._dragPlane.position.copyFrom(this._pointA);
  93615. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  93616. this._dragPlane.lookAt(this._lookAt);
  93617. }
  93618. else {
  93619. this._dragPlane.position.copyFrom(this._pointA);
  93620. this._dragPlane.lookAt(ray.origin);
  93621. }
  93622. this._dragPlane.computeWorldMatrix(true);
  93623. };
  93624. /**
  93625. * Detaches the behavior from the mesh
  93626. */
  93627. PointerDragBehavior.prototype.detach = function () {
  93628. if (this._pointerObserver) {
  93629. this._scene.onPointerObservable.remove(this._pointerObserver);
  93630. }
  93631. if (this._beforeRenderObserver) {
  93632. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  93633. }
  93634. };
  93635. return PointerDragBehavior;
  93636. }());
  93637. BABYLON.PointerDragBehavior = PointerDragBehavior;
  93638. })(BABYLON || (BABYLON = {}));
  93639. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  93640. var BABYLON;
  93641. (function (BABYLON) {
  93642. /**
  93643. * A behavior that when attached to a mesh will allow the mesh to be scaled
  93644. */
  93645. var MultiPointerScaleBehavior = /** @class */ (function () {
  93646. function MultiPointerScaleBehavior() {
  93647. this._startDistance = 0;
  93648. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  93649. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  93650. this._sceneRenderObserver = null;
  93651. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  93652. this._dragBehaviorA.moveAttached = false;
  93653. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  93654. this._dragBehaviorB.moveAttached = false;
  93655. }
  93656. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  93657. /**
  93658. * The name of the behavior
  93659. */
  93660. get: function () {
  93661. return "MultiPointerScale";
  93662. },
  93663. enumerable: true,
  93664. configurable: true
  93665. });
  93666. /**
  93667. * Initializes the behavior
  93668. */
  93669. MultiPointerScaleBehavior.prototype.init = function () { };
  93670. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  93671. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  93672. };
  93673. /**
  93674. * Attaches the scale behavior the passed in mesh
  93675. * @param ownerNode The mesh that will be scaled around once attached
  93676. */
  93677. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  93678. var _this = this;
  93679. this._ownerNode = ownerNode;
  93680. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  93681. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  93682. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93683. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  93684. _this._dragBehaviorA.releaseDrag();
  93685. }
  93686. else {
  93687. _this._initialScale.copyFrom(ownerNode.scaling);
  93688. _this._startDistance = _this._getCurrentDistance();
  93689. }
  93690. }
  93691. });
  93692. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  93693. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93694. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  93695. _this._dragBehaviorB.releaseDrag();
  93696. }
  93697. else {
  93698. _this._initialScale.copyFrom(ownerNode.scaling);
  93699. _this._startDistance = _this._getCurrentDistance();
  93700. }
  93701. }
  93702. });
  93703. // Once both drag behaviors are active scale based on the distance between the two pointers
  93704. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  93705. behavior.onDragObservable.add(function () {
  93706. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93707. var ratio = _this._getCurrentDistance() / _this._startDistance;
  93708. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  93709. }
  93710. });
  93711. });
  93712. ownerNode.addBehavior(this._dragBehaviorA);
  93713. ownerNode.addBehavior(this._dragBehaviorB);
  93714. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  93715. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  93716. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93717. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  93718. if (change.length() > 0.01) {
  93719. ownerNode.scaling.addInPlace(change);
  93720. }
  93721. }
  93722. });
  93723. };
  93724. /**
  93725. * Detaches the behavior from the mesh
  93726. */
  93727. MultiPointerScaleBehavior.prototype.detach = function () {
  93728. var _this = this;
  93729. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  93730. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  93731. behavior.onDragStartObservable.clear();
  93732. behavior.onDragObservable.clear();
  93733. _this._ownerNode.removeBehavior(behavior);
  93734. });
  93735. };
  93736. return MultiPointerScaleBehavior;
  93737. }());
  93738. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  93739. })(BABYLON || (BABYLON = {}));
  93740. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  93741. var BABYLON;
  93742. (function (BABYLON) {
  93743. /**
  93744. * 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
  93745. */
  93746. var SixDofDragBehavior = /** @class */ (function () {
  93747. function SixDofDragBehavior() {
  93748. this._sceneRenderObserver = null;
  93749. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  93750. this._moving = false;
  93751. this._startingOrientation = new BABYLON.Quaternion();
  93752. /**
  93753. * 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)
  93754. */
  93755. this.zDragFactor = 3;
  93756. /**
  93757. * If the behavior is currently in a dragging state
  93758. */
  93759. this.dragging = false;
  93760. /**
  93761. * 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)
  93762. */
  93763. this.dragDeltaRatio = 0.2;
  93764. /**
  93765. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  93766. */
  93767. this.currentDraggingPointerID = -1;
  93768. /**
  93769. * If camera controls should be detached during the drag
  93770. */
  93771. this.detachCameraControls = true;
  93772. }
  93773. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  93774. /**
  93775. * The name of the behavior
  93776. */
  93777. get: function () {
  93778. return "SixDofDrag";
  93779. },
  93780. enumerable: true,
  93781. configurable: true
  93782. });
  93783. /**
  93784. * Initializes the behavior
  93785. */
  93786. SixDofDragBehavior.prototype.init = function () { };
  93787. /**
  93788. * Attaches the scale behavior the passed in mesh
  93789. * @param ownerNode The mesh that will be scaled around once attached
  93790. */
  93791. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  93792. var _this = this;
  93793. this._ownerNode = ownerNode;
  93794. this._scene = this._ownerNode.getScene();
  93795. if (!SixDofDragBehavior._virtualScene) {
  93796. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  93797. this._scene.getEngine().scenes.pop();
  93798. }
  93799. var pickedMesh = null;
  93800. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  93801. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  93802. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  93803. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  93804. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  93805. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  93806. var pickPredicate = function (m) {
  93807. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  93808. };
  93809. var attachedElement = null;
  93810. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  93811. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93812. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  93813. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  93814. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  93815. }
  93816. pickedMesh = _this._ownerNode;
  93817. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93818. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  93819. // Set position and orientation of the controller
  93820. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93821. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93822. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  93823. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93824. pickedMesh.computeWorldMatrix();
  93825. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  93826. if (!pickedMesh.rotationQuaternion) {
  93827. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  93828. }
  93829. var oldParent = pickedMesh.parent;
  93830. pickedMesh.setParent(null);
  93831. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  93832. pickedMesh.setParent(oldParent);
  93833. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93834. // Update state
  93835. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93836. _this.dragging = true;
  93837. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  93838. // Detatch camera controls
  93839. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93840. if (_this._scene.activeCamera.inputs.attachedElement) {
  93841. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  93842. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  93843. }
  93844. else {
  93845. attachedElement = null;
  93846. }
  93847. }
  93848. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93849. }
  93850. }
  93851. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  93852. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  93853. _this.dragging = false;
  93854. _this._moving = false;
  93855. _this.currentDraggingPointerID = -1;
  93856. pickedMesh = null;
  93857. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93858. // Reattach camera controls
  93859. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93860. _this._scene.activeCamera.attachControl(attachedElement, true);
  93861. }
  93862. }
  93863. }
  93864. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  93865. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  93866. var zDragFactor = _this.zDragFactor;
  93867. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  93868. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  93869. zDragFactor = 0;
  93870. }
  93871. // Calculate controller drag distance in controller space
  93872. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  93873. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  93874. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  93875. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93876. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  93877. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  93878. if (_this._virtualDragMesh.position.z < 0) {
  93879. _this._virtualDragMesh.position.z = 0;
  93880. }
  93881. // Update the controller position
  93882. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93883. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93884. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93885. // Move the virtualObjectsPosition into the picked mesh's space if needed
  93886. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93887. if (pickedMesh.parent) {
  93888. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  93889. }
  93890. if (!_this._moving) {
  93891. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  93892. }
  93893. _this._moving = true;
  93894. }
  93895. }
  93896. });
  93897. var tmpQuaternion = new BABYLON.Quaternion();
  93898. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  93899. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  93900. if (_this.dragging && _this._moving && pickedMesh) {
  93901. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93902. // Slowly move mesh to avoid jitter
  93903. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  93904. // Get change in rotation
  93905. tmpQuaternion.copyFrom(_this._startingOrientation);
  93906. tmpQuaternion.x = -tmpQuaternion.x;
  93907. tmpQuaternion.y = -tmpQuaternion.y;
  93908. tmpQuaternion.z = -tmpQuaternion.z;
  93909. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  93910. // Convert change in rotation to only y axis rotation
  93911. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  93912. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  93913. // Slowly move mesh to avoid jitter
  93914. var oldParent = pickedMesh.parent;
  93915. pickedMesh.setParent(null);
  93916. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  93917. pickedMesh.setParent(oldParent);
  93918. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93919. }
  93920. });
  93921. };
  93922. /**
  93923. * Detaches the behavior from the mesh
  93924. */
  93925. SixDofDragBehavior.prototype.detach = function () {
  93926. if (this._scene) {
  93927. this._scene.onPointerObservable.remove(this._pointerObserver);
  93928. }
  93929. if (this._ownerNode) {
  93930. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  93931. }
  93932. if (this._virtualOriginMesh) {
  93933. this._virtualOriginMesh.dispose();
  93934. }
  93935. if (this._virtualDragMesh) {
  93936. this._virtualDragMesh.dispose();
  93937. }
  93938. };
  93939. return SixDofDragBehavior;
  93940. }());
  93941. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  93942. })(BABYLON || (BABYLON = {}));
  93943. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  93944. var BABYLON;
  93945. (function (BABYLON) {
  93946. /**
  93947. * @hidden
  93948. */
  93949. var FaceDirectionInfo = /** @class */ (function () {
  93950. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  93951. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  93952. if (diff === void 0) { diff = 0; }
  93953. if (ignore === void 0) { ignore = false; }
  93954. this.direction = direction;
  93955. this.rotatedDirection = rotatedDirection;
  93956. this.diff = diff;
  93957. this.ignore = ignore;
  93958. }
  93959. return FaceDirectionInfo;
  93960. }());
  93961. /**
  93962. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  93963. */
  93964. var AttachToBoxBehavior = /** @class */ (function () {
  93965. /**
  93966. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  93967. * @param ui The transform node that should be attched to the mesh
  93968. */
  93969. function AttachToBoxBehavior(ui) {
  93970. this.ui = ui;
  93971. /**
  93972. * The name of the behavior
  93973. */
  93974. this.name = "AttachToBoxBehavior";
  93975. /**
  93976. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  93977. */
  93978. this.distanceAwayFromFace = 0.15;
  93979. /**
  93980. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  93981. */
  93982. this.distanceAwayFromBottomOfFace = 0.15;
  93983. 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))];
  93984. this._tmpMatrix = new BABYLON.Matrix();
  93985. this._tmpVector = new BABYLON.Vector3();
  93986. this._zeroVector = BABYLON.Vector3.Zero();
  93987. this._lookAtTmpMatrix = new BABYLON.Matrix();
  93988. /* Does nothing */
  93989. }
  93990. /**
  93991. * Initializes the behavior
  93992. */
  93993. AttachToBoxBehavior.prototype.init = function () {
  93994. /* Does nothing */
  93995. };
  93996. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  93997. var _this = this;
  93998. // Go over each face and calculate the angle between the face's normal and targetDirection
  93999. this._faceVectors.forEach(function (v) {
  94000. if (!_this._target.rotationQuaternion) {
  94001. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  94002. }
  94003. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  94004. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  94005. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  94006. });
  94007. // Return the face information of the one with the normal closeset to target direction
  94008. return this._faceVectors.reduce(function (min, p) {
  94009. if (min.ignore) {
  94010. return p;
  94011. }
  94012. else if (p.ignore) {
  94013. return min;
  94014. }
  94015. else {
  94016. return min.diff < p.diff ? min : p;
  94017. }
  94018. }, this._faceVectors[0]);
  94019. };
  94020. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  94021. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  94022. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  94023. this._lookAtTmpMatrix.invert();
  94024. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  94025. };
  94026. /**
  94027. * Attaches the AttachToBoxBehavior to the passed in mesh
  94028. * @param target The mesh that the specified node will be attached to
  94029. */
  94030. AttachToBoxBehavior.prototype.attach = function (target) {
  94031. var _this = this;
  94032. this._target = target;
  94033. this._scene = this._target.getScene();
  94034. // Every frame, update the app bars position
  94035. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  94036. if (!_this._scene.activeCamera) {
  94037. return;
  94038. }
  94039. // Find the face closest to the cameras position
  94040. var cameraPos = _this._scene.activeCamera.position;
  94041. if (_this._scene.activeCamera.devicePosition) {
  94042. cameraPos = _this._scene.activeCamera.devicePosition;
  94043. }
  94044. var facing = _this._closestFace(cameraPos.subtract(target.position));
  94045. if (_this._scene.activeCamera.leftCamera) {
  94046. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  94047. }
  94048. else {
  94049. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  94050. }
  94051. // Get camera up direction
  94052. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  94053. // Ignore faces to not select a parrelel face for the up vector of the UI
  94054. _this._faceVectors.forEach(function (v) {
  94055. if (facing.direction.x && v.direction.x) {
  94056. v.ignore = true;
  94057. }
  94058. if (facing.direction.y && v.direction.y) {
  94059. v.ignore = true;
  94060. }
  94061. if (facing.direction.z && v.direction.z) {
  94062. v.ignore = true;
  94063. }
  94064. });
  94065. var facingUp = _this._closestFace(_this._tmpVector);
  94066. // Unignore faces
  94067. _this._faceVectors.forEach(function (v) {
  94068. v.ignore = false;
  94069. });
  94070. // Position the app bar on that face
  94071. _this.ui.position.copyFrom(target.position);
  94072. if (facing.direction.x) {
  94073. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  94074. _this.ui.position.addInPlace(_this._tmpVector);
  94075. }
  94076. if (facing.direction.y) {
  94077. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  94078. _this.ui.position.addInPlace(_this._tmpVector);
  94079. }
  94080. if (facing.direction.z) {
  94081. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  94082. _this.ui.position.addInPlace(_this._tmpVector);
  94083. }
  94084. // Rotate to be oriented properly to the camera
  94085. if (!_this.ui.rotationQuaternion) {
  94086. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  94087. }
  94088. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  94089. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  94090. // Place ui the correct distance from the bottom of the mesh
  94091. if (facingUp.direction.x) {
  94092. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  94093. }
  94094. if (facingUp.direction.y) {
  94095. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  94096. }
  94097. if (facingUp.direction.z) {
  94098. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  94099. }
  94100. _this.ui.position.addInPlace(_this._tmpVector);
  94101. });
  94102. };
  94103. /**
  94104. * Detaches the behavior from the mesh
  94105. */
  94106. AttachToBoxBehavior.prototype.detach = function () {
  94107. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  94108. };
  94109. return AttachToBoxBehavior;
  94110. }());
  94111. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  94112. })(BABYLON || (BABYLON = {}));
  94113. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  94114. var BABYLON;
  94115. (function (BABYLON) {
  94116. /**
  94117. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  94118. */
  94119. var FadeInOutBehavior = /** @class */ (function () {
  94120. /**
  94121. * Instatiates the FadeInOutBehavior
  94122. */
  94123. function FadeInOutBehavior() {
  94124. var _this = this;
  94125. /**
  94126. * Time in milliseconds to delay before fading in (Default: 0)
  94127. */
  94128. this.delay = 0;
  94129. /**
  94130. * Time in milliseconds for the mesh to fade in (Default: 300)
  94131. */
  94132. this.fadeInTime = 300;
  94133. this._millisecondsPerFrame = 1000 / 60;
  94134. this._hovered = false;
  94135. this._hoverValue = 0;
  94136. this._ownerNode = null;
  94137. this._update = function () {
  94138. if (_this._ownerNode) {
  94139. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  94140. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  94141. if (_this._ownerNode.visibility > 1) {
  94142. _this._setAllVisibility(_this._ownerNode, 1);
  94143. _this._hoverValue = _this.fadeInTime + _this.delay;
  94144. return;
  94145. }
  94146. else if (_this._ownerNode.visibility < 0) {
  94147. _this._setAllVisibility(_this._ownerNode, 0);
  94148. if (_this._hoverValue < 0) {
  94149. _this._hoverValue = 0;
  94150. return;
  94151. }
  94152. }
  94153. setTimeout(_this._update, _this._millisecondsPerFrame);
  94154. }
  94155. };
  94156. }
  94157. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  94158. /**
  94159. * The name of the behavior
  94160. */
  94161. get: function () {
  94162. return "FadeInOut";
  94163. },
  94164. enumerable: true,
  94165. configurable: true
  94166. });
  94167. /**
  94168. * Initializes the behavior
  94169. */
  94170. FadeInOutBehavior.prototype.init = function () {
  94171. };
  94172. /**
  94173. * Attaches the fade behavior on the passed in mesh
  94174. * @param ownerNode The mesh that will be faded in/out once attached
  94175. */
  94176. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  94177. this._ownerNode = ownerNode;
  94178. this._setAllVisibility(this._ownerNode, 0);
  94179. };
  94180. /**
  94181. * Detaches the behavior from the mesh
  94182. */
  94183. FadeInOutBehavior.prototype.detach = function () {
  94184. this._ownerNode = null;
  94185. };
  94186. /**
  94187. * Triggers the mesh to begin fading in or out
  94188. * @param value if the object should fade in or out (true to fade in)
  94189. */
  94190. FadeInOutBehavior.prototype.fadeIn = function (value) {
  94191. this._hovered = value;
  94192. this._update();
  94193. };
  94194. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  94195. var _this = this;
  94196. mesh.visibility = value;
  94197. mesh.getChildMeshes().forEach(function (c) {
  94198. _this._setAllVisibility(c, value);
  94199. });
  94200. };
  94201. return FadeInOutBehavior;
  94202. }());
  94203. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  94204. })(BABYLON || (BABYLON = {}));
  94205. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  94206. var BABYLON;
  94207. (function (BABYLON) {
  94208. /**
  94209. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  94210. */
  94211. var Gizmo = /** @class */ (function () {
  94212. /**
  94213. * Creates a gizmo
  94214. * @param gizmoLayer The utility layer the gizmo will be added to
  94215. */
  94216. function Gizmo(
  94217. /** The utility layer the gizmo will be added to */
  94218. gizmoLayer) {
  94219. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94220. var _this = this;
  94221. this.gizmoLayer = gizmoLayer;
  94222. /**
  94223. * Ratio for the scale of the gizmo (Default: 1)
  94224. */
  94225. this.scaleRatio = 1;
  94226. this._tmpMatrix = new BABYLON.Matrix();
  94227. /**
  94228. * If a custom mesh has been set (Default: false)
  94229. */
  94230. this._customMeshSet = false;
  94231. /**
  94232. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  94233. */
  94234. this.updateGizmoRotationToMatchAttachedMesh = true;
  94235. /**
  94236. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  94237. */
  94238. this.updateGizmoPositionToMatchAttachedMesh = true;
  94239. /**
  94240. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  94241. */
  94242. this._updateScale = true;
  94243. this._interactionsEnabled = true;
  94244. this._tempVector = new BABYLON.Vector3();
  94245. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  94246. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  94247. _this._update();
  94248. });
  94249. this.attachedMesh = null;
  94250. }
  94251. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  94252. /**
  94253. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  94254. * * When set, interactions will be enabled
  94255. */
  94256. get: function () {
  94257. return this._attachedMesh;
  94258. },
  94259. set: function (value) {
  94260. this._attachedMesh = value;
  94261. this._rootMesh.setEnabled(value ? true : false);
  94262. this._attachedMeshChanged(value);
  94263. },
  94264. enumerable: true,
  94265. configurable: true
  94266. });
  94267. /**
  94268. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  94269. * @param mesh The mesh to replace the default mesh of the gizmo
  94270. */
  94271. Gizmo.prototype.setCustomMesh = function (mesh) {
  94272. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  94273. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  94274. }
  94275. this._rootMesh.getChildMeshes().forEach(function (c) {
  94276. c.dispose();
  94277. });
  94278. mesh.parent = this._rootMesh;
  94279. this._customMeshSet = true;
  94280. };
  94281. Gizmo.prototype._attachedMeshChanged = function (value) {
  94282. };
  94283. /**
  94284. * @hidden
  94285. * Updates the gizmo to match the attached mesh's position/rotation
  94286. */
  94287. Gizmo.prototype._update = function () {
  94288. if (this.attachedMesh) {
  94289. if (this.updateGizmoRotationToMatchAttachedMesh) {
  94290. if (!this._rootMesh.rotationQuaternion) {
  94291. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  94292. }
  94293. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  94294. this._tempVector.copyFrom(this.attachedMesh.scaling);
  94295. if (this.attachedMesh.scaling.x < 0) {
  94296. this.attachedMesh.scaling.x *= -1;
  94297. }
  94298. if (this.attachedMesh.scaling.y < 0) {
  94299. this.attachedMesh.scaling.y *= -1;
  94300. }
  94301. if (this.attachedMesh.scaling.z < 0) {
  94302. this.attachedMesh.scaling.z *= -1;
  94303. }
  94304. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  94305. this.attachedMesh.scaling.copyFrom(this._tempVector);
  94306. this.attachedMesh.computeWorldMatrix();
  94307. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  94308. }
  94309. else if (this._rootMesh.rotationQuaternion) {
  94310. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  94311. }
  94312. if (this.updateGizmoPositionToMatchAttachedMesh) {
  94313. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  94314. }
  94315. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  94316. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  94317. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  94318. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  94319. }
  94320. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  94321. var dist = this._tempVector.length() * this.scaleRatio;
  94322. this._rootMesh.scaling.set(dist, dist, dist);
  94323. }
  94324. }
  94325. };
  94326. /**
  94327. * Disposes of the gizmo
  94328. */
  94329. Gizmo.prototype.dispose = function () {
  94330. this._rootMesh.dispose();
  94331. if (this._beforeRenderObserver) {
  94332. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  94333. }
  94334. };
  94335. return Gizmo;
  94336. }());
  94337. BABYLON.Gizmo = Gizmo;
  94338. })(BABYLON || (BABYLON = {}));
  94339. //# sourceMappingURL=babylon.gizmo.js.map
  94340. var BABYLON;
  94341. (function (BABYLON) {
  94342. /**
  94343. * Single axis drag gizmo
  94344. */
  94345. var AxisDragGizmo = /** @class */ (function (_super) {
  94346. __extends(AxisDragGizmo, _super);
  94347. /**
  94348. * Creates an AxisDragGizmo
  94349. * @param gizmoLayer The utility layer the gizmo will be added to
  94350. * @param dragAxis The axis which the gizmo will be able to drag on
  94351. * @param color The color of the gizmo
  94352. */
  94353. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  94354. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94355. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94356. var _this = _super.call(this, gizmoLayer) || this;
  94357. _this._pointerObserver = null;
  94358. /**
  94359. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94360. */
  94361. _this.snapDistance = 0;
  94362. /**
  94363. * Event that fires each time the gizmo snaps to a new location.
  94364. * * snapDistance is the the change in distance
  94365. */
  94366. _this.onSnapObservable = new BABYLON.Observable();
  94367. // Create Material
  94368. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94369. coloredMaterial.disableLighting = true;
  94370. coloredMaterial.emissiveColor = color;
  94371. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94372. hoverMaterial.disableLighting = true;
  94373. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94374. // Build mesh on root node
  94375. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94376. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  94377. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  94378. arrowTail.color = coloredMaterial.emissiveColor;
  94379. arrow.addChild(arrowMesh);
  94380. arrow.addChild(arrowTail);
  94381. // Position arrow pointing in its drag axis
  94382. arrowMesh.scaling.scaleInPlace(0.05);
  94383. arrowMesh.material = coloredMaterial;
  94384. arrowMesh.rotation.x = Math.PI / 2;
  94385. arrowMesh.position.z += 0.3;
  94386. arrowTail.scaling.scaleInPlace(0.26);
  94387. arrowTail.rotation.x = Math.PI / 2;
  94388. arrowTail.material = coloredMaterial;
  94389. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  94390. arrow.scaling.scaleInPlace(1 / 3);
  94391. _this._rootMesh.addChild(arrow);
  94392. var currentSnapDragDistance = 0;
  94393. var tmpVector = new BABYLON.Vector3();
  94394. var tmpSnapEvent = { snapDistance: 0 };
  94395. // Add drag behavior to handle events when the gizmo is dragged
  94396. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94397. _this.dragBehavior.moveAttached = false;
  94398. _this._rootMesh.addBehavior(_this.dragBehavior);
  94399. var localDelta = new BABYLON.Vector3();
  94400. var tmpMatrix = new BABYLON.Matrix();
  94401. _this.dragBehavior.onDragObservable.add(function (event) {
  94402. if (_this.attachedMesh) {
  94403. // Convert delta to local translation if it has a parent
  94404. if (_this.attachedMesh.parent) {
  94405. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  94406. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  94407. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  94408. }
  94409. else {
  94410. localDelta.copyFrom(event.delta);
  94411. }
  94412. // Snapping logic
  94413. if (_this.snapDistance == 0) {
  94414. _this.attachedMesh.position.addInPlace(localDelta);
  94415. }
  94416. else {
  94417. currentSnapDragDistance += event.dragDistance;
  94418. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94419. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  94420. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94421. localDelta.normalizeToRef(tmpVector);
  94422. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  94423. _this.attachedMesh.position.addInPlace(tmpVector);
  94424. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  94425. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94426. }
  94427. }
  94428. }
  94429. });
  94430. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94431. if (_this._customMeshSet) {
  94432. return;
  94433. }
  94434. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94435. var material = isHovered ? hoverMaterial : coloredMaterial;
  94436. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94437. m.material = material;
  94438. if (m.color) {
  94439. m.color = material.emissiveColor;
  94440. }
  94441. });
  94442. });
  94443. return _this;
  94444. }
  94445. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  94446. if (this.dragBehavior) {
  94447. this.dragBehavior.enabled = value ? true : false;
  94448. }
  94449. };
  94450. /**
  94451. * Disposes of the gizmo
  94452. */
  94453. AxisDragGizmo.prototype.dispose = function () {
  94454. this.onSnapObservable.clear();
  94455. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94456. this.dragBehavior.detach();
  94457. _super.prototype.dispose.call(this);
  94458. };
  94459. return AxisDragGizmo;
  94460. }(BABYLON.Gizmo));
  94461. BABYLON.AxisDragGizmo = AxisDragGizmo;
  94462. })(BABYLON || (BABYLON = {}));
  94463. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  94464. var BABYLON;
  94465. (function (BABYLON) {
  94466. /**
  94467. * Single axis scale gizmo
  94468. */
  94469. var AxisScaleGizmo = /** @class */ (function (_super) {
  94470. __extends(AxisScaleGizmo, _super);
  94471. /**
  94472. * Creates an AxisScaleGizmo
  94473. * @param gizmoLayer The utility layer the gizmo will be added to
  94474. * @param dragAxis The axis which the gizmo will be able to scale on
  94475. * @param color The color of the gizmo
  94476. */
  94477. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  94478. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94479. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94480. var _this = _super.call(this, gizmoLayer) || this;
  94481. _this._pointerObserver = null;
  94482. /**
  94483. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94484. */
  94485. _this.snapDistance = 0;
  94486. /**
  94487. * Event that fires each time the gizmo snaps to a new location.
  94488. * * snapDistance is the the change in distance
  94489. */
  94490. _this.onSnapObservable = new BABYLON.Observable();
  94491. /**
  94492. * If the scaling operation should be done on all axis (default: false)
  94493. */
  94494. _this.uniformScaling = false;
  94495. // Create Material
  94496. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94497. _this._coloredMaterial.disableLighting = true;
  94498. _this._coloredMaterial.emissiveColor = color;
  94499. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94500. hoverMaterial.disableLighting = true;
  94501. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94502. // Build mesh on root node
  94503. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94504. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  94505. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  94506. arrowTail.color = _this._coloredMaterial.emissiveColor;
  94507. arrow.addChild(arrowMesh);
  94508. arrow.addChild(arrowTail);
  94509. // Position arrow pointing in its drag axis
  94510. arrowMesh.scaling.scaleInPlace(0.1);
  94511. arrowMesh.material = _this._coloredMaterial;
  94512. arrowMesh.rotation.x = Math.PI / 2;
  94513. arrowMesh.position.z += 0.3;
  94514. arrowTail.scaling.scaleInPlace(0.26);
  94515. arrowTail.rotation.x = Math.PI / 2;
  94516. arrowTail.material = _this._coloredMaterial;
  94517. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  94518. _this._rootMesh.addChild(arrow);
  94519. arrow.scaling.scaleInPlace(1 / 3);
  94520. // Add drag behavior to handle events when the gizmo is dragged
  94521. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94522. _this.dragBehavior.moveAttached = false;
  94523. _this._rootMesh.addBehavior(_this.dragBehavior);
  94524. var currentSnapDragDistance = 0;
  94525. var tmpVector = new BABYLON.Vector3();
  94526. var tmpSnapEvent = { snapDistance: 0 };
  94527. _this.dragBehavior.onDragObservable.add(function (event) {
  94528. if (_this.attachedMesh) {
  94529. // Snapping logic
  94530. var snapped = false;
  94531. var dragSteps = 0;
  94532. if (_this.uniformScaling) {
  94533. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  94534. if (tmpVector.y < 0) {
  94535. tmpVector.scaleInPlace(-1);
  94536. }
  94537. }
  94538. else {
  94539. tmpVector.copyFrom(dragAxis);
  94540. }
  94541. if (_this.snapDistance == 0) {
  94542. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  94543. }
  94544. else {
  94545. currentSnapDragDistance += event.dragDistance;
  94546. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94547. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  94548. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94549. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  94550. snapped = true;
  94551. }
  94552. else {
  94553. tmpVector.scaleInPlace(0);
  94554. }
  94555. }
  94556. _this.attachedMesh.scaling.addInPlace(tmpVector);
  94557. if (snapped) {
  94558. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  94559. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94560. }
  94561. }
  94562. });
  94563. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94564. if (_this._customMeshSet) {
  94565. return;
  94566. }
  94567. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94568. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  94569. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94570. m.material = material;
  94571. if (m.color) {
  94572. m.color = material.emissiveColor;
  94573. }
  94574. });
  94575. });
  94576. return _this;
  94577. }
  94578. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  94579. if (this.dragBehavior) {
  94580. this.dragBehavior.enabled = value ? true : false;
  94581. }
  94582. };
  94583. /**
  94584. * Disposes of the gizmo
  94585. */
  94586. AxisScaleGizmo.prototype.dispose = function () {
  94587. this.onSnapObservable.clear();
  94588. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94589. this.dragBehavior.detach();
  94590. _super.prototype.dispose.call(this);
  94591. };
  94592. /**
  94593. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  94594. * @param mesh The mesh to replace the default mesh of the gizmo
  94595. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  94596. */
  94597. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  94598. var _this = this;
  94599. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  94600. _super.prototype.setCustomMesh.call(this, mesh);
  94601. if (useGizmoMaterial) {
  94602. this._rootMesh.getChildMeshes().forEach(function (m) {
  94603. m.material = _this._coloredMaterial;
  94604. if (m.color) {
  94605. m.color = _this._coloredMaterial.emissiveColor;
  94606. }
  94607. });
  94608. this._customMeshSet = false;
  94609. }
  94610. };
  94611. return AxisScaleGizmo;
  94612. }(BABYLON.Gizmo));
  94613. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  94614. })(BABYLON || (BABYLON = {}));
  94615. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  94616. var BABYLON;
  94617. (function (BABYLON) {
  94618. /**
  94619. * Single plane rotation gizmo
  94620. */
  94621. var PlaneRotationGizmo = /** @class */ (function (_super) {
  94622. __extends(PlaneRotationGizmo, _super);
  94623. /**
  94624. * Creates a PlaneRotationGizmo
  94625. * @param gizmoLayer The utility layer the gizmo will be added to
  94626. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  94627. * @param color The color of the gizmo
  94628. */
  94629. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  94630. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94631. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94632. var _this = _super.call(this, gizmoLayer) || this;
  94633. _this._pointerObserver = null;
  94634. /**
  94635. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  94636. */
  94637. _this.snapDistance = 0;
  94638. /**
  94639. * Event that fires each time the gizmo snaps to a new location.
  94640. * * snapDistance is the the change in distance
  94641. */
  94642. _this.onSnapObservable = new BABYLON.Observable();
  94643. // Create Material
  94644. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94645. coloredMaterial.disableLighting = true;
  94646. coloredMaterial.emissiveColor = color;
  94647. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94648. hoverMaterial.disableLighting = true;
  94649. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94650. // Build mesh on root node
  94651. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94652. // Create circle out of lines
  94653. var tessellation = 20;
  94654. var radius = 0.8;
  94655. var points = new Array();
  94656. for (var i = 0; i < tessellation; i++) {
  94657. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  94658. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  94659. }
  94660. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  94661. rotationMesh.color = coloredMaterial.emissiveColor;
  94662. // Position arrow pointing in its drag axis
  94663. rotationMesh.scaling.scaleInPlace(0.26);
  94664. rotationMesh.material = coloredMaterial;
  94665. rotationMesh.rotation.x = Math.PI / 2;
  94666. parentMesh.addChild(rotationMesh);
  94667. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  94668. _this._rootMesh.addChild(parentMesh);
  94669. parentMesh.scaling.scaleInPlace(1 / 3);
  94670. // Add drag behavior to handle events when the gizmo is dragged
  94671. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  94672. _this.dragBehavior.moveAttached = false;
  94673. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  94674. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  94675. _this._rootMesh.addBehavior(_this.dragBehavior);
  94676. var lastDragPosition = new BABYLON.Vector3();
  94677. _this.dragBehavior.onDragStartObservable.add(function (e) {
  94678. if (_this.attachedMesh) {
  94679. lastDragPosition.copyFrom(e.dragPlanePoint);
  94680. }
  94681. });
  94682. var rotationMatrix = new BABYLON.Matrix();
  94683. var planeNormalTowardsCamera = new BABYLON.Vector3();
  94684. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  94685. var tmpSnapEvent = { snapDistance: 0 };
  94686. var currentSnapDragDistance = 0;
  94687. var tmpMatrix = new BABYLON.Matrix();
  94688. var tmpVector = new BABYLON.Vector3();
  94689. var amountToRotate = new BABYLON.Quaternion();
  94690. _this.dragBehavior.onDragObservable.add(function (event) {
  94691. if (_this.attachedMesh) {
  94692. if (!_this.attachedMesh.rotationQuaternion) {
  94693. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  94694. }
  94695. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  94696. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  94697. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  94698. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  94699. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  94700. var angle = Math.atan2(cross.length(), dot);
  94701. planeNormalTowardsCamera.copyFrom(planeNormal);
  94702. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  94703. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  94704. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  94705. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  94706. }
  94707. // Flip up vector depending on which side the camera is on
  94708. if (gizmoLayer.utilityLayerScene.activeCamera) {
  94709. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  94710. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  94711. planeNormalTowardsCamera.scaleInPlace(-1);
  94712. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  94713. }
  94714. }
  94715. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  94716. if (halfCircleSide)
  94717. angle = -angle;
  94718. // Snapping logic
  94719. var snapped = false;
  94720. if (_this.snapDistance != 0) {
  94721. currentSnapDragDistance += angle;
  94722. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94723. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  94724. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94725. angle = _this.snapDistance * dragSteps;
  94726. snapped = true;
  94727. }
  94728. else {
  94729. angle = 0;
  94730. }
  94731. }
  94732. // If the mesh has a parent, convert needed world rotation to local rotation
  94733. tmpMatrix.reset();
  94734. if (_this.attachedMesh.parent) {
  94735. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  94736. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  94737. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  94738. }
  94739. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  94740. var quaternionCoefficient = Math.sin(angle / 2);
  94741. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  94742. // 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
  94743. if (tmpMatrix.determinant() > 0) {
  94744. amountToRotate.toEulerAnglesToRef(tmpVector);
  94745. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  94746. }
  94747. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  94748. // Rotate selected mesh quaternion over fixed axis
  94749. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  94750. }
  94751. else {
  94752. // Rotate selected mesh quaternion over rotated axis
  94753. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  94754. }
  94755. lastDragPosition.copyFrom(event.dragPlanePoint);
  94756. if (snapped) {
  94757. tmpSnapEvent.snapDistance = angle;
  94758. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94759. }
  94760. }
  94761. });
  94762. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94763. if (_this._customMeshSet) {
  94764. return;
  94765. }
  94766. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94767. var material = isHovered ? hoverMaterial : coloredMaterial;
  94768. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94769. m.material = material;
  94770. if (m.color) {
  94771. m.color = material.emissiveColor;
  94772. }
  94773. });
  94774. });
  94775. return _this;
  94776. }
  94777. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  94778. if (this.dragBehavior) {
  94779. this.dragBehavior.enabled = value ? true : false;
  94780. }
  94781. };
  94782. /**
  94783. * Disposes of the gizmo
  94784. */
  94785. PlaneRotationGizmo.prototype.dispose = function () {
  94786. this.onSnapObservable.clear();
  94787. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94788. this.dragBehavior.detach();
  94789. _super.prototype.dispose.call(this);
  94790. };
  94791. return PlaneRotationGizmo;
  94792. }(BABYLON.Gizmo));
  94793. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  94794. })(BABYLON || (BABYLON = {}));
  94795. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  94796. var BABYLON;
  94797. (function (BABYLON) {
  94798. /**
  94799. * Gizmo that enables dragging a mesh along 3 axis
  94800. */
  94801. var PositionGizmo = /** @class */ (function (_super) {
  94802. __extends(PositionGizmo, _super);
  94803. /**
  94804. * Creates a PositionGizmo
  94805. * @param gizmoLayer The utility layer the gizmo will be added to
  94806. */
  94807. function PositionGizmo(gizmoLayer) {
  94808. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94809. var _this = _super.call(this, gizmoLayer) || this;
  94810. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94811. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94812. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94813. _this.attachedMesh = null;
  94814. return _this;
  94815. }
  94816. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  94817. set: function (mesh) {
  94818. if (this.xGizmo) {
  94819. this.xGizmo.attachedMesh = mesh;
  94820. this.yGizmo.attachedMesh = mesh;
  94821. this.zGizmo.attachedMesh = mesh;
  94822. }
  94823. },
  94824. enumerable: true,
  94825. configurable: true
  94826. });
  94827. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94828. get: function () {
  94829. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94830. },
  94831. set: function (value) {
  94832. if (this.xGizmo) {
  94833. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94834. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94835. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94836. }
  94837. },
  94838. enumerable: true,
  94839. configurable: true
  94840. });
  94841. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  94842. get: function () {
  94843. return this.xGizmo.snapDistance;
  94844. },
  94845. /**
  94846. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94847. */
  94848. set: function (value) {
  94849. if (this.xGizmo) {
  94850. this.xGizmo.snapDistance = value;
  94851. this.yGizmo.snapDistance = value;
  94852. this.zGizmo.snapDistance = value;
  94853. }
  94854. },
  94855. enumerable: true,
  94856. configurable: true
  94857. });
  94858. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  94859. get: function () {
  94860. return this.xGizmo.scaleRatio;
  94861. },
  94862. /**
  94863. * Ratio for the scale of the gizmo (Default: 1)
  94864. */
  94865. set: function (value) {
  94866. if (this.xGizmo) {
  94867. this.xGizmo.scaleRatio = value;
  94868. this.yGizmo.scaleRatio = value;
  94869. this.zGizmo.scaleRatio = value;
  94870. }
  94871. },
  94872. enumerable: true,
  94873. configurable: true
  94874. });
  94875. /**
  94876. * Disposes of the gizmo
  94877. */
  94878. PositionGizmo.prototype.dispose = function () {
  94879. this.xGizmo.dispose();
  94880. this.yGizmo.dispose();
  94881. this.zGizmo.dispose();
  94882. };
  94883. /**
  94884. * CustomMeshes are not supported by this gizmo
  94885. * @param mesh The mesh to replace the default mesh of the gizmo
  94886. */
  94887. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  94888. 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)");
  94889. };
  94890. return PositionGizmo;
  94891. }(BABYLON.Gizmo));
  94892. BABYLON.PositionGizmo = PositionGizmo;
  94893. })(BABYLON || (BABYLON = {}));
  94894. //# sourceMappingURL=babylon.positionGizmo.js.map
  94895. var BABYLON;
  94896. (function (BABYLON) {
  94897. /**
  94898. * Gizmo that enables rotating a mesh along 3 axis
  94899. */
  94900. var RotationGizmo = /** @class */ (function (_super) {
  94901. __extends(RotationGizmo, _super);
  94902. /**
  94903. * Creates a RotationGizmo
  94904. * @param gizmoLayer The utility layer the gizmo will be added to
  94905. */
  94906. function RotationGizmo(gizmoLayer) {
  94907. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94908. var _this = _super.call(this, gizmoLayer) || this;
  94909. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94910. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94911. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94912. _this.attachedMesh = null;
  94913. return _this;
  94914. }
  94915. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  94916. set: function (mesh) {
  94917. if (this.xGizmo) {
  94918. this.xGizmo.attachedMesh = mesh;
  94919. this.yGizmo.attachedMesh = mesh;
  94920. this.zGizmo.attachedMesh = mesh;
  94921. }
  94922. },
  94923. enumerable: true,
  94924. configurable: true
  94925. });
  94926. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94927. get: function () {
  94928. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94929. },
  94930. set: function (value) {
  94931. if (this.xGizmo) {
  94932. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94933. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94934. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94935. }
  94936. },
  94937. enumerable: true,
  94938. configurable: true
  94939. });
  94940. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  94941. get: function () {
  94942. return this.xGizmo.snapDistance;
  94943. },
  94944. /**
  94945. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94946. */
  94947. set: function (value) {
  94948. if (this.xGizmo) {
  94949. this.xGizmo.snapDistance = value;
  94950. this.yGizmo.snapDistance = value;
  94951. this.zGizmo.snapDistance = value;
  94952. }
  94953. },
  94954. enumerable: true,
  94955. configurable: true
  94956. });
  94957. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  94958. get: function () {
  94959. return this.xGizmo.scaleRatio;
  94960. },
  94961. /**
  94962. * Ratio for the scale of the gizmo (Default: 1)
  94963. */
  94964. set: function (value) {
  94965. if (this.xGizmo) {
  94966. this.xGizmo.scaleRatio = value;
  94967. this.yGizmo.scaleRatio = value;
  94968. this.zGizmo.scaleRatio = value;
  94969. }
  94970. },
  94971. enumerable: true,
  94972. configurable: true
  94973. });
  94974. /**
  94975. * Disposes of the gizmo
  94976. */
  94977. RotationGizmo.prototype.dispose = function () {
  94978. this.xGizmo.dispose();
  94979. this.yGizmo.dispose();
  94980. this.zGizmo.dispose();
  94981. };
  94982. /**
  94983. * CustomMeshes are not supported by this gizmo
  94984. * @param mesh The mesh to replace the default mesh of the gizmo
  94985. */
  94986. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  94987. 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)");
  94988. };
  94989. return RotationGizmo;
  94990. }(BABYLON.Gizmo));
  94991. BABYLON.RotationGizmo = RotationGizmo;
  94992. })(BABYLON || (BABYLON = {}));
  94993. //# sourceMappingURL=babylon.rotationGizmo.js.map
  94994. var BABYLON;
  94995. (function (BABYLON) {
  94996. /**
  94997. * Gizmo that enables scaling a mesh along 3 axis
  94998. */
  94999. var ScaleGizmo = /** @class */ (function (_super) {
  95000. __extends(ScaleGizmo, _super);
  95001. /**
  95002. * Creates a ScaleGizmo
  95003. * @param gizmoLayer The utility layer the gizmo will be added to
  95004. */
  95005. function ScaleGizmo(gizmoLayer) {
  95006. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  95007. var _this = _super.call(this, gizmoLayer) || this;
  95008. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  95009. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  95010. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  95011. // Create uniform scale gizmo
  95012. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  95013. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  95014. _this._uniformGizmo.uniformScaling = true;
  95015. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  95016. octahedron.scaling.scaleInPlace(0.007);
  95017. _this._uniformGizmo.setCustomMesh(octahedron, true);
  95018. _this.attachedMesh = null;
  95019. return _this;
  95020. }
  95021. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  95022. set: function (mesh) {
  95023. if (this.xGizmo) {
  95024. this.xGizmo.attachedMesh = mesh;
  95025. this.yGizmo.attachedMesh = mesh;
  95026. this.zGizmo.attachedMesh = mesh;
  95027. this._uniformGizmo.attachedMesh = mesh;
  95028. }
  95029. },
  95030. enumerable: true,
  95031. configurable: true
  95032. });
  95033. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  95034. get: function () {
  95035. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  95036. },
  95037. set: function (value) {
  95038. if (this.xGizmo) {
  95039. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  95040. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  95041. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  95042. }
  95043. },
  95044. enumerable: true,
  95045. configurable: true
  95046. });
  95047. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  95048. get: function () {
  95049. return this.xGizmo.snapDistance;
  95050. },
  95051. /**
  95052. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  95053. */
  95054. set: function (value) {
  95055. if (this.xGizmo) {
  95056. this.xGizmo.snapDistance = value;
  95057. this.yGizmo.snapDistance = value;
  95058. this.zGizmo.snapDistance = value;
  95059. this._uniformGizmo.snapDistance = value;
  95060. }
  95061. },
  95062. enumerable: true,
  95063. configurable: true
  95064. });
  95065. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  95066. get: function () {
  95067. return this.xGizmo.scaleRatio;
  95068. },
  95069. /**
  95070. * Ratio for the scale of the gizmo (Default: 1)
  95071. */
  95072. set: function (value) {
  95073. if (this.xGizmo) {
  95074. this.xGizmo.scaleRatio = value;
  95075. this.yGizmo.scaleRatio = value;
  95076. this.zGizmo.scaleRatio = value;
  95077. this._uniformGizmo.scaleRatio = value;
  95078. }
  95079. },
  95080. enumerable: true,
  95081. configurable: true
  95082. });
  95083. /**
  95084. * Disposes of the gizmo
  95085. */
  95086. ScaleGizmo.prototype.dispose = function () {
  95087. this.xGizmo.dispose();
  95088. this.yGizmo.dispose();
  95089. this.zGizmo.dispose();
  95090. this._uniformGizmo.dispose();
  95091. };
  95092. return ScaleGizmo;
  95093. }(BABYLON.Gizmo));
  95094. BABYLON.ScaleGizmo = ScaleGizmo;
  95095. })(BABYLON || (BABYLON = {}));
  95096. //# sourceMappingURL=babylon.scaleGizmo.js.map
  95097. var BABYLON;
  95098. (function (BABYLON) {
  95099. /**
  95100. * Bounding box gizmo
  95101. */
  95102. var BoundingBoxGizmo = /** @class */ (function (_super) {
  95103. __extends(BoundingBoxGizmo, _super);
  95104. /**
  95105. * Creates an BoundingBoxGizmo
  95106. * @param gizmoLayer The utility layer the gizmo will be added to
  95107. * @param color The color of the gizmo
  95108. */
  95109. function BoundingBoxGizmo(color, gizmoLayer) {
  95110. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  95111. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  95112. var _this = _super.call(this, gizmoLayer) || this;
  95113. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  95114. _this._renderObserver = null;
  95115. _this._pointerObserver = null;
  95116. _this._scaleDragSpeed = 0.2;
  95117. _this._tmpQuaternion = new BABYLON.Quaternion();
  95118. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  95119. _this._tmpRotationMatrix = new BABYLON.Matrix();
  95120. /**
  95121. * 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)
  95122. */
  95123. _this.ignoreChildren = false;
  95124. /**
  95125. * 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)
  95126. */
  95127. _this.includeChildPredicate = null;
  95128. /**
  95129. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  95130. */
  95131. _this.rotationSphereSize = 0.1;
  95132. /**
  95133. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  95134. */
  95135. _this.scaleBoxSize = 0.1;
  95136. /**
  95137. * 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)
  95138. */
  95139. _this.fixedDragMeshScreenSize = false;
  95140. /**
  95141. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  95142. */
  95143. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  95144. /**
  95145. * Fired when a rotation sphere or scale box is dragged
  95146. */
  95147. _this.onDragStartObservable = new BABYLON.Observable();
  95148. /**
  95149. * Fired when a scale box is dragged
  95150. */
  95151. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  95152. /**
  95153. * Fired when a scale box drag is ended
  95154. */
  95155. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  95156. /**
  95157. * Fired when a rotation sphere is dragged
  95158. */
  95159. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  95160. /**
  95161. * Fired when a rotation sphere drag is ended
  95162. */
  95163. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  95164. /**
  95165. * 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)
  95166. */
  95167. _this.scalePivot = null;
  95168. _this._existingMeshScale = new BABYLON.Vector3();
  95169. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  95170. _this._updateScale = false;
  95171. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  95172. // Create Materials
  95173. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95174. coloredMaterial.disableLighting = true;
  95175. coloredMaterial.emissiveColor = color;
  95176. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95177. hoverColoredMaterial.disableLighting = true;
  95178. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  95179. // Build bounding box out of lines
  95180. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  95181. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  95182. var lines = [];
  95183. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  95184. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  95185. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  95186. 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));
  95187. 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));
  95188. 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));
  95189. 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));
  95190. 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));
  95191. 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));
  95192. 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));
  95193. 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));
  95194. 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));
  95195. lines.forEach(function (l) {
  95196. l.color = color;
  95197. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  95198. l.isPickable = false;
  95199. _this._lineBoundingBox.addChild(l);
  95200. });
  95201. _this._rootMesh.addChild(_this._lineBoundingBox);
  95202. // Create rotation spheres
  95203. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  95204. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  95205. var _loop_1 = function (i_1) {
  95206. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  95207. sphere.rotationQuaternion = new BABYLON.Quaternion();
  95208. sphere.material = coloredMaterial;
  95209. // Drag behavior
  95210. _dragBehavior = new BABYLON.PointerDragBehavior({});
  95211. _dragBehavior.moveAttached = false;
  95212. _dragBehavior.updateDragPlane = false;
  95213. sphere.addBehavior(_dragBehavior);
  95214. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  95215. var totalTurnAmountOfDrag = 0;
  95216. _dragBehavior.onDragStartObservable.add(function (event) {
  95217. startingTurnDirection.copyFrom(sphere.forward);
  95218. totalTurnAmountOfDrag = 0;
  95219. });
  95220. _dragBehavior.onDragObservable.add(function (event) {
  95221. _this.onRotationSphereDragObservable.notifyObservers({});
  95222. if (_this.attachedMesh) {
  95223. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  95224. var worldDragDirection = startingTurnDirection;
  95225. // Project the world right on to the drag plane
  95226. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  95227. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  95228. // project drag delta on to the resulting drag axis and rotate based on that
  95229. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  95230. // Make rotation relative to size of mesh.
  95231. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  95232. // Rotate based on axis
  95233. if (!_this.attachedMesh.rotationQuaternion) {
  95234. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  95235. }
  95236. if (!_this._anchorMesh.rotationQuaternion) {
  95237. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  95238. }
  95239. // Do not allow the object to turn more than a full circle
  95240. totalTurnAmountOfDrag += projectDist;
  95241. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  95242. if (i_1 >= 8) {
  95243. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  95244. }
  95245. else if (i_1 >= 4) {
  95246. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  95247. }
  95248. else {
  95249. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  95250. }
  95251. // Rotate around center of bounding box
  95252. _this._anchorMesh.addChild(_this.attachedMesh);
  95253. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  95254. _this._anchorMesh.removeChild(_this.attachedMesh);
  95255. }
  95256. _this.updateBoundingBox();
  95257. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  95258. }
  95259. });
  95260. // Selection/deselection
  95261. _dragBehavior.onDragStartObservable.add(function () {
  95262. _this.onDragStartObservable.notifyObservers({});
  95263. _this._selectNode(sphere);
  95264. });
  95265. _dragBehavior.onDragEndObservable.add(function () {
  95266. _this.onRotationSphereDragEndObservable.notifyObservers({});
  95267. _this._selectNode(null);
  95268. });
  95269. this_1._rotateSpheresParent.addChild(sphere);
  95270. };
  95271. var this_1 = this, _dragBehavior;
  95272. for (var i_1 = 0; i_1 < 12; i_1++) {
  95273. _loop_1(i_1);
  95274. }
  95275. _this._rootMesh.addChild(_this._rotateSpheresParent);
  95276. // Create scale cubes
  95277. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  95278. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  95279. for (var i = 0; i < 2; i++) {
  95280. for (var j = 0; j < 2; j++) {
  95281. var _loop_2 = function () {
  95282. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  95283. box.material = coloredMaterial;
  95284. // Dragging logic
  95285. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  95286. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  95287. _dragBehavior.moveAttached = false;
  95288. box.addBehavior(_dragBehavior);
  95289. _dragBehavior.onDragObservable.add(function (event) {
  95290. _this.onScaleBoxDragObservable.notifyObservers({});
  95291. if (_this.attachedMesh) {
  95292. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  95293. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  95294. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  95295. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  95296. _this.updateBoundingBox();
  95297. if (_this.scalePivot) {
  95298. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  95299. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  95300. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  95301. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  95302. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  95303. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  95304. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  95305. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  95306. }
  95307. else {
  95308. // Scale from the position of the opposite corner
  95309. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  95310. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  95311. }
  95312. _this._anchorMesh.addChild(_this.attachedMesh);
  95313. _this._anchorMesh.scaling.addInPlace(deltaScale);
  95314. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  95315. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  95316. }
  95317. _this._anchorMesh.removeChild(_this.attachedMesh);
  95318. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  95319. }
  95320. });
  95321. // Selection/deselection
  95322. _dragBehavior.onDragStartObservable.add(function () {
  95323. _this.onDragStartObservable.notifyObservers({});
  95324. _this._selectNode(box);
  95325. });
  95326. _dragBehavior.onDragEndObservable.add(function () {
  95327. _this.onScaleBoxDragEndObservable.notifyObservers({});
  95328. _this._selectNode(null);
  95329. });
  95330. this_2._scaleBoxesParent.addChild(box);
  95331. };
  95332. var this_2 = this, _dragBehavior;
  95333. for (var k = 0; k < 2; k++) {
  95334. _loop_2();
  95335. }
  95336. }
  95337. }
  95338. _this._rootMesh.addChild(_this._scaleBoxesParent);
  95339. // Hover color change
  95340. var pointerIds = new Array();
  95341. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  95342. if (!pointerIds[pointerInfo.event.pointerId]) {
  95343. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  95344. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  95345. pointerIds[pointerInfo.event.pointerId] = mesh;
  95346. mesh.material = hoverColoredMaterial;
  95347. }
  95348. });
  95349. }
  95350. else {
  95351. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  95352. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  95353. delete pointerIds[pointerInfo.event.pointerId];
  95354. }
  95355. }
  95356. });
  95357. // Update bounding box positions
  95358. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  95359. // Only update the bouding box if scaling has changed
  95360. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  95361. _this.updateBoundingBox();
  95362. }
  95363. });
  95364. _this.updateBoundingBox();
  95365. return _this;
  95366. }
  95367. /** @hidden */
  95368. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  95369. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  95370. // Save old pivot and set pivot to 0,0,0
  95371. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  95372. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  95373. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  95374. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  95375. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  95376. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  95377. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  95378. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  95379. }
  95380. }
  95381. BoundingBoxGizmo._PivotCached++;
  95382. };
  95383. /** @hidden */
  95384. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  95385. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  95386. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  95387. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  95388. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  95389. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  95390. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  95391. }
  95392. this._PivotCached--;
  95393. };
  95394. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  95395. if (value) {
  95396. // Reset anchor mesh to match attached mesh's scale
  95397. // This is needed to avoid invalid box/sphere position on first drag
  95398. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  95399. this._anchorMesh.addChild(value);
  95400. this._anchorMesh.removeChild(value);
  95401. BoundingBoxGizmo._RestorePivotPoint(value);
  95402. this.updateBoundingBox();
  95403. }
  95404. };
  95405. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  95406. this._rotateSpheresParent.getChildMeshes()
  95407. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  95408. m.isVisible = (!selectedMesh || m == selectedMesh);
  95409. });
  95410. };
  95411. /**
  95412. * Updates the bounding box information for the Gizmo
  95413. */
  95414. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  95415. if (this.attachedMesh) {
  95416. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  95417. this._update();
  95418. // Rotate based on axis
  95419. if (!this.attachedMesh.rotationQuaternion) {
  95420. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  95421. }
  95422. if (!this._anchorMesh.rotationQuaternion) {
  95423. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  95424. }
  95425. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  95426. // Store original position and reset mesh to origin before computing the bounding box
  95427. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  95428. this._tmpVector.copyFrom(this.attachedMesh.position);
  95429. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  95430. this.attachedMesh.position.set(0, 0, 0);
  95431. // Update bounding dimensions/positions
  95432. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  95433. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  95434. // Update gizmo to match bounding box scaling and rotation
  95435. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  95436. 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);
  95437. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  95438. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  95439. this._lineBoundingBox.computeWorldMatrix();
  95440. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  95441. // restore position/rotation values
  95442. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  95443. this.attachedMesh.position.copyFrom(this._tmpVector);
  95444. }
  95445. // Update rotation sphere locations
  95446. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  95447. for (var i = 0; i < 3; i++) {
  95448. for (var j = 0; j < 2; j++) {
  95449. for (var k = 0; k < 2; k++) {
  95450. var index = ((i * 4) + (j * 2)) + k;
  95451. if (i == 0) {
  95452. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  95453. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95454. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95455. }
  95456. if (i == 1) {
  95457. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  95458. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95459. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95460. }
  95461. if (i == 2) {
  95462. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  95463. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95464. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95465. }
  95466. if (this.fixedDragMeshScreenSize) {
  95467. this._rootMesh.computeWorldMatrix();
  95468. this._rotateSpheresParent.computeWorldMatrix();
  95469. rotateSpheres[index].computeWorldMatrix();
  95470. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  95471. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  95472. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  95473. }
  95474. else {
  95475. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  95476. }
  95477. }
  95478. }
  95479. }
  95480. // Update scale box locations
  95481. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  95482. for (var i = 0; i < 2; i++) {
  95483. for (var j = 0; j < 2; j++) {
  95484. for (var k = 0; k < 2; k++) {
  95485. var index = ((i * 4) + (j * 2)) + k;
  95486. if (scaleBoxes[index]) {
  95487. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  95488. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95489. if (this.fixedDragMeshScreenSize) {
  95490. this._rootMesh.computeWorldMatrix();
  95491. this._scaleBoxesParent.computeWorldMatrix();
  95492. scaleBoxes[index].computeWorldMatrix();
  95493. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  95494. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  95495. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  95496. }
  95497. else {
  95498. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  95499. }
  95500. }
  95501. }
  95502. }
  95503. }
  95504. if (this.attachedMesh) {
  95505. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  95506. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  95507. }
  95508. };
  95509. /**
  95510. * Enables rotation on the specified axis and disables rotation on the others
  95511. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  95512. */
  95513. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  95514. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  95515. if (i < 4) {
  95516. m.setEnabled(axis.indexOf("x") != -1);
  95517. }
  95518. else if (i < 8) {
  95519. m.setEnabled(axis.indexOf("y") != -1);
  95520. }
  95521. else {
  95522. m.setEnabled(axis.indexOf("z") != -1);
  95523. }
  95524. });
  95525. };
  95526. /**
  95527. * Disposes of the gizmo
  95528. */
  95529. BoundingBoxGizmo.prototype.dispose = function () {
  95530. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  95531. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  95532. this._lineBoundingBox.dispose();
  95533. this._rotateSpheresParent.dispose();
  95534. this._scaleBoxesParent.dispose();
  95535. _super.prototype.dispose.call(this);
  95536. };
  95537. /**
  95538. * 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)
  95539. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  95540. * @returns the bounding box mesh with the passed in mesh as a child
  95541. */
  95542. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  95543. var makeNotPickable = function (root) {
  95544. root.isPickable = false;
  95545. root.getChildMeshes().forEach(function (c) {
  95546. makeNotPickable(c);
  95547. });
  95548. };
  95549. makeNotPickable(mesh);
  95550. // Reset position to get boudning box from origin with no rotation
  95551. if (!mesh.rotationQuaternion) {
  95552. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  95553. }
  95554. var oldPos = mesh.position.clone();
  95555. var oldRot = mesh.rotationQuaternion.clone();
  95556. mesh.rotationQuaternion.set(0, 0, 0, 1);
  95557. mesh.position.set(0, 0, 0);
  95558. // Update bounding dimensions/positions
  95559. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  95560. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  95561. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  95562. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  95563. // Restore original positions
  95564. mesh.addChild(box);
  95565. mesh.rotationQuaternion.copyFrom(oldRot);
  95566. mesh.position.copyFrom(oldPos);
  95567. // Reverse parenting
  95568. mesh.removeChild(box);
  95569. box.addChild(mesh);
  95570. box.visibility = 0;
  95571. return box;
  95572. };
  95573. /**
  95574. * CustomMeshes are not supported by this gizmo
  95575. * @param mesh The mesh to replace the default mesh of the gizmo
  95576. */
  95577. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  95578. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  95579. };
  95580. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  95581. // store/remove pivot point should only be applied during their outermost calls
  95582. BoundingBoxGizmo._PivotCached = 0;
  95583. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  95584. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  95585. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  95586. return BoundingBoxGizmo;
  95587. }(BABYLON.Gizmo));
  95588. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  95589. })(BABYLON || (BABYLON = {}));
  95590. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  95591. var BABYLON;
  95592. (function (BABYLON) {
  95593. /**
  95594. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  95595. */
  95596. var GizmoManager = /** @class */ (function () {
  95597. /**
  95598. * Instatiates a gizmo manager
  95599. * @param scene the scene to overlay the gizmos on top of
  95600. */
  95601. function GizmoManager(scene) {
  95602. var _this = this;
  95603. this.scene = scene;
  95604. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  95605. this._pointerObserver = null;
  95606. this._attachedMesh = null;
  95607. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  95608. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  95609. /**
  95610. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  95611. */
  95612. this.attachableMeshes = null;
  95613. /**
  95614. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  95615. */
  95616. this.usePointerToAttachGizmos = true;
  95617. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  95618. // Instatiate/dispose gizmos based on pointer actions
  95619. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  95620. if (!_this.usePointerToAttachGizmos) {
  95621. return;
  95622. }
  95623. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95624. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  95625. var node = pointerInfo.pickInfo.pickedMesh;
  95626. if (_this.attachableMeshes == null) {
  95627. // Attach to the most parent node
  95628. while (node && node.parent != null) {
  95629. node = node.parent;
  95630. }
  95631. }
  95632. else {
  95633. // Attach to the parent node that is an attachableMesh
  95634. var found = false;
  95635. _this.attachableMeshes.forEach(function (mesh) {
  95636. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  95637. node = mesh;
  95638. found = true;
  95639. }
  95640. });
  95641. if (!found) {
  95642. node = null;
  95643. }
  95644. }
  95645. if (node instanceof BABYLON.AbstractMesh) {
  95646. _this.attachToMesh(node);
  95647. }
  95648. else {
  95649. _this.attachToMesh(null);
  95650. }
  95651. }
  95652. else {
  95653. _this.attachToMesh(null);
  95654. }
  95655. }
  95656. });
  95657. }
  95658. /**
  95659. * Attaches a set of gizmos to the specified mesh
  95660. * @param mesh The mesh the gizmo's should be attached to
  95661. */
  95662. GizmoManager.prototype.attachToMesh = function (mesh) {
  95663. if (this._attachedMesh) {
  95664. this._attachedMesh.removeBehavior(this._dragBehavior);
  95665. }
  95666. this._attachedMesh = mesh;
  95667. for (var key in this.gizmos) {
  95668. var gizmo = (this.gizmos[key]);
  95669. if (gizmo && this._gizmosEnabled[key]) {
  95670. gizmo.attachedMesh = mesh;
  95671. }
  95672. }
  95673. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  95674. this._attachedMesh.addBehavior(this._dragBehavior);
  95675. }
  95676. };
  95677. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  95678. get: function () {
  95679. return this._gizmosEnabled.positionGizmo;
  95680. },
  95681. /**
  95682. * If the position gizmo is enabled
  95683. */
  95684. set: function (value) {
  95685. if (value) {
  95686. if (!this.gizmos.positionGizmo) {
  95687. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  95688. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  95689. }
  95690. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  95691. }
  95692. else if (this.gizmos.positionGizmo) {
  95693. this.gizmos.positionGizmo.attachedMesh = null;
  95694. }
  95695. this._gizmosEnabled.positionGizmo = value;
  95696. },
  95697. enumerable: true,
  95698. configurable: true
  95699. });
  95700. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  95701. get: function () {
  95702. return this._gizmosEnabled.rotationGizmo;
  95703. },
  95704. /**
  95705. * If the rotation gizmo is enabled
  95706. */
  95707. set: function (value) {
  95708. if (value) {
  95709. if (!this.gizmos.rotationGizmo) {
  95710. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  95711. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  95712. }
  95713. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  95714. }
  95715. else if (this.gizmos.rotationGizmo) {
  95716. this.gizmos.rotationGizmo.attachedMesh = null;
  95717. }
  95718. this._gizmosEnabled.rotationGizmo = value;
  95719. },
  95720. enumerable: true,
  95721. configurable: true
  95722. });
  95723. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  95724. get: function () {
  95725. return this._gizmosEnabled.scaleGizmo;
  95726. },
  95727. /**
  95728. * If the scale gizmo is enabled
  95729. */
  95730. set: function (value) {
  95731. if (value) {
  95732. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  95733. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  95734. }
  95735. else if (this.gizmos.scaleGizmo) {
  95736. this.gizmos.scaleGizmo.attachedMesh = null;
  95737. }
  95738. this._gizmosEnabled.scaleGizmo = value;
  95739. },
  95740. enumerable: true,
  95741. configurable: true
  95742. });
  95743. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  95744. get: function () {
  95745. return this._gizmosEnabled.boundingBoxGizmo;
  95746. },
  95747. /**
  95748. * If the boundingBox gizmo is enabled
  95749. */
  95750. set: function (value) {
  95751. if (value) {
  95752. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  95753. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  95754. if (this._attachedMesh) {
  95755. this._attachedMesh.removeBehavior(this._dragBehavior);
  95756. this._attachedMesh.addBehavior(this._dragBehavior);
  95757. }
  95758. }
  95759. else if (this.gizmos.boundingBoxGizmo) {
  95760. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  95761. }
  95762. this._gizmosEnabled.boundingBoxGizmo = value;
  95763. },
  95764. enumerable: true,
  95765. configurable: true
  95766. });
  95767. /**
  95768. * Disposes of the gizmo manager
  95769. */
  95770. GizmoManager.prototype.dispose = function () {
  95771. this.scene.onPointerObservable.remove(this._pointerObserver);
  95772. for (var key in this.gizmos) {
  95773. var gizmo = (this.gizmos[key]);
  95774. if (gizmo) {
  95775. gizmo.dispose();
  95776. }
  95777. }
  95778. this._dragBehavior.detach();
  95779. };
  95780. return GizmoManager;
  95781. }());
  95782. BABYLON.GizmoManager = GizmoManager;
  95783. })(BABYLON || (BABYLON = {}));
  95784. //# sourceMappingURL=babylon.gizmoManager.js.map
  95785. var BABYLON;
  95786. (function (BABYLON) {
  95787. /**
  95788. * Defines a target to use with MorphTargetManager
  95789. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  95790. */
  95791. var MorphTarget = /** @class */ (function () {
  95792. /**
  95793. * Creates a new MorphTarget
  95794. * @param name defines the name of the target
  95795. * @param influence defines the influence to use
  95796. */
  95797. function MorphTarget(
  95798. /** defines the name of the target */
  95799. name, influence, scene) {
  95800. if (influence === void 0) { influence = 0; }
  95801. if (scene === void 0) { scene = null; }
  95802. this.name = name;
  95803. /**
  95804. * Gets or sets the list of animations
  95805. */
  95806. this.animations = new Array();
  95807. this._positions = null;
  95808. this._normals = null;
  95809. this._tangents = null;
  95810. /**
  95811. * Observable raised when the influence changes
  95812. */
  95813. this.onInfluenceChanged = new BABYLON.Observable();
  95814. this._animationPropertiesOverride = null;
  95815. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95816. this.influence = influence;
  95817. }
  95818. Object.defineProperty(MorphTarget.prototype, "influence", {
  95819. /**
  95820. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  95821. */
  95822. get: function () {
  95823. return this._influence;
  95824. },
  95825. set: function (influence) {
  95826. if (this._influence === influence) {
  95827. return;
  95828. }
  95829. var previous = this._influence;
  95830. this._influence = influence;
  95831. if (this.onInfluenceChanged.hasObservers) {
  95832. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  95833. }
  95834. },
  95835. enumerable: true,
  95836. configurable: true
  95837. });
  95838. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  95839. /**
  95840. * Gets or sets the animation properties override
  95841. */
  95842. get: function () {
  95843. if (!this._animationPropertiesOverride && this._scene) {
  95844. return this._scene.animationPropertiesOverride;
  95845. }
  95846. return this._animationPropertiesOverride;
  95847. },
  95848. set: function (value) {
  95849. this._animationPropertiesOverride = value;
  95850. },
  95851. enumerable: true,
  95852. configurable: true
  95853. });
  95854. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  95855. /**
  95856. * Gets a boolean defining if the target contains position data
  95857. */
  95858. get: function () {
  95859. return !!this._positions;
  95860. },
  95861. enumerable: true,
  95862. configurable: true
  95863. });
  95864. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  95865. /**
  95866. * Gets a boolean defining if the target contains normal data
  95867. */
  95868. get: function () {
  95869. return !!this._normals;
  95870. },
  95871. enumerable: true,
  95872. configurable: true
  95873. });
  95874. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  95875. /**
  95876. * Gets a boolean defining if the target contains tangent data
  95877. */
  95878. get: function () {
  95879. return !!this._tangents;
  95880. },
  95881. enumerable: true,
  95882. configurable: true
  95883. });
  95884. /**
  95885. * Affects position data to this target
  95886. * @param data defines the position data to use
  95887. */
  95888. MorphTarget.prototype.setPositions = function (data) {
  95889. this._positions = data;
  95890. };
  95891. /**
  95892. * Gets the position data stored in this target
  95893. * @returns a FloatArray containing the position data (or null if not present)
  95894. */
  95895. MorphTarget.prototype.getPositions = function () {
  95896. return this._positions;
  95897. };
  95898. /**
  95899. * Affects normal data to this target
  95900. * @param data defines the normal data to use
  95901. */
  95902. MorphTarget.prototype.setNormals = function (data) {
  95903. this._normals = data;
  95904. };
  95905. /**
  95906. * Gets the normal data stored in this target
  95907. * @returns a FloatArray containing the normal data (or null if not present)
  95908. */
  95909. MorphTarget.prototype.getNormals = function () {
  95910. return this._normals;
  95911. };
  95912. /**
  95913. * Affects tangent data to this target
  95914. * @param data defines the tangent data to use
  95915. */
  95916. MorphTarget.prototype.setTangents = function (data) {
  95917. this._tangents = data;
  95918. };
  95919. /**
  95920. * Gets the tangent data stored in this target
  95921. * @returns a FloatArray containing the tangent data (or null if not present)
  95922. */
  95923. MorphTarget.prototype.getTangents = function () {
  95924. return this._tangents;
  95925. };
  95926. /**
  95927. * Serializes the current target into a Serialization object
  95928. * @returns the serialized object
  95929. */
  95930. MorphTarget.prototype.serialize = function () {
  95931. var serializationObject = {};
  95932. serializationObject.name = this.name;
  95933. serializationObject.influence = this.influence;
  95934. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  95935. if (this.hasNormals) {
  95936. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  95937. }
  95938. if (this.hasTangents) {
  95939. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  95940. }
  95941. // Animations
  95942. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  95943. return serializationObject;
  95944. };
  95945. // Statics
  95946. /**
  95947. * Creates a new target from serialized data
  95948. * @param serializationObject defines the serialized data to use
  95949. * @returns a new MorphTarget
  95950. */
  95951. MorphTarget.Parse = function (serializationObject) {
  95952. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  95953. result.setPositions(serializationObject.positions);
  95954. if (serializationObject.normals) {
  95955. result.setNormals(serializationObject.normals);
  95956. }
  95957. if (serializationObject.tangents) {
  95958. result.setTangents(serializationObject.tangents);
  95959. }
  95960. // Animations
  95961. if (serializationObject.animations) {
  95962. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  95963. var parsedAnimation = serializationObject.animations[animationIndex];
  95964. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  95965. }
  95966. }
  95967. return result;
  95968. };
  95969. /**
  95970. * Creates a MorphTarget from mesh data
  95971. * @param mesh defines the source mesh
  95972. * @param name defines the name to use for the new target
  95973. * @param influence defines the influence to attach to the target
  95974. * @returns a new MorphTarget
  95975. */
  95976. MorphTarget.FromMesh = function (mesh, name, influence) {
  95977. if (!name) {
  95978. name = mesh.name;
  95979. }
  95980. var result = new MorphTarget(name, influence, mesh.getScene());
  95981. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  95982. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95983. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  95984. }
  95985. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  95986. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  95987. }
  95988. return result;
  95989. };
  95990. return MorphTarget;
  95991. }());
  95992. BABYLON.MorphTarget = MorphTarget;
  95993. })(BABYLON || (BABYLON = {}));
  95994. //# sourceMappingURL=babylon.morphTarget.js.map
  95995. var BABYLON;
  95996. (function (BABYLON) {
  95997. /**
  95998. * This class is used to deform meshes using morphing between different targets
  95999. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  96000. */
  96001. var MorphTargetManager = /** @class */ (function () {
  96002. /**
  96003. * Creates a new MorphTargetManager
  96004. * @param scene defines the current scene
  96005. */
  96006. function MorphTargetManager(scene) {
  96007. if (scene === void 0) { scene = null; }
  96008. this._targets = new Array();
  96009. this._targetObservable = new Array();
  96010. this._activeTargets = new BABYLON.SmartArray(16);
  96011. this._supportsNormals = false;
  96012. this._supportsTangents = false;
  96013. this._vertexCount = 0;
  96014. this._uniqueId = 0;
  96015. this._tempInfluences = new Array();
  96016. if (!scene) {
  96017. scene = BABYLON.Engine.LastCreatedScene;
  96018. }
  96019. this._scene = scene;
  96020. if (this._scene) {
  96021. this._scene.morphTargetManagers.push(this);
  96022. this._uniqueId = this._scene.getUniqueId();
  96023. }
  96024. }
  96025. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  96026. /**
  96027. * Gets the unique ID of this manager
  96028. */
  96029. get: function () {
  96030. return this._uniqueId;
  96031. },
  96032. enumerable: true,
  96033. configurable: true
  96034. });
  96035. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  96036. /**
  96037. * Gets the number of vertices handled by this manager
  96038. */
  96039. get: function () {
  96040. return this._vertexCount;
  96041. },
  96042. enumerable: true,
  96043. configurable: true
  96044. });
  96045. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  96046. /**
  96047. * Gets a boolean indicating if this manager supports morphing of normals
  96048. */
  96049. get: function () {
  96050. return this._supportsNormals;
  96051. },
  96052. enumerable: true,
  96053. configurable: true
  96054. });
  96055. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  96056. /**
  96057. * Gets a boolean indicating if this manager supports morphing of tangents
  96058. */
  96059. get: function () {
  96060. return this._supportsTangents;
  96061. },
  96062. enumerable: true,
  96063. configurable: true
  96064. });
  96065. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  96066. /**
  96067. * Gets the number of targets stored in this manager
  96068. */
  96069. get: function () {
  96070. return this._targets.length;
  96071. },
  96072. enumerable: true,
  96073. configurable: true
  96074. });
  96075. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  96076. /**
  96077. * Gets the number of influencers (ie. the number of targets with influences > 0)
  96078. */
  96079. get: function () {
  96080. return this._activeTargets.length;
  96081. },
  96082. enumerable: true,
  96083. configurable: true
  96084. });
  96085. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  96086. /**
  96087. * Gets the list of influences (one per target)
  96088. */
  96089. get: function () {
  96090. return this._influences;
  96091. },
  96092. enumerable: true,
  96093. configurable: true
  96094. });
  96095. /**
  96096. * Gets the active target at specified index. An active target is a target with an influence > 0
  96097. * @param index defines the index to check
  96098. * @returns the requested target
  96099. */
  96100. MorphTargetManager.prototype.getActiveTarget = function (index) {
  96101. return this._activeTargets.data[index];
  96102. };
  96103. /**
  96104. * Gets the target at specified index
  96105. * @param index defines the index to check
  96106. * @returns the requested target
  96107. */
  96108. MorphTargetManager.prototype.getTarget = function (index) {
  96109. return this._targets[index];
  96110. };
  96111. /**
  96112. * Add a new target to this manager
  96113. * @param target defines the target to add
  96114. */
  96115. MorphTargetManager.prototype.addTarget = function (target) {
  96116. var _this = this;
  96117. this._targets.push(target);
  96118. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  96119. _this._syncActiveTargets(needUpdate);
  96120. }));
  96121. this._syncActiveTargets(true);
  96122. };
  96123. /**
  96124. * Removes a target from the manager
  96125. * @param target defines the target to remove
  96126. */
  96127. MorphTargetManager.prototype.removeTarget = function (target) {
  96128. var index = this._targets.indexOf(target);
  96129. if (index >= 0) {
  96130. this._targets.splice(index, 1);
  96131. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  96132. this._syncActiveTargets(true);
  96133. }
  96134. };
  96135. /**
  96136. * Serializes the current manager into a Serialization object
  96137. * @returns the serialized object
  96138. */
  96139. MorphTargetManager.prototype.serialize = function () {
  96140. var serializationObject = {};
  96141. serializationObject.id = this.uniqueId;
  96142. serializationObject.targets = [];
  96143. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  96144. var target = _a[_i];
  96145. serializationObject.targets.push(target.serialize());
  96146. }
  96147. return serializationObject;
  96148. };
  96149. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  96150. var influenceCount = 0;
  96151. this._activeTargets.reset();
  96152. this._supportsNormals = true;
  96153. this._supportsTangents = true;
  96154. this._vertexCount = 0;
  96155. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  96156. var target = _a[_i];
  96157. this._activeTargets.push(target);
  96158. this._tempInfluences[influenceCount++] = target.influence;
  96159. var positions = target.getPositions();
  96160. if (positions) {
  96161. this._supportsNormals = this._supportsNormals && target.hasNormals;
  96162. this._supportsTangents = this._supportsTangents && target.hasTangents;
  96163. var vertexCount = positions.length / 3;
  96164. if (this._vertexCount === 0) {
  96165. this._vertexCount = vertexCount;
  96166. }
  96167. else if (this._vertexCount !== vertexCount) {
  96168. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  96169. return;
  96170. }
  96171. }
  96172. }
  96173. if (!this._influences || this._influences.length !== influenceCount) {
  96174. this._influences = new Float32Array(influenceCount);
  96175. }
  96176. for (var index = 0; index < influenceCount; index++) {
  96177. this._influences[index] = this._tempInfluences[index];
  96178. }
  96179. if (needUpdate) {
  96180. this.synchronize();
  96181. }
  96182. };
  96183. /**
  96184. * Syncrhonize the targets with all the meshes using this morph target manager
  96185. */
  96186. MorphTargetManager.prototype.synchronize = function () {
  96187. if (!this._scene) {
  96188. return;
  96189. }
  96190. // Flag meshes as dirty to resync with the active targets
  96191. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  96192. var mesh = _a[_i];
  96193. if (mesh.morphTargetManager === this) {
  96194. mesh._syncGeometryWithMorphTargetManager();
  96195. }
  96196. }
  96197. };
  96198. // Statics
  96199. /**
  96200. * Creates a new MorphTargetManager from serialized data
  96201. * @param serializationObject defines the serialized data
  96202. * @param scene defines the hosting scene
  96203. * @returns the new MorphTargetManager
  96204. */
  96205. MorphTargetManager.Parse = function (serializationObject, scene) {
  96206. var result = new MorphTargetManager(scene);
  96207. result._uniqueId = serializationObject.id;
  96208. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  96209. var targetData = _a[_i];
  96210. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  96211. }
  96212. return result;
  96213. };
  96214. return MorphTargetManager;
  96215. }());
  96216. BABYLON.MorphTargetManager = MorphTargetManager;
  96217. })(BABYLON || (BABYLON = {}));
  96218. //# sourceMappingURL=babylon.morphTargetManager.js.map
  96219. var BABYLON;
  96220. (function (BABYLON) {
  96221. var Octree = /** @class */ (function () {
  96222. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  96223. if (maxDepth === void 0) { maxDepth = 2; }
  96224. this.maxDepth = maxDepth;
  96225. this.dynamicContent = new Array();
  96226. this._maxBlockCapacity = maxBlockCapacity || 64;
  96227. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  96228. this._creationFunc = creationFunc;
  96229. }
  96230. // Methods
  96231. Octree.prototype.update = function (worldMin, worldMax, entries) {
  96232. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  96233. };
  96234. Octree.prototype.addMesh = function (entry) {
  96235. for (var index = 0; index < this.blocks.length; index++) {
  96236. var block = this.blocks[index];
  96237. block.addEntry(entry);
  96238. }
  96239. };
  96240. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  96241. this._selectionContent.reset();
  96242. for (var index = 0; index < this.blocks.length; index++) {
  96243. var block = this.blocks[index];
  96244. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  96245. }
  96246. if (allowDuplicate) {
  96247. this._selectionContent.concat(this.dynamicContent);
  96248. }
  96249. else {
  96250. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  96251. }
  96252. return this._selectionContent;
  96253. };
  96254. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  96255. this._selectionContent.reset();
  96256. for (var index = 0; index < this.blocks.length; index++) {
  96257. var block = this.blocks[index];
  96258. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  96259. }
  96260. if (allowDuplicate) {
  96261. this._selectionContent.concat(this.dynamicContent);
  96262. }
  96263. else {
  96264. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  96265. }
  96266. return this._selectionContent;
  96267. };
  96268. Octree.prototype.intersectsRay = function (ray) {
  96269. this._selectionContent.reset();
  96270. for (var index = 0; index < this.blocks.length; index++) {
  96271. var block = this.blocks[index];
  96272. block.intersectsRay(ray, this._selectionContent);
  96273. }
  96274. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  96275. return this._selectionContent;
  96276. };
  96277. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  96278. target.blocks = new Array();
  96279. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  96280. // Segmenting space
  96281. for (var x = 0; x < 2; x++) {
  96282. for (var y = 0; y < 2; y++) {
  96283. for (var z = 0; z < 2; z++) {
  96284. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  96285. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  96286. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  96287. block.addEntries(entries);
  96288. target.blocks.push(block);
  96289. }
  96290. }
  96291. }
  96292. };
  96293. Octree.CreationFuncForMeshes = function (entry, block) {
  96294. var boundingInfo = entry.getBoundingInfo();
  96295. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  96296. block.entries.push(entry);
  96297. }
  96298. };
  96299. Octree.CreationFuncForSubMeshes = function (entry, block) {
  96300. var boundingInfo = entry.getBoundingInfo();
  96301. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  96302. block.entries.push(entry);
  96303. }
  96304. };
  96305. return Octree;
  96306. }());
  96307. BABYLON.Octree = Octree;
  96308. })(BABYLON || (BABYLON = {}));
  96309. //# sourceMappingURL=babylon.octree.js.map
  96310. var BABYLON;
  96311. (function (BABYLON) {
  96312. var OctreeBlock = /** @class */ (function () {
  96313. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  96314. this.entries = new Array();
  96315. this._boundingVectors = new Array();
  96316. this._capacity = capacity;
  96317. this._depth = depth;
  96318. this._maxDepth = maxDepth;
  96319. this._creationFunc = creationFunc;
  96320. this._minPoint = minPoint;
  96321. this._maxPoint = maxPoint;
  96322. this._boundingVectors.push(minPoint.clone());
  96323. this._boundingVectors.push(maxPoint.clone());
  96324. this._boundingVectors.push(minPoint.clone());
  96325. this._boundingVectors[2].x = maxPoint.x;
  96326. this._boundingVectors.push(minPoint.clone());
  96327. this._boundingVectors[3].y = maxPoint.y;
  96328. this._boundingVectors.push(minPoint.clone());
  96329. this._boundingVectors[4].z = maxPoint.z;
  96330. this._boundingVectors.push(maxPoint.clone());
  96331. this._boundingVectors[5].z = minPoint.z;
  96332. this._boundingVectors.push(maxPoint.clone());
  96333. this._boundingVectors[6].x = minPoint.x;
  96334. this._boundingVectors.push(maxPoint.clone());
  96335. this._boundingVectors[7].y = minPoint.y;
  96336. }
  96337. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  96338. // Property
  96339. get: function () {
  96340. return this._capacity;
  96341. },
  96342. enumerable: true,
  96343. configurable: true
  96344. });
  96345. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  96346. get: function () {
  96347. return this._minPoint;
  96348. },
  96349. enumerable: true,
  96350. configurable: true
  96351. });
  96352. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  96353. get: function () {
  96354. return this._maxPoint;
  96355. },
  96356. enumerable: true,
  96357. configurable: true
  96358. });
  96359. // Methods
  96360. OctreeBlock.prototype.addEntry = function (entry) {
  96361. if (this.blocks) {
  96362. for (var index = 0; index < this.blocks.length; index++) {
  96363. var block = this.blocks[index];
  96364. block.addEntry(entry);
  96365. }
  96366. return;
  96367. }
  96368. this._creationFunc(entry, this);
  96369. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  96370. this.createInnerBlocks();
  96371. }
  96372. };
  96373. OctreeBlock.prototype.addEntries = function (entries) {
  96374. for (var index = 0; index < entries.length; index++) {
  96375. var mesh = entries[index];
  96376. this.addEntry(mesh);
  96377. }
  96378. };
  96379. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  96380. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  96381. if (this.blocks) {
  96382. for (var index = 0; index < this.blocks.length; index++) {
  96383. var block = this.blocks[index];
  96384. block.select(frustumPlanes, selection, allowDuplicate);
  96385. }
  96386. return;
  96387. }
  96388. if (allowDuplicate) {
  96389. selection.concat(this.entries);
  96390. }
  96391. else {
  96392. selection.concatWithNoDuplicate(this.entries);
  96393. }
  96394. }
  96395. };
  96396. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  96397. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  96398. if (this.blocks) {
  96399. for (var index = 0; index < this.blocks.length; index++) {
  96400. var block = this.blocks[index];
  96401. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  96402. }
  96403. return;
  96404. }
  96405. if (allowDuplicate) {
  96406. selection.concat(this.entries);
  96407. }
  96408. else {
  96409. selection.concatWithNoDuplicate(this.entries);
  96410. }
  96411. }
  96412. };
  96413. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  96414. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  96415. if (this.blocks) {
  96416. for (var index = 0; index < this.blocks.length; index++) {
  96417. var block = this.blocks[index];
  96418. block.intersectsRay(ray, selection);
  96419. }
  96420. return;
  96421. }
  96422. selection.concatWithNoDuplicate(this.entries);
  96423. }
  96424. };
  96425. OctreeBlock.prototype.createInnerBlocks = function () {
  96426. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  96427. };
  96428. return OctreeBlock;
  96429. }());
  96430. BABYLON.OctreeBlock = OctreeBlock;
  96431. })(BABYLON || (BABYLON = {}));
  96432. //# sourceMappingURL=babylon.octreeBlock.js.map
  96433. var BABYLON;
  96434. (function (BABYLON) {
  96435. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  96436. if (maxCapacity === void 0) { maxCapacity = 64; }
  96437. if (maxDepth === void 0) { maxDepth = 2; }
  96438. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  96439. if (!component) {
  96440. component = new OctreeSceneComponent(this);
  96441. this._addComponent(component);
  96442. }
  96443. if (!this._selectionOctree) {
  96444. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  96445. }
  96446. var worldExtends = this.getWorldExtends();
  96447. // Update octree
  96448. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  96449. return this._selectionOctree;
  96450. };
  96451. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  96452. get: function () {
  96453. return this._selectionOctree;
  96454. },
  96455. enumerable: true,
  96456. configurable: true
  96457. });
  96458. /**
  96459. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  96460. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  96461. * @param maxCapacity defines the maximum size of each block (64 by default)
  96462. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  96463. * @returns the new octree
  96464. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  96465. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  96466. */
  96467. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  96468. if (maxCapacity === void 0) { maxCapacity = 64; }
  96469. if (maxDepth === void 0) { maxDepth = 2; }
  96470. var scene = this.getScene();
  96471. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  96472. if (!component) {
  96473. component = new OctreeSceneComponent(scene);
  96474. scene._addComponent(component);
  96475. }
  96476. if (!this._submeshesOctree) {
  96477. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  96478. }
  96479. this.computeWorldMatrix(true);
  96480. var boundingInfo = this.getBoundingInfo();
  96481. // Update octree
  96482. var bbox = boundingInfo.boundingBox;
  96483. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  96484. return this._submeshesOctree;
  96485. };
  96486. /**
  96487. * Defines the octree scene component responsible to manage any octrees
  96488. * in a given scene.
  96489. */
  96490. var OctreeSceneComponent = /** @class */ (function () {
  96491. /**
  96492. * Creates a new instance of the component for the given scene
  96493. * @param scene Defines the scene to register the component in
  96494. */
  96495. function OctreeSceneComponent(scene) {
  96496. /**
  96497. * The component name helpfull to identify the component in the list of scene components.
  96498. */
  96499. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  96500. /**
  96501. * Indicates if the meshes have been checked to make sure they are isEnabled()
  96502. */
  96503. this.checksIsEnabled = true;
  96504. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  96505. this.scene = scene;
  96506. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  96507. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  96508. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  96509. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  96510. }
  96511. /**
  96512. * Registers the component in a given scene
  96513. */
  96514. OctreeSceneComponent.prototype.register = function () {
  96515. var _this = this;
  96516. this.scene.onMeshRemovedObservable.add(function (mesh) {
  96517. var sceneOctree = _this.scene.selectionOctree;
  96518. if (sceneOctree !== undefined && sceneOctree !== null) {
  96519. var index = sceneOctree.dynamicContent.indexOf(mesh);
  96520. if (index !== -1) {
  96521. sceneOctree.dynamicContent.splice(index, 1);
  96522. }
  96523. }
  96524. });
  96525. this.scene.onMeshImportedObservable.add(function (mesh) {
  96526. var sceneOctree = _this.scene.selectionOctree;
  96527. if (sceneOctree !== undefined && sceneOctree !== null) {
  96528. sceneOctree.addMesh(mesh);
  96529. }
  96530. });
  96531. };
  96532. /**
  96533. * Return the list of active meshes
  96534. * @returns the list of active meshes
  96535. */
  96536. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  96537. if (this.scene._selectionOctree) {
  96538. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  96539. return selection;
  96540. }
  96541. return this.scene._getDefaultMeshCandidates();
  96542. };
  96543. /**
  96544. * Return the list of active sub meshes
  96545. * @param mesh The mesh to get the candidates sub meshes from
  96546. * @returns the list of active sub meshes
  96547. */
  96548. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  96549. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  96550. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  96551. return intersections;
  96552. }
  96553. return this.scene._getDefaultSubMeshCandidates(mesh);
  96554. };
  96555. /**
  96556. * Return the list of sub meshes intersecting with a given local ray
  96557. * @param mesh defines the mesh to find the submesh for
  96558. * @param localRay defines the ray in local space
  96559. * @returns the list of intersecting sub meshes
  96560. */
  96561. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  96562. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  96563. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  96564. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  96565. return intersections;
  96566. }
  96567. return this.scene._getDefaultSubMeshCandidates(mesh);
  96568. };
  96569. /**
  96570. * Return the list of sub meshes colliding with a collider
  96571. * @param mesh defines the mesh to find the submesh for
  96572. * @param collider defines the collider to evaluate the collision against
  96573. * @returns the list of colliding sub meshes
  96574. */
  96575. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  96576. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  96577. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  96578. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  96579. return intersections;
  96580. }
  96581. return this.scene._getDefaultSubMeshCandidates(mesh);
  96582. };
  96583. /**
  96584. * Rebuilds the elements related to this component in case of
  96585. * context lost for instance.
  96586. */
  96587. OctreeSceneComponent.prototype.rebuild = function () {
  96588. // Nothing to do here.
  96589. };
  96590. /**
  96591. * Disposes the component and the associated ressources.
  96592. */
  96593. OctreeSceneComponent.prototype.dispose = function () {
  96594. // Nothing to do here.
  96595. };
  96596. return OctreeSceneComponent;
  96597. }());
  96598. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  96599. })(BABYLON || (BABYLON = {}));
  96600. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  96601. var BABYLON;
  96602. (function (BABYLON) {
  96603. /**
  96604. * Postprocess used to generate anaglyphic rendering
  96605. */
  96606. var AnaglyphPostProcess = /** @class */ (function (_super) {
  96607. __extends(AnaglyphPostProcess, _super);
  96608. /**
  96609. * Creates a new AnaglyphPostProcess
  96610. * @param name defines postprocess name
  96611. * @param options defines creation options or target ratio scale
  96612. * @param rigCameras defines cameras using this postprocess
  96613. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  96614. * @param engine defines hosting engine
  96615. * @param reusable defines if the postprocess will be reused multiple times per frame
  96616. */
  96617. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  96618. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  96619. _this._passedProcess = rigCameras[0]._rigPostProcess;
  96620. _this.onApplyObservable.add(function (effect) {
  96621. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  96622. });
  96623. return _this;
  96624. }
  96625. return AnaglyphPostProcess;
  96626. }(BABYLON.PostProcess));
  96627. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  96628. })(BABYLON || (BABYLON = {}));
  96629. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  96630. var BABYLON;
  96631. (function (BABYLON) {
  96632. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  96633. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96634. });
  96635. /**
  96636. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  96637. */
  96638. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  96639. __extends(AnaglyphArcRotateCamera, _super);
  96640. /**
  96641. * Creates a new AnaglyphArcRotateCamera
  96642. * @param name defines camera name
  96643. * @param alpha defines alpha angle (in radians)
  96644. * @param beta defines beta angle (in radians)
  96645. * @param radius defines radius
  96646. * @param target defines camera target
  96647. * @param interaxialDistance defines distance between each color axis
  96648. * @param scene defines the hosting scene
  96649. */
  96650. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  96651. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  96652. _this.interaxialDistance = interaxialDistance;
  96653. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96654. return _this;
  96655. }
  96656. /**
  96657. * Gets camera class name
  96658. * @returns AnaglyphArcRotateCamera
  96659. */
  96660. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  96661. return "AnaglyphArcRotateCamera";
  96662. };
  96663. return AnaglyphArcRotateCamera;
  96664. }(BABYLON.ArcRotateCamera));
  96665. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  96666. })(BABYLON || (BABYLON = {}));
  96667. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  96668. var BABYLON;
  96669. (function (BABYLON) {
  96670. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  96671. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96672. });
  96673. /**
  96674. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  96675. */
  96676. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  96677. __extends(AnaglyphFreeCamera, _super);
  96678. /**
  96679. * Creates a new AnaglyphFreeCamera
  96680. * @param name defines camera name
  96681. * @param position defines initial position
  96682. * @param interaxialDistance defines distance between each color axis
  96683. * @param scene defines the hosting scene
  96684. */
  96685. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  96686. var _this = _super.call(this, name, position, scene) || this;
  96687. _this.interaxialDistance = interaxialDistance;
  96688. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96689. return _this;
  96690. }
  96691. /**
  96692. * Gets camera class name
  96693. * @returns AnaglyphFreeCamera
  96694. */
  96695. AnaglyphFreeCamera.prototype.getClassName = function () {
  96696. return "AnaglyphFreeCamera";
  96697. };
  96698. return AnaglyphFreeCamera;
  96699. }(BABYLON.FreeCamera));
  96700. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  96701. })(BABYLON || (BABYLON = {}));
  96702. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  96703. var BABYLON;
  96704. (function (BABYLON) {
  96705. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  96706. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96707. });
  96708. /**
  96709. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  96710. */
  96711. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  96712. __extends(AnaglyphGamepadCamera, _super);
  96713. /**
  96714. * Creates a new AnaglyphGamepadCamera
  96715. * @param name defines camera name
  96716. * @param position defines initial position
  96717. * @param interaxialDistance defines distance between each color axis
  96718. * @param scene defines the hosting scene
  96719. */
  96720. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  96721. var _this = _super.call(this, name, position, scene) || this;
  96722. _this.interaxialDistance = interaxialDistance;
  96723. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96724. return _this;
  96725. }
  96726. /**
  96727. * Gets camera class name
  96728. * @returns AnaglyphGamepadCamera
  96729. */
  96730. AnaglyphGamepadCamera.prototype.getClassName = function () {
  96731. return "AnaglyphGamepadCamera";
  96732. };
  96733. return AnaglyphGamepadCamera;
  96734. }(BABYLON.GamepadCamera));
  96735. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  96736. })(BABYLON || (BABYLON = {}));
  96737. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  96738. var BABYLON;
  96739. (function (BABYLON) {
  96740. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  96741. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96742. });
  96743. /**
  96744. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  96745. */
  96746. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  96747. __extends(AnaglyphUniversalCamera, _super);
  96748. /**
  96749. * Creates a new AnaglyphUniversalCamera
  96750. * @param name defines camera name
  96751. * @param position defines initial position
  96752. * @param interaxialDistance defines distance between each color axis
  96753. * @param scene defines the hosting scene
  96754. */
  96755. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  96756. var _this = _super.call(this, name, position, scene) || this;
  96757. _this.interaxialDistance = interaxialDistance;
  96758. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96759. return _this;
  96760. }
  96761. /**
  96762. * Gets camera class name
  96763. * @returns AnaglyphUniversalCamera
  96764. */
  96765. AnaglyphUniversalCamera.prototype.getClassName = function () {
  96766. return "AnaglyphUniversalCamera";
  96767. };
  96768. return AnaglyphUniversalCamera;
  96769. }(BABYLON.UniversalCamera));
  96770. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  96771. })(BABYLON || (BABYLON = {}));
  96772. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  96773. var BABYLON;
  96774. (function (BABYLON) {
  96775. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  96776. __extends(StereoscopicInterlacePostProcess, _super);
  96777. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  96778. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  96779. _this._passedProcess = rigCameras[0]._rigPostProcess;
  96780. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  96781. _this.onSizeChangedObservable.add(function () {
  96782. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  96783. });
  96784. _this.onApplyObservable.add(function (effect) {
  96785. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  96786. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  96787. });
  96788. return _this;
  96789. }
  96790. return StereoscopicInterlacePostProcess;
  96791. }(BABYLON.PostProcess));
  96792. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  96793. })(BABYLON || (BABYLON = {}));
  96794. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  96795. var BABYLON;
  96796. (function (BABYLON) {
  96797. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  96798. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96799. });
  96800. /**
  96801. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  96802. */
  96803. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  96804. __extends(StereoscopicArcRotateCamera, _super);
  96805. /**
  96806. * Creates a new StereoscopicArcRotateCamera
  96807. * @param name defines camera name
  96808. * @param alpha defines alpha angle (in radians)
  96809. * @param beta defines beta angle (in radians)
  96810. * @param radius defines radius
  96811. * @param target defines camera target
  96812. * @param interaxialDistance defines distance between each color axis
  96813. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96814. * @param scene defines the hosting scene
  96815. */
  96816. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  96817. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  96818. _this.interaxialDistance = interaxialDistance;
  96819. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96820. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96821. return _this;
  96822. }
  96823. /**
  96824. * Gets camera class name
  96825. * @returns StereoscopicArcRotateCamera
  96826. */
  96827. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  96828. return "StereoscopicArcRotateCamera";
  96829. };
  96830. return StereoscopicArcRotateCamera;
  96831. }(BABYLON.ArcRotateCamera));
  96832. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  96833. })(BABYLON || (BABYLON = {}));
  96834. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  96835. var BABYLON;
  96836. (function (BABYLON) {
  96837. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96838. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96839. });
  96840. /**
  96841. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  96842. */
  96843. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  96844. __extends(StereoscopicFreeCamera, _super);
  96845. /**
  96846. * Creates a new StereoscopicFreeCamera
  96847. * @param name defines camera name
  96848. * @param position defines initial position
  96849. * @param interaxialDistance defines distance between each color axis
  96850. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96851. * @param scene defines the hosting scene
  96852. */
  96853. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96854. var _this = _super.call(this, name, position, scene) || this;
  96855. _this.interaxialDistance = interaxialDistance;
  96856. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96857. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96858. return _this;
  96859. }
  96860. /**
  96861. * Gets camera class name
  96862. * @returns StereoscopicFreeCamera
  96863. */
  96864. StereoscopicFreeCamera.prototype.getClassName = function () {
  96865. return "StereoscopicFreeCamera";
  96866. };
  96867. return StereoscopicFreeCamera;
  96868. }(BABYLON.FreeCamera));
  96869. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  96870. })(BABYLON || (BABYLON = {}));
  96871. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  96872. var BABYLON;
  96873. (function (BABYLON) {
  96874. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  96875. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96876. });
  96877. /**
  96878. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  96879. */
  96880. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  96881. __extends(StereoscopicGamepadCamera, _super);
  96882. /**
  96883. * Creates a new StereoscopicGamepadCamera
  96884. * @param name defines camera name
  96885. * @param position defines initial position
  96886. * @param interaxialDistance defines distance between each color axis
  96887. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96888. * @param scene defines the hosting scene
  96889. */
  96890. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96891. var _this = _super.call(this, name, position, scene) || this;
  96892. _this.interaxialDistance = interaxialDistance;
  96893. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96894. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96895. return _this;
  96896. }
  96897. /**
  96898. * Gets camera class name
  96899. * @returns StereoscopicGamepadCamera
  96900. */
  96901. StereoscopicGamepadCamera.prototype.getClassName = function () {
  96902. return "StereoscopicGamepadCamera";
  96903. };
  96904. return StereoscopicGamepadCamera;
  96905. }(BABYLON.GamepadCamera));
  96906. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  96907. })(BABYLON || (BABYLON = {}));
  96908. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  96909. var BABYLON;
  96910. (function (BABYLON) {
  96911. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96912. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96913. });
  96914. /**
  96915. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  96916. */
  96917. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  96918. __extends(StereoscopicUniversalCamera, _super);
  96919. /**
  96920. * Creates a new StereoscopicUniversalCamera
  96921. * @param name defines camera name
  96922. * @param position defines initial position
  96923. * @param interaxialDistance defines distance between each color axis
  96924. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96925. * @param scene defines the hosting scene
  96926. */
  96927. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96928. var _this = _super.call(this, name, position, scene) || this;
  96929. _this.interaxialDistance = interaxialDistance;
  96930. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96931. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96932. return _this;
  96933. }
  96934. /**
  96935. * Gets camera class name
  96936. * @returns StereoscopicUniversalCamera
  96937. */
  96938. StereoscopicUniversalCamera.prototype.getClassName = function () {
  96939. return "StereoscopicUniversalCamera";
  96940. };
  96941. return StereoscopicUniversalCamera;
  96942. }(BABYLON.UniversalCamera));
  96943. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  96944. })(BABYLON || (BABYLON = {}));
  96945. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  96946. var BABYLON;
  96947. (function (BABYLON) {
  96948. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  96949. __extends(VRDistortionCorrectionPostProcess, _super);
  96950. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  96951. var _this = _super.call(this, name, "vrDistortionCorrection", [
  96952. 'LensCenter',
  96953. 'Scale',
  96954. 'ScaleIn',
  96955. 'HmdWarpParam'
  96956. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  96957. _this._isRightEye = isRightEye;
  96958. _this._distortionFactors = vrMetrics.distortionK;
  96959. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  96960. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  96961. _this.adaptScaleToCurrentViewport = true;
  96962. _this.onSizeChangedObservable.add(function () {
  96963. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  96964. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  96965. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  96966. });
  96967. _this.onApplyObservable.add(function (effect) {
  96968. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  96969. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  96970. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  96971. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  96972. });
  96973. return _this;
  96974. }
  96975. return VRDistortionCorrectionPostProcess;
  96976. }(BABYLON.PostProcess));
  96977. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  96978. })(BABYLON || (BABYLON = {}));
  96979. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  96980. var BABYLON;
  96981. (function (BABYLON) {
  96982. /**
  96983. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  96984. * Screen rotation is taken into account.
  96985. */
  96986. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  96987. function FreeCameraDeviceOrientationInput() {
  96988. var _this = this;
  96989. this._screenOrientationAngle = 0;
  96990. this._screenQuaternion = new BABYLON.Quaternion();
  96991. this._alpha = 0;
  96992. this._beta = 0;
  96993. this._gamma = 0;
  96994. this._orientationChanged = function () {
  96995. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  96996. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  96997. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  96998. };
  96999. this._deviceOrientation = function (evt) {
  97000. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  97001. _this._beta = evt.beta !== null ? evt.beta : 0;
  97002. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  97003. };
  97004. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  97005. this._orientationChanged();
  97006. }
  97007. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  97008. get: function () {
  97009. return this._camera;
  97010. },
  97011. set: function (camera) {
  97012. this._camera = camera;
  97013. if (this._camera != null && !this._camera.rotationQuaternion) {
  97014. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  97015. }
  97016. },
  97017. enumerable: true,
  97018. configurable: true
  97019. });
  97020. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  97021. window.addEventListener("orientationchange", this._orientationChanged);
  97022. window.addEventListener("deviceorientation", this._deviceOrientation);
  97023. //In certain cases, the attach control is called AFTER orientation was changed,
  97024. //So this is needed.
  97025. this._orientationChanged();
  97026. };
  97027. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  97028. window.removeEventListener("orientationchange", this._orientationChanged);
  97029. window.removeEventListener("deviceorientation", this._deviceOrientation);
  97030. };
  97031. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  97032. //if no device orientation provided, don't update the rotation.
  97033. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  97034. if (!this._alpha)
  97035. return;
  97036. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  97037. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  97038. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  97039. //Mirror on XY Plane
  97040. this._camera.rotationQuaternion.z *= -1;
  97041. this._camera.rotationQuaternion.w *= -1;
  97042. };
  97043. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  97044. return "FreeCameraDeviceOrientationInput";
  97045. };
  97046. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  97047. return "deviceOrientation";
  97048. };
  97049. return FreeCameraDeviceOrientationInput;
  97050. }());
  97051. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  97052. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  97053. })(BABYLON || (BABYLON = {}));
  97054. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  97055. var BABYLON;
  97056. (function (BABYLON) {
  97057. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  97058. function ArcRotateCameraVRDeviceOrientationInput() {
  97059. this.alphaCorrection = 1;
  97060. this.betaCorrection = 1;
  97061. this.gammaCorrection = 1;
  97062. this._alpha = 0;
  97063. this._gamma = 0;
  97064. this._dirty = false;
  97065. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  97066. }
  97067. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  97068. this.camera.attachControl(element, noPreventDefault);
  97069. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  97070. };
  97071. /** @hidden */
  97072. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  97073. if (evt.alpha !== null) {
  97074. this._alpha = +evt.alpha | 0;
  97075. }
  97076. if (evt.gamma !== null) {
  97077. this._gamma = +evt.gamma | 0;
  97078. }
  97079. this._dirty = true;
  97080. };
  97081. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  97082. if (this._dirty) {
  97083. this._dirty = false;
  97084. if (this._gamma < 0) {
  97085. this._gamma = 180 + this._gamma;
  97086. }
  97087. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  97088. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  97089. }
  97090. };
  97091. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  97092. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  97093. };
  97094. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  97095. return "ArcRotateCameraVRDeviceOrientationInput";
  97096. };
  97097. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  97098. return "VRDeviceOrientation";
  97099. };
  97100. return ArcRotateCameraVRDeviceOrientationInput;
  97101. }());
  97102. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  97103. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  97104. })(BABYLON || (BABYLON = {}));
  97105. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  97106. var BABYLON;
  97107. (function (BABYLON) {
  97108. var VRCameraMetrics = /** @class */ (function () {
  97109. function VRCameraMetrics() {
  97110. this.compensateDistortion = true;
  97111. }
  97112. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  97113. get: function () {
  97114. return this.hResolution / (2 * this.vResolution);
  97115. },
  97116. enumerable: true,
  97117. configurable: true
  97118. });
  97119. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  97120. get: function () {
  97121. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  97122. },
  97123. enumerable: true,
  97124. configurable: true
  97125. });
  97126. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  97127. get: function () {
  97128. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  97129. var h = (4 * meters) / this.hScreenSize;
  97130. return BABYLON.Matrix.Translation(h, 0, 0);
  97131. },
  97132. enumerable: true,
  97133. configurable: true
  97134. });
  97135. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  97136. get: function () {
  97137. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  97138. var h = (4 * meters) / this.hScreenSize;
  97139. return BABYLON.Matrix.Translation(-h, 0, 0);
  97140. },
  97141. enumerable: true,
  97142. configurable: true
  97143. });
  97144. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  97145. get: function () {
  97146. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  97147. },
  97148. enumerable: true,
  97149. configurable: true
  97150. });
  97151. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  97152. get: function () {
  97153. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  97154. },
  97155. enumerable: true,
  97156. configurable: true
  97157. });
  97158. VRCameraMetrics.GetDefault = function () {
  97159. var result = new VRCameraMetrics();
  97160. result.hResolution = 1280;
  97161. result.vResolution = 800;
  97162. result.hScreenSize = 0.149759993;
  97163. result.vScreenSize = 0.0935999975;
  97164. result.vScreenCenter = 0.0467999987;
  97165. result.eyeToScreenDistance = 0.0410000011;
  97166. result.lensSeparationDistance = 0.0635000020;
  97167. result.interpupillaryDistance = 0.0640000030;
  97168. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  97169. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  97170. result.postProcessScaleFactor = 1.714605507808412;
  97171. result.lensCenterOffset = 0.151976421;
  97172. return result;
  97173. };
  97174. return VRCameraMetrics;
  97175. }());
  97176. BABYLON.VRCameraMetrics = VRCameraMetrics;
  97177. })(BABYLON || (BABYLON = {}));
  97178. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  97179. var BABYLON;
  97180. (function (BABYLON) {
  97181. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  97182. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  97183. });
  97184. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  97185. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  97186. });
  97187. /**
  97188. * This represents a WebVR camera.
  97189. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  97190. * @example http://doc.babylonjs.com/how_to/webvr_camera
  97191. */
  97192. var WebVRFreeCamera = /** @class */ (function (_super) {
  97193. __extends(WebVRFreeCamera, _super);
  97194. /**
  97195. * Instantiates a WebVRFreeCamera.
  97196. * @param name The name of the WebVRFreeCamera
  97197. * @param position The starting anchor position for the camera
  97198. * @param scene The scene the camera belongs to
  97199. * @param webVROptions a set of customizable options for the webVRCamera
  97200. */
  97201. function WebVRFreeCamera(name, position, scene, webVROptions) {
  97202. if (webVROptions === void 0) { webVROptions = {}; }
  97203. var _this = _super.call(this, name, position, scene) || this;
  97204. _this.webVROptions = webVROptions;
  97205. /**
  97206. * @hidden
  97207. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  97208. */
  97209. _this._vrDevice = null;
  97210. /**
  97211. * The rawPose of the vrDevice.
  97212. */
  97213. _this.rawPose = null;
  97214. _this._specsVersion = "1.1";
  97215. _this._attached = false;
  97216. _this._descendants = [];
  97217. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  97218. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  97219. /** @hidden */
  97220. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  97221. _this._standingMatrix = null;
  97222. /**
  97223. * Represents device position in babylon space.
  97224. */
  97225. _this.devicePosition = BABYLON.Vector3.Zero();
  97226. /**
  97227. * Represents device rotation in babylon space.
  97228. */
  97229. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  97230. /**
  97231. * The scale of the device to be used when translating from device space to babylon space.
  97232. */
  97233. _this.deviceScaleFactor = 1;
  97234. _this._deviceToWorld = BABYLON.Matrix.Identity();
  97235. _this._worldToDevice = BABYLON.Matrix.Identity();
  97236. /**
  97237. * References to the webVR controllers for the vrDevice.
  97238. */
  97239. _this.controllers = [];
  97240. /**
  97241. * Emits an event when a controller is attached.
  97242. */
  97243. _this.onControllersAttachedObservable = new BABYLON.Observable();
  97244. /**
  97245. * Emits an event when a controller's mesh has been loaded;
  97246. */
  97247. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  97248. /**
  97249. * Emits an event when the HMD's pose has been updated.
  97250. */
  97251. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  97252. _this._poseSet = false;
  97253. /**
  97254. * If the rig cameras be used as parent instead of this camera.
  97255. */
  97256. _this.rigParenting = true;
  97257. _this._defaultHeight = undefined;
  97258. _this._htmlElementAttached = null;
  97259. _this._detachIfAttached = function () {
  97260. var vrDisplay = _this.getEngine().getVRDevice();
  97261. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  97262. _this.detachControl(_this._htmlElementAttached);
  97263. }
  97264. };
  97265. _this._workingVector = BABYLON.Vector3.Zero();
  97266. _this._oneVector = BABYLON.Vector3.One();
  97267. _this._workingMatrix = BABYLON.Matrix.Identity();
  97268. _this._tmpMatrix = new BABYLON.Matrix();
  97269. _this._cache.position = BABYLON.Vector3.Zero();
  97270. if (webVROptions.defaultHeight) {
  97271. _this._defaultHeight = webVROptions.defaultHeight;
  97272. _this.position.y = _this._defaultHeight;
  97273. }
  97274. _this.minZ = 0.1;
  97275. //legacy support - the compensation boolean was removed.
  97276. if (arguments.length === 5) {
  97277. _this.webVROptions = arguments[4];
  97278. }
  97279. // default webVR options
  97280. if (_this.webVROptions.trackPosition == undefined) {
  97281. _this.webVROptions.trackPosition = true;
  97282. }
  97283. if (_this.webVROptions.controllerMeshes == undefined) {
  97284. _this.webVROptions.controllerMeshes = true;
  97285. }
  97286. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  97287. _this.webVROptions.defaultLightingOnControllers = true;
  97288. }
  97289. _this.rotationQuaternion = new BABYLON.Quaternion();
  97290. if (_this.webVROptions && _this.webVROptions.positionScale) {
  97291. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  97292. }
  97293. //enable VR
  97294. var engine = _this.getEngine();
  97295. _this._onVREnabled = function (success) { if (success) {
  97296. _this.initControllers();
  97297. } };
  97298. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  97299. engine.initWebVR().add(function (event) {
  97300. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  97301. return;
  97302. }
  97303. _this._vrDevice = event.vrDisplay;
  97304. //reset the rig parameters.
  97305. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  97306. if (_this._attached) {
  97307. _this.getEngine().enableVR();
  97308. }
  97309. });
  97310. if (typeof (VRFrameData) !== "undefined")
  97311. _this._frameData = new VRFrameData();
  97312. /**
  97313. * The idea behind the following lines:
  97314. * objects that have the camera as parent should actually have the rig cameras as a parent.
  97315. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  97316. * the second will not show it correctly.
  97317. *
  97318. * To solve this - each object that has the camera as parent will be added to a protected array.
  97319. * When the rig camera renders, it will take this array and set all of those to be its children.
  97320. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  97321. * Amazing!
  97322. */
  97323. scene.onBeforeCameraRenderObservable.add(function (camera) {
  97324. if (camera.parent === _this && _this.rigParenting) {
  97325. _this._descendants = _this.getDescendants(true, function (n) {
  97326. // don't take the cameras or the controllers!
  97327. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  97328. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  97329. return !isController && !isRigCamera;
  97330. });
  97331. _this._descendants.forEach(function (node) {
  97332. node.parent = camera;
  97333. });
  97334. }
  97335. });
  97336. scene.onAfterCameraRenderObservable.add(function (camera) {
  97337. if (camera.parent === _this && _this.rigParenting) {
  97338. _this._descendants.forEach(function (node) {
  97339. node.parent = _this;
  97340. });
  97341. }
  97342. });
  97343. return _this;
  97344. }
  97345. /**
  97346. * Gets the device distance from the ground in meters.
  97347. * @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.
  97348. */
  97349. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  97350. if (this._standingMatrix) {
  97351. // Add standing matrix offset to get real offset from ground in room
  97352. this._standingMatrix.getTranslationToRef(this._workingVector);
  97353. return this._deviceRoomPosition.y + this._workingVector.y;
  97354. }
  97355. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  97356. return this._defaultHeight || 0;
  97357. };
  97358. /**
  97359. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  97360. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  97361. */
  97362. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  97363. var _this = this;
  97364. if (callback === void 0) { callback = function (bool) { }; }
  97365. // Use standing matrix if available
  97366. this.getEngine().initWebVRAsync().then(function (result) {
  97367. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  97368. callback(false);
  97369. }
  97370. else {
  97371. _this._standingMatrix = new BABYLON.Matrix();
  97372. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  97373. if (!_this.getScene().useRightHandedSystem) {
  97374. [2, 6, 8, 9, 14].forEach(function (num) {
  97375. if (_this._standingMatrix) {
  97376. _this._standingMatrix.m[num] *= -1;
  97377. }
  97378. });
  97379. }
  97380. callback(true);
  97381. }
  97382. });
  97383. };
  97384. /**
  97385. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  97386. * @returns A promise with a boolean set to if the standing matrix is supported.
  97387. */
  97388. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  97389. var _this = this;
  97390. return new Promise(function (res, rej) {
  97391. _this.useStandingMatrix(function (supported) {
  97392. res(supported);
  97393. });
  97394. });
  97395. };
  97396. /**
  97397. * Disposes the camera
  97398. */
  97399. WebVRFreeCamera.prototype.dispose = function () {
  97400. this._detachIfAttached();
  97401. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  97402. _super.prototype.dispose.call(this);
  97403. };
  97404. /**
  97405. * Gets a vrController by name.
  97406. * @param name The name of the controller to retreive
  97407. * @returns the controller matching the name specified or null if not found
  97408. */
  97409. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  97410. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  97411. var gp = _a[_i];
  97412. if (gp.hand === name) {
  97413. return gp;
  97414. }
  97415. }
  97416. return null;
  97417. };
  97418. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  97419. /**
  97420. * The controller corrisponding to the users left hand.
  97421. */
  97422. get: function () {
  97423. if (!this._leftController) {
  97424. this._leftController = this.getControllerByName("left");
  97425. }
  97426. return this._leftController;
  97427. },
  97428. enumerable: true,
  97429. configurable: true
  97430. });
  97431. ;
  97432. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  97433. /**
  97434. * The controller corrisponding to the users right hand.
  97435. */
  97436. get: function () {
  97437. if (!this._rightController) {
  97438. this._rightController = this.getControllerByName("right");
  97439. }
  97440. return this._rightController;
  97441. },
  97442. enumerable: true,
  97443. configurable: true
  97444. });
  97445. ;
  97446. /**
  97447. * Casts a ray forward from the vrCamera's gaze.
  97448. * @param length Length of the ray (default: 100)
  97449. * @returns the ray corrisponding to the gaze
  97450. */
  97451. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  97452. if (length === void 0) { length = 100; }
  97453. if (this.leftCamera) {
  97454. // Use left eye to avoid computation to compute center on every call
  97455. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  97456. }
  97457. else {
  97458. return _super.prototype.getForwardRay.call(this, length);
  97459. }
  97460. };
  97461. /**
  97462. * @hidden
  97463. * Updates the camera based on device's frame data
  97464. */
  97465. WebVRFreeCamera.prototype._checkInputs = function () {
  97466. if (this._vrDevice && this._vrDevice.isPresenting) {
  97467. this._vrDevice.getFrameData(this._frameData);
  97468. this.updateFromDevice(this._frameData.pose);
  97469. }
  97470. _super.prototype._checkInputs.call(this);
  97471. };
  97472. /**
  97473. * Updates the poseControlled values based on the input device pose.
  97474. * @param poseData Pose coming from the device
  97475. */
  97476. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  97477. if (poseData && poseData.orientation) {
  97478. this.rawPose = poseData;
  97479. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  97480. if (this.getScene().useRightHandedSystem) {
  97481. this._deviceRoomRotationQuaternion.z *= -1;
  97482. this._deviceRoomRotationQuaternion.w *= -1;
  97483. }
  97484. if (this.webVROptions.trackPosition && this.rawPose.position) {
  97485. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  97486. if (this.getScene().useRightHandedSystem) {
  97487. this._deviceRoomPosition.z *= -1;
  97488. }
  97489. }
  97490. this._poseSet = true;
  97491. }
  97492. };
  97493. /**
  97494. * WebVR's attach control will start broadcasting frames to the device.
  97495. * Note that in certain browsers (chrome for example) this function must be called
  97496. * within a user-interaction callback. Example:
  97497. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  97498. *
  97499. * @param element html element to attach the vrDevice to
  97500. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  97501. */
  97502. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  97503. _super.prototype.attachControl.call(this, element, noPreventDefault);
  97504. this._attached = true;
  97505. this._htmlElementAttached = element;
  97506. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  97507. if (this._vrDevice) {
  97508. this.getEngine().enableVR();
  97509. }
  97510. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  97511. };
  97512. /**
  97513. * Detaches the camera from the html element and disables VR
  97514. *
  97515. * @param element html element to detach from
  97516. */
  97517. WebVRFreeCamera.prototype.detachControl = function (element) {
  97518. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  97519. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  97520. _super.prototype.detachControl.call(this, element);
  97521. this._attached = false;
  97522. this.getEngine().disableVR();
  97523. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  97524. };
  97525. /**
  97526. * @returns the name of this class
  97527. */
  97528. WebVRFreeCamera.prototype.getClassName = function () {
  97529. return "WebVRFreeCamera";
  97530. };
  97531. /**
  97532. * Calls resetPose on the vrDisplay
  97533. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  97534. */
  97535. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  97536. //uses the vrDisplay's "resetPose()".
  97537. //pitch and roll won't be affected.
  97538. this._vrDevice.resetPose();
  97539. };
  97540. /**
  97541. * @hidden
  97542. * Updates the rig cameras (left and right eye)
  97543. */
  97544. WebVRFreeCamera.prototype._updateRigCameras = function () {
  97545. var camLeft = this._rigCameras[0];
  97546. var camRight = this._rigCameras[1];
  97547. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  97548. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  97549. camLeft.position.copyFrom(this._deviceRoomPosition);
  97550. camRight.position.copyFrom(this._deviceRoomPosition);
  97551. };
  97552. // Remove translation from 6dof headset if trackposition is set to false
  97553. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  97554. if (isViewMatrix === void 0) { isViewMatrix = false; }
  97555. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  97556. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  97557. if (!isViewMatrix) {
  97558. this._tmpMatrix.invert();
  97559. }
  97560. this._tmpMatrix.multiplyToRef(matrix, matrix);
  97561. }
  97562. };
  97563. /**
  97564. * @hidden
  97565. * Updates the cached values of the camera
  97566. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  97567. */
  97568. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  97569. var _this = this;
  97570. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  97571. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  97572. if (!this.updateCacheCalled) {
  97573. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  97574. this.updateCacheCalled = true;
  97575. this.update();
  97576. }
  97577. // Set working vector to the device position in room space rotated by the new rotation
  97578. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  97579. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  97580. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  97581. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  97582. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  97583. // Add translation from anchor position
  97584. this._deviceToWorld.getTranslationToRef(this._workingVector);
  97585. this._workingVector.addInPlace(this.position);
  97586. this._workingVector.subtractInPlace(this._cache.position);
  97587. this._deviceToWorld.setTranslation(this._workingVector);
  97588. // Set an inverted matrix to be used when updating the camera
  97589. this._deviceToWorld.invertToRef(this._worldToDevice);
  97590. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  97591. this.controllers.forEach(function (controller) {
  97592. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  97593. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  97594. controller.update();
  97595. });
  97596. }
  97597. if (!ignoreParentClass) {
  97598. _super.prototype._updateCache.call(this);
  97599. }
  97600. this.updateCacheCalled = false;
  97601. };
  97602. /**
  97603. * Updates the current device position and rotation in the babylon world
  97604. */
  97605. WebVRFreeCamera.prototype.update = function () {
  97606. // Get current device position in babylon world
  97607. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  97608. // Get current device rotation in babylon world
  97609. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  97610. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  97611. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  97612. if (this._poseSet) {
  97613. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  97614. }
  97615. _super.prototype.update.call(this);
  97616. };
  97617. /**
  97618. * @hidden
  97619. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  97620. * @returns an identity matrix
  97621. */
  97622. WebVRFreeCamera.prototype._getViewMatrix = function () {
  97623. return BABYLON.Matrix.Identity();
  97624. };
  97625. /**
  97626. * This function is called by the two RIG cameras.
  97627. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  97628. */
  97629. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  97630. var _this = this;
  97631. // Update the parent camera prior to using a child camera to avoid desynchronization
  97632. var parentCamera = this._cameraRigParams["parentCamera"];
  97633. parentCamera._updateCache();
  97634. //WebVR 1.1
  97635. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  97636. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  97637. if (!this.getScene().useRightHandedSystem) {
  97638. [2, 6, 8, 9, 14].forEach(function (num) {
  97639. _this._webvrViewMatrix.m[num] *= -1;
  97640. });
  97641. }
  97642. // update the camera rotation matrix
  97643. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  97644. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  97645. // Computing target and final matrix
  97646. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  97647. // should the view matrix be updated with scale and position offset?
  97648. if (parentCamera.deviceScaleFactor !== 1) {
  97649. this._webvrViewMatrix.invert();
  97650. // scale the position, if set
  97651. if (parentCamera.deviceScaleFactor) {
  97652. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  97653. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  97654. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  97655. }
  97656. this._webvrViewMatrix.invert();
  97657. }
  97658. // Remove translation from 6dof headset if trackposition is set to false
  97659. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  97660. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  97661. // Compute global position
  97662. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  97663. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  97664. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  97665. this._workingMatrix.getTranslationToRef(this._globalPosition);
  97666. this._markSyncedWithParent();
  97667. return this._webvrViewMatrix;
  97668. };
  97669. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  97670. var _this = this;
  97671. var parentCamera = this.parent;
  97672. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  97673. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  97674. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  97675. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  97676. //babylon compatible matrix
  97677. if (!this.getScene().useRightHandedSystem) {
  97678. [8, 9, 10, 11].forEach(function (num) {
  97679. _this._projectionMatrix.m[num] *= -1;
  97680. });
  97681. }
  97682. return this._projectionMatrix;
  97683. };
  97684. /**
  97685. * Initializes the controllers and their meshes
  97686. */
  97687. WebVRFreeCamera.prototype.initControllers = function () {
  97688. var _this = this;
  97689. this.controllers = [];
  97690. var manager = this.getScene().gamepadManager;
  97691. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  97692. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  97693. var webVrController = gamepad;
  97694. if (webVrController.defaultModel) {
  97695. webVrController.defaultModel.setEnabled(false);
  97696. }
  97697. if (webVrController.hand === "right") {
  97698. _this._rightController = null;
  97699. }
  97700. if (webVrController.hand === "left") {
  97701. _this._leftController = null;
  97702. }
  97703. var controllerIndex = _this.controllers.indexOf(webVrController);
  97704. if (controllerIndex !== -1) {
  97705. _this.controllers.splice(controllerIndex, 1);
  97706. }
  97707. }
  97708. });
  97709. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  97710. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  97711. var webVrController_1 = gamepad;
  97712. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  97713. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  97714. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  97715. if (_this.webVROptions.controllerMeshes) {
  97716. if (webVrController_1.defaultModel) {
  97717. webVrController_1.defaultModel.setEnabled(true);
  97718. }
  97719. else {
  97720. // Load the meshes
  97721. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  97722. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  97723. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  97724. if (_this.webVROptions.defaultLightingOnControllers) {
  97725. if (!_this._lightOnControllers) {
  97726. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  97727. }
  97728. var activateLightOnSubMeshes_1 = function (mesh, light) {
  97729. var children = mesh.getChildren();
  97730. if (children && children.length !== 0) {
  97731. children.forEach(function (mesh) {
  97732. light.includedOnlyMeshes.push(mesh);
  97733. activateLightOnSubMeshes_1(mesh, light);
  97734. });
  97735. }
  97736. };
  97737. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  97738. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  97739. }
  97740. });
  97741. }
  97742. }
  97743. webVrController_1.attachToPoseControlledCamera(_this);
  97744. // since this is async - sanity check. Is the controller already stored?
  97745. if (_this.controllers.indexOf(webVrController_1) === -1) {
  97746. //add to the controllers array
  97747. _this.controllers.push(webVrController_1);
  97748. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  97749. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  97750. // So we're overriding setting left & right manually to be sure
  97751. var firstViveWandDetected = false;
  97752. for (var i = 0; i < _this.controllers.length; i++) {
  97753. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  97754. if (!firstViveWandDetected) {
  97755. firstViveWandDetected = true;
  97756. _this.controllers[i].hand = "left";
  97757. }
  97758. else {
  97759. _this.controllers[i].hand = "right";
  97760. }
  97761. }
  97762. }
  97763. //did we find enough controllers? Great! let the developer know.
  97764. if (_this.controllers.length >= 2) {
  97765. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  97766. }
  97767. }
  97768. }
  97769. });
  97770. };
  97771. return WebVRFreeCamera;
  97772. }(BABYLON.FreeCamera));
  97773. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  97774. })(BABYLON || (BABYLON = {}));
  97775. //# sourceMappingURL=babylon.webVRCamera.js.map
  97776. var BABYLON;
  97777. (function (BABYLON) {
  97778. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  97779. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  97780. });
  97781. // We're mainly based on the logic defined into the FreeCamera code
  97782. /**
  97783. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  97784. * being tilted forward or back and left or right.
  97785. */
  97786. var DeviceOrientationCamera = /** @class */ (function (_super) {
  97787. __extends(DeviceOrientationCamera, _super);
  97788. /**
  97789. * Creates a new device orientation camera
  97790. * @param name The name of the camera
  97791. * @param position The start position camera
  97792. * @param scene The scene the camera belongs to
  97793. */
  97794. function DeviceOrientationCamera(name, position, scene) {
  97795. var _this = _super.call(this, name, position, scene) || this;
  97796. _this._quaternionCache = new BABYLON.Quaternion();
  97797. _this.inputs.addDeviceOrientation();
  97798. return _this;
  97799. }
  97800. /**
  97801. * Gets the current instance class name ("DeviceOrientationCamera").
  97802. * This helps avoiding instanceof at run time.
  97803. * @returns the class name
  97804. */
  97805. DeviceOrientationCamera.prototype.getClassName = function () {
  97806. return "DeviceOrientationCamera";
  97807. };
  97808. /**
  97809. * @hidden
  97810. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  97811. */
  97812. DeviceOrientationCamera.prototype._checkInputs = function () {
  97813. _super.prototype._checkInputs.call(this);
  97814. this._quaternionCache.copyFrom(this.rotationQuaternion);
  97815. if (this._initialQuaternion) {
  97816. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  97817. }
  97818. };
  97819. /**
  97820. * Reset the camera to its default orientation on the specified axis only.
  97821. * @param axis The axis to reset
  97822. */
  97823. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  97824. var _this = this;
  97825. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  97826. //can only work if this camera has a rotation quaternion already.
  97827. if (!this.rotationQuaternion)
  97828. return;
  97829. if (!this._initialQuaternion) {
  97830. this._initialQuaternion = new BABYLON.Quaternion();
  97831. }
  97832. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  97833. ['x', 'y', 'z'].forEach(function (axisName) {
  97834. if (!axis[axisName]) {
  97835. _this._initialQuaternion[axisName] = 0;
  97836. }
  97837. else {
  97838. _this._initialQuaternion[axisName] *= -1;
  97839. }
  97840. });
  97841. this._initialQuaternion.normalize();
  97842. //force rotation update
  97843. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  97844. };
  97845. return DeviceOrientationCamera;
  97846. }(BABYLON.FreeCamera));
  97847. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  97848. })(BABYLON || (BABYLON = {}));
  97849. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  97850. var BABYLON;
  97851. (function (BABYLON) {
  97852. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97853. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  97854. });
  97855. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  97856. __extends(VRDeviceOrientationFreeCamera, _super);
  97857. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97858. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97859. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97860. var _this = _super.call(this, name, position, scene) || this;
  97861. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97862. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97863. return _this;
  97864. }
  97865. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  97866. return "VRDeviceOrientationFreeCamera";
  97867. };
  97868. return VRDeviceOrientationFreeCamera;
  97869. }(BABYLON.DeviceOrientationCamera));
  97870. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  97871. })(BABYLON || (BABYLON = {}));
  97872. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  97873. var BABYLON;
  97874. (function (BABYLON) {
  97875. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97876. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  97877. });
  97878. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  97879. __extends(VRDeviceOrientationArcRotateCamera, _super);
  97880. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  97881. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97882. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97883. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  97884. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97885. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97886. _this.inputs.addVRDeviceOrientation();
  97887. return _this;
  97888. }
  97889. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  97890. return "VRDeviceOrientationArcRotateCamera";
  97891. };
  97892. return VRDeviceOrientationArcRotateCamera;
  97893. }(BABYLON.ArcRotateCamera));
  97894. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  97895. })(BABYLON || (BABYLON = {}));
  97896. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  97897. var BABYLON;
  97898. (function (BABYLON) {
  97899. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  97900. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  97901. });
  97902. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  97903. __extends(VRDeviceOrientationGamepadCamera, _super);
  97904. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97905. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97906. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97907. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  97908. _this.inputs.addGamepad();
  97909. return _this;
  97910. }
  97911. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  97912. return "VRDeviceOrientationGamepadCamera";
  97913. };
  97914. return VRDeviceOrientationGamepadCamera;
  97915. }(BABYLON.VRDeviceOrientationFreeCamera));
  97916. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  97917. })(BABYLON || (BABYLON = {}));
  97918. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  97919. var BABYLON;
  97920. (function (BABYLON) {
  97921. var VRExperienceHelperGazer = /** @class */ (function () {
  97922. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  97923. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  97924. this.scene = scene;
  97925. /** @hidden */
  97926. this._pointerDownOnMeshAsked = false;
  97927. /** @hidden */
  97928. this._isActionableMesh = false;
  97929. /** @hidden */
  97930. this._teleportationRequestInitiated = false;
  97931. /** @hidden */
  97932. this._teleportationBackRequestInitiated = false;
  97933. /** @hidden */
  97934. this._rotationRightAsked = false;
  97935. /** @hidden */
  97936. this._rotationLeftAsked = false;
  97937. /** @hidden */
  97938. this._dpadPressed = true;
  97939. /** @hidden */
  97940. this._activePointer = false;
  97941. this._id = VRExperienceHelperGazer._idCounter++;
  97942. // Gaze tracker
  97943. if (!gazeTrackerToClone) {
  97944. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  97945. this._gazeTracker.bakeCurrentTransformIntoVertices();
  97946. this._gazeTracker.isPickable = false;
  97947. this._gazeTracker.isVisible = false;
  97948. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  97949. targetMat.specularColor = BABYLON.Color3.Black();
  97950. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97951. targetMat.backFaceCulling = false;
  97952. this._gazeTracker.material = targetMat;
  97953. }
  97954. else {
  97955. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  97956. }
  97957. }
  97958. /** @hidden */
  97959. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  97960. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  97961. };
  97962. /** @hidden */
  97963. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  97964. this._pointerDownOnMeshAsked = true;
  97965. if (this._currentHit) {
  97966. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  97967. }
  97968. };
  97969. /** @hidden */
  97970. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  97971. if (this._currentHit) {
  97972. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  97973. }
  97974. this._pointerDownOnMeshAsked = false;
  97975. };
  97976. /** @hidden */
  97977. VRExperienceHelperGazer.prototype._activatePointer = function () {
  97978. this._activePointer = true;
  97979. };
  97980. /** @hidden */
  97981. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  97982. this._activePointer = false;
  97983. };
  97984. /** @hidden */
  97985. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  97986. if (distance === void 0) { distance = 100; }
  97987. };
  97988. VRExperienceHelperGazer.prototype.dispose = function () {
  97989. this._interactionsEnabled = false;
  97990. this._teleportationEnabled = false;
  97991. if (this._gazeTracker) {
  97992. this._gazeTracker.dispose();
  97993. }
  97994. };
  97995. VRExperienceHelperGazer._idCounter = 0;
  97996. return VRExperienceHelperGazer;
  97997. }());
  97998. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  97999. __extends(VRExperienceHelperControllerGazer, _super);
  98000. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  98001. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  98002. _this.webVRController = webVRController;
  98003. // Laser pointer
  98004. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  98005. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  98006. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  98007. laserPointerMaterial.alpha = 0.6;
  98008. _this._laserPointer.material = laserPointerMaterial;
  98009. _this._laserPointer.rotation.x = Math.PI / 2;
  98010. _this._laserPointer.position.z = -0.5;
  98011. _this._laserPointer.isVisible = false;
  98012. _this._laserPointer.isPickable = false;
  98013. if (!webVRController.mesh) {
  98014. // Create an empty mesh that is used prior to loading the high quality model
  98015. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  98016. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  98017. preloadPointerPose.rotation.x = -0.7;
  98018. preloadMesh.addChild(preloadPointerPose);
  98019. webVRController.attachToMesh(preloadMesh);
  98020. }
  98021. _this._setLaserPointerParent(webVRController.mesh);
  98022. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  98023. _this._setLaserPointerParent(mesh);
  98024. });
  98025. return _this;
  98026. }
  98027. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  98028. return this.webVRController.getForwardRay(length);
  98029. };
  98030. /** @hidden */
  98031. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  98032. _super.prototype._activatePointer.call(this);
  98033. this._laserPointer.isVisible = true;
  98034. };
  98035. /** @hidden */
  98036. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  98037. _super.prototype._deactivatePointer.call(this);
  98038. this._laserPointer.isVisible = false;
  98039. };
  98040. /** @hidden */
  98041. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  98042. this._laserPointer.material.emissiveColor = color;
  98043. };
  98044. /** @hidden */
  98045. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  98046. var makeNotPick = function (root) {
  98047. root.isPickable = false;
  98048. root.getChildMeshes().forEach(function (c) {
  98049. makeNotPick(c);
  98050. });
  98051. };
  98052. makeNotPick(mesh);
  98053. var childMeshes = mesh.getChildMeshes();
  98054. this.webVRController._pointingPoseNode = null;
  98055. for (var i = 0; i < childMeshes.length; i++) {
  98056. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  98057. mesh = childMeshes[i];
  98058. this.webVRController._pointingPoseNode = mesh;
  98059. break;
  98060. }
  98061. }
  98062. this._laserPointer.parent = mesh;
  98063. };
  98064. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  98065. if (distance === void 0) { distance = 100; }
  98066. this._laserPointer.scaling.y = distance;
  98067. this._laserPointer.position.z = -distance / 2;
  98068. };
  98069. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  98070. _super.prototype.dispose.call(this);
  98071. this._laserPointer.dispose();
  98072. if (this._meshAttachedObserver) {
  98073. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  98074. }
  98075. };
  98076. return VRExperienceHelperControllerGazer;
  98077. }(VRExperienceHelperGazer));
  98078. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  98079. __extends(VRExperienceHelperCameraGazer, _super);
  98080. function VRExperienceHelperCameraGazer(getCamera, scene) {
  98081. var _this = _super.call(this, scene) || this;
  98082. _this.getCamera = getCamera;
  98083. return _this;
  98084. }
  98085. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  98086. var camera = this.getCamera();
  98087. if (camera) {
  98088. return camera.getForwardRay(length);
  98089. }
  98090. else {
  98091. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  98092. }
  98093. };
  98094. return VRExperienceHelperCameraGazer;
  98095. }(VRExperienceHelperGazer));
  98096. /**
  98097. * Helps to quickly add VR support to an existing scene.
  98098. * See http://doc.babylonjs.com/how_to/webvr_helper
  98099. */
  98100. var VRExperienceHelper = /** @class */ (function () {
  98101. /**
  98102. * Instantiates a VRExperienceHelper.
  98103. * Helps to quickly add VR support to an existing scene.
  98104. * @param scene The scene the VRExperienceHelper belongs to.
  98105. * @param webVROptions Options to modify the vr experience helper's behavior.
  98106. */
  98107. function VRExperienceHelper(scene,
  98108. /** Options to modify the vr experience helper's behavior. */
  98109. webVROptions) {
  98110. if (webVROptions === void 0) { webVROptions = {}; }
  98111. var _this = this;
  98112. this.webVROptions = webVROptions;
  98113. // Can the system support WebVR, even if a headset isn't plugged in?
  98114. this._webVRsupported = false;
  98115. // If WebVR is supported, is a headset plugged in and are we ready to present?
  98116. this._webVRready = false;
  98117. // Are we waiting for the requestPresent callback to complete?
  98118. this._webVRrequesting = false;
  98119. // Are we presenting to the headset right now? (this is the vrDevice state)
  98120. this._webVRpresenting = false;
  98121. // Are we presenting in the fullscreen fallback?
  98122. this._fullscreenVRpresenting = false;
  98123. /**
  98124. * Observable raised when entering VR.
  98125. */
  98126. this.onEnteringVRObservable = new BABYLON.Observable();
  98127. /**
  98128. * Observable raised when exiting VR.
  98129. */
  98130. this.onExitingVRObservable = new BABYLON.Observable();
  98131. /**
  98132. * Observable raised when controller mesh is loaded.
  98133. */
  98134. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  98135. this._useCustomVRButton = false;
  98136. this._teleportationRequested = false;
  98137. this._teleportActive = false;
  98138. this._floorMeshesCollection = [];
  98139. this._rotationAllowed = true;
  98140. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  98141. this._isDefaultTeleportationTarget = true;
  98142. this._teleportationFillColor = "#444444";
  98143. this._teleportationBorderColor = "#FFFFFF";
  98144. this._rotationAngle = 0;
  98145. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  98146. this._padSensibilityUp = 0.65;
  98147. this._padSensibilityDown = 0.35;
  98148. this._leftController = null;
  98149. this._rightController = null;
  98150. /**
  98151. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  98152. */
  98153. this.onNewMeshSelected = new BABYLON.Observable();
  98154. /**
  98155. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  98156. */
  98157. this.onNewMeshPicked = new BABYLON.Observable();
  98158. /**
  98159. * Observable raised before camera teleportation
  98160. */
  98161. this.onBeforeCameraTeleport = new BABYLON.Observable();
  98162. /**
  98163. * Observable raised after camera teleportation
  98164. */
  98165. this.onAfterCameraTeleport = new BABYLON.Observable();
  98166. /**
  98167. * Observable raised when current selected mesh gets unselected
  98168. */
  98169. this.onSelectedMeshUnselected = new BABYLON.Observable();
  98170. /**
  98171. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  98172. */
  98173. this.teleportationEnabled = true;
  98174. this._teleportationInitialized = false;
  98175. this._interactionsEnabled = false;
  98176. this._interactionsRequested = false;
  98177. this._displayGaze = true;
  98178. this._displayLaserPointer = true;
  98179. /**
  98180. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  98181. */
  98182. this.updateGazeTrackerScale = true;
  98183. this._onResize = function () {
  98184. _this.moveButtonToBottomRight();
  98185. if (_this._fullscreenVRpresenting && _this._webVRready) {
  98186. _this.exitVR();
  98187. }
  98188. };
  98189. this._onFullscreenChange = function () {
  98190. if (document.fullscreen !== undefined) {
  98191. _this._fullscreenVRpresenting = document.fullscreen;
  98192. }
  98193. else if (document.mozFullScreen !== undefined) {
  98194. _this._fullscreenVRpresenting = document.mozFullScreen;
  98195. }
  98196. else if (document.webkitIsFullScreen !== undefined) {
  98197. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  98198. }
  98199. else if (document.msIsFullScreen !== undefined) {
  98200. _this._fullscreenVRpresenting = document.msIsFullScreen;
  98201. }
  98202. else if (document.msFullscreenElement !== undefined) {
  98203. _this._fullscreenVRpresenting = document.msFullscreenElement;
  98204. }
  98205. if (!_this._fullscreenVRpresenting && _this._canvas) {
  98206. _this.exitVR();
  98207. if (!_this._useCustomVRButton) {
  98208. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  98209. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  98210. }
  98211. }
  98212. };
  98213. this.beforeRender = function () {
  98214. if (_this._leftController && _this._leftController._activePointer) {
  98215. _this._castRayAndSelectObject(_this._leftController);
  98216. }
  98217. if (_this._rightController && _this._rightController._activePointer) {
  98218. _this._castRayAndSelectObject(_this._rightController);
  98219. }
  98220. if (_this._noControllerIsActive) {
  98221. _this._castRayAndSelectObject(_this._cameraGazer);
  98222. }
  98223. else {
  98224. _this._cameraGazer._gazeTracker.isVisible = false;
  98225. }
  98226. };
  98227. this._onNewGamepadConnected = function (gamepad) {
  98228. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  98229. if (gamepad.leftStick) {
  98230. gamepad.onleftstickchanged(function (stickValues) {
  98231. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  98232. // Listening to classic/xbox gamepad only if no VR controller is active
  98233. if ((!_this._leftController && !_this._rightController) ||
  98234. ((_this._leftController && !_this._leftController._activePointer) &&
  98235. (_this._rightController && !_this._rightController._activePointer))) {
  98236. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  98237. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  98238. }
  98239. }
  98240. });
  98241. }
  98242. if (gamepad.rightStick) {
  98243. gamepad.onrightstickchanged(function (stickValues) {
  98244. if (_this._teleportationInitialized) {
  98245. _this._checkRotate(stickValues, _this._cameraGazer);
  98246. }
  98247. });
  98248. }
  98249. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  98250. gamepad.onbuttondown(function (buttonPressed) {
  98251. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  98252. _this._cameraGazer._selectionPointerDown();
  98253. }
  98254. });
  98255. gamepad.onbuttonup(function (buttonPressed) {
  98256. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  98257. _this._cameraGazer._selectionPointerUp();
  98258. }
  98259. });
  98260. }
  98261. }
  98262. else {
  98263. var webVRController = gamepad;
  98264. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  98265. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  98266. _this._rightController = controller;
  98267. }
  98268. else {
  98269. _this._leftController = controller;
  98270. }
  98271. _this._tryEnableInteractionOnController(controller);
  98272. }
  98273. };
  98274. // 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
  98275. this._tryEnableInteractionOnController = function (controller) {
  98276. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  98277. _this._enableInteractionOnController(controller);
  98278. }
  98279. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  98280. _this._enableTeleportationOnController(controller);
  98281. }
  98282. };
  98283. this._onNewGamepadDisconnected = function (gamepad) {
  98284. if (gamepad instanceof BABYLON.WebVRController) {
  98285. if (gamepad.hand === "left" && _this._leftController != null) {
  98286. _this._leftController.dispose();
  98287. _this._leftController = null;
  98288. }
  98289. if (gamepad.hand === "right" && _this._rightController != null) {
  98290. _this._rightController.dispose();
  98291. _this._rightController = null;
  98292. }
  98293. }
  98294. };
  98295. this._workingVector = BABYLON.Vector3.Zero();
  98296. this._workingQuaternion = BABYLON.Quaternion.Identity();
  98297. this._workingMatrix = BABYLON.Matrix.Identity();
  98298. this._scene = scene;
  98299. this._canvas = scene.getEngine().getRenderingCanvas();
  98300. // Parse options
  98301. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  98302. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  98303. }
  98304. if (webVROptions.createDeviceOrientationCamera === undefined) {
  98305. webVROptions.createDeviceOrientationCamera = true;
  98306. }
  98307. if (webVROptions.laserToggle === undefined) {
  98308. webVROptions.laserToggle = true;
  98309. }
  98310. if (webVROptions.defaultHeight === undefined) {
  98311. webVROptions.defaultHeight = 1.7;
  98312. }
  98313. if (webVROptions.useCustomVRButton) {
  98314. this._useCustomVRButton = true;
  98315. if (webVROptions.customVRButton) {
  98316. this._btnVR = webVROptions.customVRButton;
  98317. }
  98318. }
  98319. if (webVROptions.rayLength) {
  98320. this._rayLength = webVROptions.rayLength;
  98321. }
  98322. this._defaultHeight = webVROptions.defaultHeight;
  98323. if (webVROptions.positionScale) {
  98324. this._rayLength *= webVROptions.positionScale;
  98325. this._defaultHeight *= webVROptions.positionScale;
  98326. }
  98327. this._hasEnteredVR = false;
  98328. // Set position
  98329. if (this._scene.activeCamera) {
  98330. this._position = this._scene.activeCamera.position.clone();
  98331. }
  98332. else {
  98333. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  98334. }
  98335. // Set non-vr camera
  98336. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  98337. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  98338. // Copy data from existing camera
  98339. if (this._scene.activeCamera) {
  98340. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  98341. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  98342. // Set rotation from previous camera
  98343. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  98344. var targetCamera = this._scene.activeCamera;
  98345. if (targetCamera.rotationQuaternion) {
  98346. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  98347. }
  98348. else {
  98349. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  98350. }
  98351. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  98352. }
  98353. }
  98354. this._scene.activeCamera = this._deviceOrientationCamera;
  98355. if (this._canvas) {
  98356. this._scene.activeCamera.attachControl(this._canvas);
  98357. }
  98358. }
  98359. else {
  98360. this._existingCamera = this._scene.activeCamera;
  98361. }
  98362. // Create VR cameras
  98363. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  98364. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  98365. }
  98366. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  98367. this._webVRCamera.useStandingMatrix();
  98368. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  98369. // Create default button
  98370. if (!this._useCustomVRButton) {
  98371. this._btnVR = document.createElement("BUTTON");
  98372. this._btnVR.className = "babylonVRicon";
  98373. this._btnVR.id = "babylonVRiconbtn";
  98374. this._btnVR.title = "Click to switch to VR";
  98375. 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) }";
  98376. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  98377. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  98378. // css += ".babylonVRicon.vrdisplaysupported { }";
  98379. // css += ".babylonVRicon.vrdisplayready { }";
  98380. // css += ".babylonVRicon.vrdisplayrequesting { }";
  98381. var style = document.createElement('style');
  98382. style.appendChild(document.createTextNode(css));
  98383. document.getElementsByTagName('head')[0].appendChild(style);
  98384. this.moveButtonToBottomRight();
  98385. }
  98386. // VR button click event
  98387. if (this._btnVR) {
  98388. this._btnVR.addEventListener("click", function () {
  98389. if (!_this.isInVRMode) {
  98390. _this.enterVR();
  98391. }
  98392. else {
  98393. _this.exitVR();
  98394. }
  98395. });
  98396. }
  98397. // Window events
  98398. window.addEventListener("resize", this._onResize);
  98399. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  98400. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  98401. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  98402. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  98403. document.onmsfullscreenchange = this._onFullscreenChange;
  98404. // Display vr button when headset is connected
  98405. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  98406. this.displayVRButton();
  98407. }
  98408. else {
  98409. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  98410. if (e.vrDisplay) {
  98411. _this.displayVRButton();
  98412. }
  98413. });
  98414. }
  98415. // Exiting VR mode using 'ESC' key on desktop
  98416. this._onKeyDown = function (event) {
  98417. if (event.keyCode === 27 && _this.isInVRMode) {
  98418. _this.exitVR();
  98419. }
  98420. };
  98421. document.addEventListener("keydown", this._onKeyDown);
  98422. // Exiting VR mode double tapping the touch screen
  98423. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  98424. if (_this.isInVRMode) {
  98425. _this.exitVR();
  98426. if (_this._fullscreenVRpresenting) {
  98427. _this._scene.getEngine().switchFullscreen(true);
  98428. }
  98429. }
  98430. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  98431. // Listen for WebVR display changes
  98432. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  98433. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  98434. this._onVRRequestPresentStart = function () {
  98435. _this._webVRrequesting = true;
  98436. _this.updateButtonVisibility();
  98437. };
  98438. this._onVRRequestPresentComplete = function (success) {
  98439. _this._webVRrequesting = false;
  98440. _this.updateButtonVisibility();
  98441. };
  98442. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  98443. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  98444. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  98445. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98446. scene.onDisposeObservable.add(function () {
  98447. _this.dispose();
  98448. });
  98449. // Gamepad connection events
  98450. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  98451. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  98452. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  98453. this.updateButtonVisibility();
  98454. //create easing functions
  98455. this._circleEase = new BABYLON.CircleEase();
  98456. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  98457. if (this.webVROptions.floorMeshes) {
  98458. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  98459. }
  98460. }
  98461. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  98462. /** Return this.onEnteringVRObservable
  98463. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  98464. */
  98465. get: function () {
  98466. return this.onEnteringVRObservable;
  98467. },
  98468. enumerable: true,
  98469. configurable: true
  98470. });
  98471. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  98472. /** Return this.onExitingVRObservable
  98473. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  98474. */
  98475. get: function () {
  98476. return this.onExitingVRObservable;
  98477. },
  98478. enumerable: true,
  98479. configurable: true
  98480. });
  98481. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  98482. /** Return this.onControllerMeshLoadedObservable
  98483. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  98484. */
  98485. get: function () {
  98486. return this.onControllerMeshLoadedObservable;
  98487. },
  98488. enumerable: true,
  98489. configurable: true
  98490. });
  98491. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  98492. /**
  98493. * The mesh used to display where the user is going to teleport.
  98494. */
  98495. get: function () {
  98496. return this._teleportationTarget;
  98497. },
  98498. /**
  98499. * Sets the mesh to be used to display where the user is going to teleport.
  98500. */
  98501. set: function (value) {
  98502. if (value) {
  98503. value.name = "teleportationTarget";
  98504. this._isDefaultTeleportationTarget = false;
  98505. this._teleportationTarget = value;
  98506. }
  98507. },
  98508. enumerable: true,
  98509. configurable: true
  98510. });
  98511. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  98512. /**
  98513. * 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
  98514. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  98515. * See http://doc.babylonjs.com/resources/baking_transformations
  98516. */
  98517. get: function () {
  98518. return this._cameraGazer._gazeTracker;
  98519. },
  98520. set: function (value) {
  98521. if (value) {
  98522. // Dispose of existing meshes
  98523. if (this._cameraGazer._gazeTracker) {
  98524. this._cameraGazer._gazeTracker.dispose();
  98525. }
  98526. if (this._leftController && this._leftController._gazeTracker) {
  98527. this._leftController._gazeTracker.dispose();
  98528. }
  98529. if (this._rightController && this._rightController._gazeTracker) {
  98530. this._rightController._gazeTracker.dispose();
  98531. }
  98532. // Set and create gaze trackers on head and controllers
  98533. this._cameraGazer._gazeTracker = value;
  98534. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  98535. this._cameraGazer._gazeTracker.isPickable = false;
  98536. this._cameraGazer._gazeTracker.isVisible = false;
  98537. this._cameraGazer._gazeTracker.name = "gazeTracker";
  98538. if (this._leftController) {
  98539. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  98540. }
  98541. if (this._rightController) {
  98542. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  98543. }
  98544. }
  98545. },
  98546. enumerable: true,
  98547. configurable: true
  98548. });
  98549. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  98550. /**
  98551. * The gaze tracking mesh corresponding to the left controller
  98552. */
  98553. get: function () {
  98554. if (this._leftController) {
  98555. return this._leftController._gazeTracker;
  98556. }
  98557. return null;
  98558. },
  98559. enumerable: true,
  98560. configurable: true
  98561. });
  98562. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  98563. /**
  98564. * The gaze tracking mesh corresponding to the right controller
  98565. */
  98566. get: function () {
  98567. if (this._rightController) {
  98568. return this._rightController._gazeTracker;
  98569. }
  98570. return null;
  98571. },
  98572. enumerable: true,
  98573. configurable: true
  98574. });
  98575. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  98576. /**
  98577. * If the ray of the gaze should be displayed.
  98578. */
  98579. get: function () {
  98580. return this._displayGaze;
  98581. },
  98582. /**
  98583. * Sets if the ray of the gaze should be displayed.
  98584. */
  98585. set: function (value) {
  98586. this._displayGaze = value;
  98587. if (!value) {
  98588. this._cameraGazer._gazeTracker.isVisible = false;
  98589. if (this._leftController) {
  98590. this._leftController._gazeTracker.isVisible = false;
  98591. }
  98592. if (this._rightController) {
  98593. this._rightController._gazeTracker.isVisible = false;
  98594. }
  98595. }
  98596. },
  98597. enumerable: true,
  98598. configurable: true
  98599. });
  98600. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  98601. /**
  98602. * If the ray of the LaserPointer should be displayed.
  98603. */
  98604. get: function () {
  98605. return this._displayLaserPointer;
  98606. },
  98607. /**
  98608. * Sets if the ray of the LaserPointer should be displayed.
  98609. */
  98610. set: function (value) {
  98611. this._displayLaserPointer = value;
  98612. if (!value) {
  98613. if (this._rightController) {
  98614. this._rightController._deactivatePointer();
  98615. this._rightController._gazeTracker.isVisible = false;
  98616. }
  98617. if (this._leftController) {
  98618. this._leftController._deactivatePointer();
  98619. this._leftController._gazeTracker.isVisible = false;
  98620. }
  98621. }
  98622. else {
  98623. if (this._rightController) {
  98624. this._rightController._activatePointer();
  98625. }
  98626. if (this._leftController) {
  98627. this._leftController._activatePointer();
  98628. }
  98629. }
  98630. },
  98631. enumerable: true,
  98632. configurable: true
  98633. });
  98634. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  98635. /**
  98636. * The deviceOrientationCamera used as the camera when not in VR.
  98637. */
  98638. get: function () {
  98639. return this._deviceOrientationCamera;
  98640. },
  98641. enumerable: true,
  98642. configurable: true
  98643. });
  98644. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  98645. /**
  98646. * Based on the current WebVR support, returns the current VR camera used.
  98647. */
  98648. get: function () {
  98649. if (this._webVRready) {
  98650. return this._webVRCamera;
  98651. }
  98652. else {
  98653. return this._scene.activeCamera;
  98654. }
  98655. },
  98656. enumerable: true,
  98657. configurable: true
  98658. });
  98659. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  98660. /**
  98661. * The webVRCamera which is used when in VR.
  98662. */
  98663. get: function () {
  98664. return this._webVRCamera;
  98665. },
  98666. enumerable: true,
  98667. configurable: true
  98668. });
  98669. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  98670. /**
  98671. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  98672. */
  98673. get: function () {
  98674. return this._vrDeviceOrientationCamera;
  98675. },
  98676. enumerable: true,
  98677. configurable: true
  98678. });
  98679. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  98680. get: function () {
  98681. var result = this._cameraGazer._teleportationRequestInitiated
  98682. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  98683. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  98684. return result;
  98685. },
  98686. enumerable: true,
  98687. configurable: true
  98688. });
  98689. // Raised when one of the controller has loaded successfully its associated default mesh
  98690. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  98691. if (this._leftController && this._leftController.webVRController == webVRController) {
  98692. if (webVRController.mesh) {
  98693. this._leftController._setLaserPointerParent(webVRController.mesh);
  98694. }
  98695. }
  98696. if (this._rightController && this._rightController.webVRController == webVRController) {
  98697. if (webVRController.mesh) {
  98698. this._rightController._setLaserPointerParent(webVRController.mesh);
  98699. }
  98700. }
  98701. try {
  98702. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  98703. }
  98704. catch (err) {
  98705. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  98706. }
  98707. };
  98708. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  98709. /**
  98710. * Gets a value indicating if we are currently in VR mode.
  98711. */
  98712. get: function () {
  98713. return this._webVRpresenting || this._fullscreenVRpresenting;
  98714. },
  98715. enumerable: true,
  98716. configurable: true
  98717. });
  98718. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  98719. var vrDisplay = this._scene.getEngine().getVRDevice();
  98720. if (vrDisplay) {
  98721. var wasPresenting = this._webVRpresenting;
  98722. this._webVRpresenting = vrDisplay.isPresenting;
  98723. if (wasPresenting && !this._webVRpresenting)
  98724. this.exitVR();
  98725. }
  98726. else {
  98727. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  98728. }
  98729. this.updateButtonVisibility();
  98730. };
  98731. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  98732. this._webVRsupported = eventArgs.vrSupported;
  98733. this._webVRready = !!eventArgs.vrDisplay;
  98734. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  98735. this.updateButtonVisibility();
  98736. };
  98737. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  98738. if (this._canvas && !this._useCustomVRButton) {
  98739. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  98740. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  98741. }
  98742. };
  98743. VRExperienceHelper.prototype.displayVRButton = function () {
  98744. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  98745. document.body.appendChild(this._btnVR);
  98746. this._btnVRDisplayed = true;
  98747. }
  98748. };
  98749. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  98750. if (!this._btnVR || this._useCustomVRButton) {
  98751. return;
  98752. }
  98753. this._btnVR.className = "babylonVRicon";
  98754. if (this.isInVRMode) {
  98755. this._btnVR.className += " vrdisplaypresenting";
  98756. }
  98757. else {
  98758. if (this._webVRready)
  98759. this._btnVR.className += " vrdisplayready";
  98760. if (this._webVRsupported)
  98761. this._btnVR.className += " vrdisplaysupported";
  98762. if (this._webVRrequesting)
  98763. this._btnVR.className += " vrdisplayrequesting";
  98764. }
  98765. };
  98766. /**
  98767. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  98768. * Otherwise, will use the fullscreen API.
  98769. */
  98770. VRExperienceHelper.prototype.enterVR = function () {
  98771. if (this.onEnteringVRObservable) {
  98772. try {
  98773. this.onEnteringVRObservable.notifyObservers(this);
  98774. }
  98775. catch (err) {
  98776. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  98777. }
  98778. }
  98779. if (this._scene.activeCamera) {
  98780. this._position = this._scene.activeCamera.position.clone();
  98781. // make sure that we return to the last active camera
  98782. this._existingCamera = this._scene.activeCamera;
  98783. }
  98784. if (this._webVRrequesting)
  98785. return;
  98786. // If WebVR is supported and a headset is connected
  98787. if (this._webVRready) {
  98788. if (!this._webVRpresenting) {
  98789. this._webVRCamera.position = this._position;
  98790. this._scene.activeCamera = this._webVRCamera;
  98791. }
  98792. }
  98793. else if (this._vrDeviceOrientationCamera) {
  98794. this._vrDeviceOrientationCamera.position = this._position;
  98795. if (this._scene.activeCamera) {
  98796. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  98797. }
  98798. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  98799. this._scene.getEngine().switchFullscreen(true);
  98800. this.updateButtonVisibility();
  98801. }
  98802. if (this._scene.activeCamera && this._canvas) {
  98803. this._scene.activeCamera.attachControl(this._canvas);
  98804. }
  98805. if (this._interactionsEnabled) {
  98806. this._scene.registerBeforeRender(this.beforeRender);
  98807. }
  98808. this._hasEnteredVR = true;
  98809. };
  98810. /**
  98811. * Attempt to exit VR, or fullscreen.
  98812. */
  98813. VRExperienceHelper.prototype.exitVR = function () {
  98814. if (this._hasEnteredVR) {
  98815. if (this.onExitingVRObservable) {
  98816. try {
  98817. this.onExitingVRObservable.notifyObservers(this);
  98818. }
  98819. catch (err) {
  98820. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  98821. }
  98822. }
  98823. if (this._webVRpresenting) {
  98824. this._scene.getEngine().disableVR();
  98825. }
  98826. if (this._scene.activeCamera) {
  98827. this._position = this._scene.activeCamera.position.clone();
  98828. }
  98829. if (this._deviceOrientationCamera) {
  98830. this._deviceOrientationCamera.position = this._position;
  98831. this._scene.activeCamera = this._deviceOrientationCamera;
  98832. if (this._canvas) {
  98833. this._scene.activeCamera.attachControl(this._canvas);
  98834. }
  98835. }
  98836. else if (this._existingCamera) {
  98837. this._existingCamera.position = this._position;
  98838. this._scene.activeCamera = this._existingCamera;
  98839. }
  98840. this.updateButtonVisibility();
  98841. if (this._interactionsEnabled) {
  98842. this._scene.unregisterBeforeRender(this.beforeRender);
  98843. this._cameraGazer._gazeTracker.isVisible = false;
  98844. if (this._leftController) {
  98845. this._leftController._gazeTracker.isVisible = false;
  98846. }
  98847. if (this._rightController) {
  98848. this._rightController._gazeTracker.isVisible = false;
  98849. }
  98850. }
  98851. // resize to update width and height when exiting vr exits fullscreen
  98852. this._scene.getEngine().resize();
  98853. this._hasEnteredVR = false;
  98854. }
  98855. };
  98856. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  98857. /**
  98858. * The position of the vr experience helper.
  98859. */
  98860. get: function () {
  98861. return this._position;
  98862. },
  98863. /**
  98864. * Sets the position of the vr experience helper.
  98865. */
  98866. set: function (value) {
  98867. this._position = value;
  98868. if (this._scene.activeCamera) {
  98869. this._scene.activeCamera.position = value;
  98870. }
  98871. },
  98872. enumerable: true,
  98873. configurable: true
  98874. });
  98875. /**
  98876. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  98877. */
  98878. VRExperienceHelper.prototype.enableInteractions = function () {
  98879. var _this = this;
  98880. if (!this._interactionsEnabled) {
  98881. this._interactionsRequested = true;
  98882. if (this._leftController) {
  98883. this._enableInteractionOnController(this._leftController);
  98884. }
  98885. if (this._rightController) {
  98886. this._enableInteractionOnController(this._rightController);
  98887. }
  98888. this.raySelectionPredicate = function (mesh) {
  98889. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  98890. };
  98891. this.meshSelectionPredicate = function (mesh) {
  98892. return true;
  98893. };
  98894. this._raySelectionPredicate = function (mesh) {
  98895. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  98896. && mesh.name.indexOf("teleportationTarget") === -1
  98897. && mesh.name.indexOf("torusTeleportation") === -1)) {
  98898. return _this.raySelectionPredicate(mesh);
  98899. }
  98900. return false;
  98901. };
  98902. this._interactionsEnabled = true;
  98903. }
  98904. };
  98905. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  98906. get: function () {
  98907. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  98908. },
  98909. enumerable: true,
  98910. configurable: true
  98911. });
  98912. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  98913. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  98914. if (this._floorMeshesCollection[i].id === mesh.id) {
  98915. return true;
  98916. }
  98917. }
  98918. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  98919. return true;
  98920. }
  98921. return false;
  98922. };
  98923. /**
  98924. * Adds a floor mesh to be used for teleportation.
  98925. * @param floorMesh the mesh to be used for teleportation.
  98926. */
  98927. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  98928. if (!this._floorMeshesCollection) {
  98929. return;
  98930. }
  98931. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  98932. return;
  98933. }
  98934. this._floorMeshesCollection.push(floorMesh);
  98935. };
  98936. /**
  98937. * Removes a floor mesh from being used for teleportation.
  98938. * @param floorMesh the mesh to be removed.
  98939. */
  98940. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  98941. if (!this._floorMeshesCollection) {
  98942. return;
  98943. }
  98944. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  98945. if (meshIndex !== -1) {
  98946. this._floorMeshesCollection.splice(meshIndex, 1);
  98947. }
  98948. };
  98949. /**
  98950. * Enables interactions and teleportation using the VR controllers and gaze.
  98951. * @param vrTeleportationOptions options to modify teleportation behavior.
  98952. */
  98953. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  98954. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  98955. if (!this._teleportationInitialized) {
  98956. this._teleportationRequested = true;
  98957. this.enableInteractions();
  98958. if (vrTeleportationOptions.floorMeshName) {
  98959. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  98960. }
  98961. if (vrTeleportationOptions.floorMeshes) {
  98962. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  98963. }
  98964. if (this._leftController != null) {
  98965. this._enableTeleportationOnController(this._leftController);
  98966. }
  98967. if (this._rightController != null) {
  98968. this._enableTeleportationOnController(this._rightController);
  98969. }
  98970. // Creates an image processing post process for the vignette not relying
  98971. // on the main scene configuration for image processing to reduce setup and spaces
  98972. // (gamma/linear) conflicts.
  98973. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  98974. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  98975. imageProcessingConfiguration.vignetteEnabled = true;
  98976. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  98977. this._webVRCamera.detachPostProcess(this._postProcessMove);
  98978. this._teleportationInitialized = true;
  98979. if (this._isDefaultTeleportationTarget) {
  98980. this._createTeleportationCircles();
  98981. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  98982. }
  98983. }
  98984. };
  98985. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  98986. var _this = this;
  98987. var controllerMesh = controller.webVRController.mesh;
  98988. if (controllerMesh) {
  98989. controller._interactionsEnabled = true;
  98990. controller._activatePointer();
  98991. if (this.webVROptions.laserToggle) {
  98992. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  98993. // Enabling / disabling laserPointer
  98994. if (_this._displayLaserPointer && stateObject.value === 1) {
  98995. if (controller._activePointer) {
  98996. controller._deactivatePointer();
  98997. }
  98998. else {
  98999. controller._activatePointer();
  99000. }
  99001. if (_this.displayGaze) {
  99002. controller._gazeTracker.isVisible = controller._activePointer;
  99003. }
  99004. }
  99005. });
  99006. }
  99007. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  99008. var gazer = controller;
  99009. if (_this._noControllerIsActive) {
  99010. gazer = _this._cameraGazer;
  99011. }
  99012. if (!gazer._pointerDownOnMeshAsked) {
  99013. if (stateObject.value > _this._padSensibilityUp) {
  99014. gazer._selectionPointerDown();
  99015. }
  99016. }
  99017. else if (stateObject.value < _this._padSensibilityDown) {
  99018. gazer._selectionPointerUp();
  99019. }
  99020. });
  99021. }
  99022. };
  99023. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  99024. // Dont teleport if another gaze already requested teleportation
  99025. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  99026. return;
  99027. }
  99028. if (!gazer._teleportationRequestInitiated) {
  99029. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  99030. gazer._activatePointer();
  99031. gazer._teleportationRequestInitiated = true;
  99032. }
  99033. }
  99034. else {
  99035. // Listening to the proper controller values changes to confirm teleportation
  99036. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  99037. if (this._teleportActive) {
  99038. this.teleportCamera(this._haloCenter);
  99039. }
  99040. gazer._teleportationRequestInitiated = false;
  99041. }
  99042. }
  99043. };
  99044. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  99045. // Only rotate when user is not currently selecting a teleportation location
  99046. if (gazer._teleportationRequestInitiated) {
  99047. return;
  99048. }
  99049. if (!gazer._rotationLeftAsked) {
  99050. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  99051. gazer._rotationLeftAsked = true;
  99052. if (this._rotationAllowed) {
  99053. this._rotateCamera(false);
  99054. }
  99055. }
  99056. }
  99057. else {
  99058. if (stateObject.x > -this._padSensibilityDown) {
  99059. gazer._rotationLeftAsked = false;
  99060. }
  99061. }
  99062. if (!gazer._rotationRightAsked) {
  99063. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  99064. gazer._rotationRightAsked = true;
  99065. if (this._rotationAllowed) {
  99066. this._rotateCamera(true);
  99067. }
  99068. }
  99069. }
  99070. else {
  99071. if (stateObject.x < this._padSensibilityDown) {
  99072. gazer._rotationRightAsked = false;
  99073. }
  99074. }
  99075. };
  99076. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  99077. // Only teleport backwards when user is not currently selecting a teleportation location
  99078. if (gazer._teleportationRequestInitiated) {
  99079. return;
  99080. }
  99081. // Teleport backwards
  99082. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  99083. if (!gazer._teleportationBackRequestInitiated) {
  99084. if (!this.currentVRCamera) {
  99085. return;
  99086. }
  99087. // Get rotation and position of the current camera
  99088. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  99089. var position = this.currentVRCamera.position;
  99090. // If the camera has device position, use that instead
  99091. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  99092. rotation = this.currentVRCamera.deviceRotationQuaternion;
  99093. position = this.currentVRCamera.devicePosition;
  99094. }
  99095. // Get matrix with only the y rotation of the device rotation
  99096. rotation.toEulerAnglesToRef(this._workingVector);
  99097. this._workingVector.z = 0;
  99098. this._workingVector.x = 0;
  99099. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  99100. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  99101. // Rotate backwards ray by device rotation to cast at the ground behind the user
  99102. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  99103. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  99104. var ray = new BABYLON.Ray(position, this._workingVector);
  99105. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  99106. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  99107. this.teleportCamera(hit.pickedPoint);
  99108. }
  99109. gazer._teleportationBackRequestInitiated = true;
  99110. }
  99111. }
  99112. else {
  99113. gazer._teleportationBackRequestInitiated = false;
  99114. }
  99115. };
  99116. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  99117. var _this = this;
  99118. var controllerMesh = controller.webVRController.mesh;
  99119. if (controllerMesh) {
  99120. if (!controller._interactionsEnabled) {
  99121. this._enableInteractionOnController(controller);
  99122. }
  99123. controller._interactionsEnabled = true;
  99124. controller._teleportationEnabled = true;
  99125. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  99126. controller._dpadPressed = false;
  99127. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  99128. controller._dpadPressed = stateObject.pressed;
  99129. if (!controller._dpadPressed) {
  99130. controller._rotationLeftAsked = false;
  99131. controller._rotationRightAsked = false;
  99132. controller._teleportationBackRequestInitiated = false;
  99133. }
  99134. });
  99135. }
  99136. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  99137. if (_this.teleportationEnabled) {
  99138. _this._checkTeleportBackwards(stateObject, controller);
  99139. _this._checkTeleportWithRay(stateObject, controller);
  99140. }
  99141. _this._checkRotate(stateObject, controller);
  99142. });
  99143. }
  99144. };
  99145. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  99146. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  99147. this._teleportationTarget.isPickable = false;
  99148. var length = 512;
  99149. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  99150. dynamicTexture.hasAlpha = true;
  99151. var context = dynamicTexture.getContext();
  99152. var centerX = length / 2;
  99153. var centerY = length / 2;
  99154. var radius = 200;
  99155. context.beginPath();
  99156. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  99157. context.fillStyle = this._teleportationFillColor;
  99158. context.fill();
  99159. context.lineWidth = 10;
  99160. context.strokeStyle = this._teleportationBorderColor;
  99161. context.stroke();
  99162. context.closePath();
  99163. dynamicTexture.update();
  99164. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  99165. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  99166. this._teleportationTarget.material = teleportationCircleMaterial;
  99167. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  99168. torus.isPickable = false;
  99169. torus.parent = this._teleportationTarget;
  99170. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  99171. var keys = [];
  99172. keys.push({
  99173. frame: 0,
  99174. value: 0
  99175. });
  99176. keys.push({
  99177. frame: 30,
  99178. value: 0.4
  99179. });
  99180. keys.push({
  99181. frame: 60,
  99182. value: 0
  99183. });
  99184. animationInnerCircle.setKeys(keys);
  99185. var easingFunction = new BABYLON.SineEase();
  99186. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  99187. animationInnerCircle.setEasingFunction(easingFunction);
  99188. torus.animations = [];
  99189. torus.animations.push(animationInnerCircle);
  99190. this._scene.beginAnimation(torus, 0, 60, true);
  99191. this._hideTeleportationTarget();
  99192. };
  99193. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  99194. this._teleportActive = true;
  99195. if (this._teleportationInitialized) {
  99196. this._teleportationTarget.isVisible = true;
  99197. if (this._isDefaultTeleportationTarget) {
  99198. this._teleportationTarget.getChildren()[0].isVisible = true;
  99199. }
  99200. }
  99201. };
  99202. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  99203. this._teleportActive = false;
  99204. if (this._teleportationInitialized) {
  99205. this._teleportationTarget.isVisible = false;
  99206. if (this._isDefaultTeleportationTarget) {
  99207. this._teleportationTarget.getChildren()[0].isVisible = false;
  99208. }
  99209. }
  99210. };
  99211. VRExperienceHelper.prototype._rotateCamera = function (right) {
  99212. var _this = this;
  99213. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  99214. return;
  99215. }
  99216. if (right) {
  99217. this._rotationAngle++;
  99218. }
  99219. else {
  99220. this._rotationAngle--;
  99221. }
  99222. this.currentVRCamera.animations = [];
  99223. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  99224. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99225. var animationRotationKeys = [];
  99226. animationRotationKeys.push({
  99227. frame: 0,
  99228. value: this.currentVRCamera.rotationQuaternion
  99229. });
  99230. animationRotationKeys.push({
  99231. frame: 6,
  99232. value: target
  99233. });
  99234. animationRotation.setKeys(animationRotationKeys);
  99235. animationRotation.setEasingFunction(this._circleEase);
  99236. this.currentVRCamera.animations.push(animationRotation);
  99237. this._postProcessMove.animations = [];
  99238. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99239. var vignetteWeightKeys = [];
  99240. vignetteWeightKeys.push({
  99241. frame: 0,
  99242. value: 0
  99243. });
  99244. vignetteWeightKeys.push({
  99245. frame: 3,
  99246. value: 4
  99247. });
  99248. vignetteWeightKeys.push({
  99249. frame: 6,
  99250. value: 0
  99251. });
  99252. animationPP.setKeys(vignetteWeightKeys);
  99253. animationPP.setEasingFunction(this._circleEase);
  99254. this._postProcessMove.animations.push(animationPP);
  99255. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99256. var vignetteStretchKeys = [];
  99257. vignetteStretchKeys.push({
  99258. frame: 0,
  99259. value: 0
  99260. });
  99261. vignetteStretchKeys.push({
  99262. frame: 3,
  99263. value: 10
  99264. });
  99265. vignetteStretchKeys.push({
  99266. frame: 6,
  99267. value: 0
  99268. });
  99269. animationPP2.setKeys(vignetteStretchKeys);
  99270. animationPP2.setEasingFunction(this._circleEase);
  99271. this._postProcessMove.animations.push(animationPP2);
  99272. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  99273. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  99274. this._postProcessMove.samples = 4;
  99275. this._webVRCamera.attachPostProcess(this._postProcessMove);
  99276. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  99277. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  99278. });
  99279. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  99280. };
  99281. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  99282. if (hit.pickedPoint) {
  99283. if (gazer._teleportationRequestInitiated) {
  99284. this._displayTeleportationTarget();
  99285. this._haloCenter.copyFrom(hit.pickedPoint);
  99286. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  99287. }
  99288. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  99289. if (pickNormal) {
  99290. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  99291. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  99292. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  99293. }
  99294. this._teleportationTarget.position.y += 0.1;
  99295. }
  99296. };
  99297. /**
  99298. * Teleports the users feet to the desired location
  99299. * @param location The location where the user's feet should be placed
  99300. */
  99301. VRExperienceHelper.prototype.teleportCamera = function (location) {
  99302. var _this = this;
  99303. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  99304. return;
  99305. }
  99306. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  99307. // offset of the headset from the anchor.
  99308. if (this.webVRCamera.leftCamera) {
  99309. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  99310. this._workingVector.subtractInPlace(this.webVRCamera.position);
  99311. location.subtractToRef(this._workingVector, this._workingVector);
  99312. }
  99313. else {
  99314. this._workingVector.copyFrom(location);
  99315. }
  99316. // Add height to account for user's height offset
  99317. if (this.isInVRMode) {
  99318. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  99319. }
  99320. else {
  99321. this._workingVector.y += this._defaultHeight;
  99322. }
  99323. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  99324. // Create animation from the camera's position to the new location
  99325. this.currentVRCamera.animations = [];
  99326. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99327. var animationCameraTeleportationKeys = [{
  99328. frame: 0,
  99329. value: this.currentVRCamera.position
  99330. },
  99331. {
  99332. frame: 11,
  99333. value: this._workingVector
  99334. }
  99335. ];
  99336. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  99337. animationCameraTeleportation.setEasingFunction(this._circleEase);
  99338. this.currentVRCamera.animations.push(animationCameraTeleportation);
  99339. this._postProcessMove.animations = [];
  99340. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99341. var vignetteWeightKeys = [];
  99342. vignetteWeightKeys.push({
  99343. frame: 0,
  99344. value: 0
  99345. });
  99346. vignetteWeightKeys.push({
  99347. frame: 5,
  99348. value: 8
  99349. });
  99350. vignetteWeightKeys.push({
  99351. frame: 11,
  99352. value: 0
  99353. });
  99354. animationPP.setKeys(vignetteWeightKeys);
  99355. this._postProcessMove.animations.push(animationPP);
  99356. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99357. var vignetteStretchKeys = [];
  99358. vignetteStretchKeys.push({
  99359. frame: 0,
  99360. value: 0
  99361. });
  99362. vignetteStretchKeys.push({
  99363. frame: 5,
  99364. value: 10
  99365. });
  99366. vignetteStretchKeys.push({
  99367. frame: 11,
  99368. value: 0
  99369. });
  99370. animationPP2.setKeys(vignetteStretchKeys);
  99371. this._postProcessMove.animations.push(animationPP2);
  99372. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  99373. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  99374. this._webVRCamera.attachPostProcess(this._postProcessMove);
  99375. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  99376. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  99377. });
  99378. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  99379. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  99380. });
  99381. this._hideTeleportationTarget();
  99382. };
  99383. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  99384. if (normal) {
  99385. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  99386. if (angle < Math.PI / 2) {
  99387. normal.scaleInPlace(-1);
  99388. }
  99389. }
  99390. return normal;
  99391. };
  99392. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  99393. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  99394. return;
  99395. }
  99396. var ray = gazer._getForwardRay(this._rayLength);
  99397. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  99398. if (hit) {
  99399. // Populate the contrllers mesh that can be used for drag/drop
  99400. if (gazer._laserPointer) {
  99401. hit.originMesh = gazer._laserPointer.parent;
  99402. }
  99403. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  99404. }
  99405. gazer._currentHit = hit;
  99406. // Moving the gazeTracker on the mesh face targetted
  99407. if (hit && hit.pickedPoint) {
  99408. if (this._displayGaze) {
  99409. var multiplier = 1;
  99410. gazer._gazeTracker.isVisible = true;
  99411. if (gazer._isActionableMesh) {
  99412. multiplier = 3;
  99413. }
  99414. if (this.updateGazeTrackerScale) {
  99415. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  99416. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  99417. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  99418. }
  99419. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  99420. // To avoid z-fighting
  99421. var deltaFighting = 0.002;
  99422. if (pickNormal) {
  99423. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  99424. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  99425. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  99426. }
  99427. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  99428. if (gazer._gazeTracker.position.x < 0) {
  99429. gazer._gazeTracker.position.x += deltaFighting;
  99430. }
  99431. else {
  99432. gazer._gazeTracker.position.x -= deltaFighting;
  99433. }
  99434. if (gazer._gazeTracker.position.y < 0) {
  99435. gazer._gazeTracker.position.y += deltaFighting;
  99436. }
  99437. else {
  99438. gazer._gazeTracker.position.y -= deltaFighting;
  99439. }
  99440. if (gazer._gazeTracker.position.z < 0) {
  99441. gazer._gazeTracker.position.z += deltaFighting;
  99442. }
  99443. else {
  99444. gazer._gazeTracker.position.z -= deltaFighting;
  99445. }
  99446. }
  99447. // Changing the size of the laser pointer based on the distance from the targetted point
  99448. gazer._updatePointerDistance(hit.distance);
  99449. }
  99450. else {
  99451. gazer._updatePointerDistance();
  99452. gazer._gazeTracker.isVisible = false;
  99453. }
  99454. if (hit && hit.pickedMesh) {
  99455. // The object selected is the floor, we're in a teleportation scenario
  99456. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  99457. // Moving the teleportation area to this targetted point
  99458. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  99459. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  99460. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99461. }
  99462. gazer._currentMeshSelected = null;
  99463. if (gazer._teleportationRequestInitiated) {
  99464. this._moveTeleportationSelectorTo(hit, gazer, ray);
  99465. }
  99466. return;
  99467. }
  99468. // If not, we're in a selection scenario
  99469. //this._teleportationAllowed = false;
  99470. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  99471. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  99472. this.onNewMeshPicked.notifyObservers(hit);
  99473. gazer._currentMeshSelected = hit.pickedMesh;
  99474. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  99475. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  99476. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  99477. gazer._isActionableMesh = true;
  99478. }
  99479. else {
  99480. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99481. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99482. gazer._isActionableMesh = false;
  99483. }
  99484. try {
  99485. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  99486. }
  99487. catch (err) {
  99488. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  99489. }
  99490. }
  99491. else {
  99492. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99493. gazer._currentMeshSelected = null;
  99494. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99495. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99496. }
  99497. }
  99498. }
  99499. else {
  99500. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99501. gazer._currentMeshSelected = null;
  99502. //this._teleportationAllowed = false;
  99503. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99504. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99505. }
  99506. };
  99507. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  99508. if (mesh) {
  99509. this.onSelectedMeshUnselected.notifyObservers(mesh);
  99510. }
  99511. };
  99512. /**
  99513. * Sets the color of the laser ray from the vr controllers.
  99514. * @param color new color for the ray.
  99515. */
  99516. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  99517. if (this._leftController) {
  99518. this._leftController._setLaserPointerColor(color);
  99519. }
  99520. if (this._rightController) {
  99521. this._rightController._setLaserPointerColor(color);
  99522. }
  99523. };
  99524. /**
  99525. * Sets the color of the ray from the vr headsets gaze.
  99526. * @param color new color for the ray.
  99527. */
  99528. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  99529. if (!this._cameraGazer._gazeTracker.material) {
  99530. return;
  99531. }
  99532. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  99533. if (this._leftController) {
  99534. this._leftController._gazeTracker.material.emissiveColor = color;
  99535. }
  99536. if (this._rightController) {
  99537. this._rightController._gazeTracker.material.emissiveColor = color;
  99538. }
  99539. };
  99540. /**
  99541. * Exits VR and disposes of the vr experience helper
  99542. */
  99543. VRExperienceHelper.prototype.dispose = function () {
  99544. if (this.isInVRMode) {
  99545. this.exitVR();
  99546. }
  99547. if (this._postProcessMove) {
  99548. this._postProcessMove.dispose();
  99549. }
  99550. if (this._webVRCamera) {
  99551. this._webVRCamera.dispose();
  99552. }
  99553. if (this._vrDeviceOrientationCamera) {
  99554. this._vrDeviceOrientationCamera.dispose();
  99555. }
  99556. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  99557. document.body.removeChild(this._btnVR);
  99558. }
  99559. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  99560. this._deviceOrientationCamera.dispose();
  99561. }
  99562. if (this._cameraGazer) {
  99563. this._cameraGazer.dispose();
  99564. }
  99565. if (this._leftController) {
  99566. this._leftController.dispose();
  99567. }
  99568. if (this._rightController) {
  99569. this._rightController.dispose();
  99570. }
  99571. if (this._teleportationTarget) {
  99572. this._teleportationTarget.dispose();
  99573. }
  99574. this._floorMeshesCollection = [];
  99575. document.removeEventListener("keydown", this._onKeyDown);
  99576. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  99577. window.removeEventListener("resize", this._onResize);
  99578. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  99579. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  99580. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  99581. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  99582. document.onmsfullscreenchange = null;
  99583. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  99584. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  99585. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  99586. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  99587. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  99588. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  99589. this._scene.unregisterBeforeRender(this.beforeRender);
  99590. };
  99591. /**
  99592. * Gets the name of the VRExperienceHelper class
  99593. * @returns "VRExperienceHelper"
  99594. */
  99595. VRExperienceHelper.prototype.getClassName = function () {
  99596. return "VRExperienceHelper";
  99597. };
  99598. return VRExperienceHelper;
  99599. }());
  99600. BABYLON.VRExperienceHelper = VRExperienceHelper;
  99601. })(BABYLON || (BABYLON = {}));
  99602. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  99603. // Mainly based on these 2 articles :
  99604. // 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
  99605. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  99606. var BABYLON;
  99607. (function (BABYLON) {
  99608. /**
  99609. * Defines the potential axis of a Joystick
  99610. */
  99611. var JoystickAxis;
  99612. (function (JoystickAxis) {
  99613. /** X axis */
  99614. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  99615. /** Y axis */
  99616. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  99617. /** Z axis */
  99618. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  99619. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  99620. /**
  99621. * Class used to define virtual joystick (used in touch mode)
  99622. */
  99623. var VirtualJoystick = /** @class */ (function () {
  99624. /**
  99625. * Creates a new virtual joystick
  99626. * @param leftJoystick defines that the joystick is for left hand (false by default)
  99627. */
  99628. function VirtualJoystick(leftJoystick) {
  99629. var _this = this;
  99630. if (leftJoystick) {
  99631. this._leftJoystick = true;
  99632. }
  99633. else {
  99634. this._leftJoystick = false;
  99635. }
  99636. VirtualJoystick._globalJoystickIndex++;
  99637. // By default left & right arrow keys are moving the X
  99638. // and up & down keys are moving the Y
  99639. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  99640. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  99641. this.reverseLeftRight = false;
  99642. this.reverseUpDown = false;
  99643. // collections of pointers
  99644. this._touches = new BABYLON.StringDictionary();
  99645. this.deltaPosition = BABYLON.Vector3.Zero();
  99646. this._joystickSensibility = 25;
  99647. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  99648. this._onResize = function (evt) {
  99649. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  99650. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  99651. if (VirtualJoystick.vjCanvas) {
  99652. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  99653. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  99654. }
  99655. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  99656. };
  99657. // injecting a canvas element on top of the canvas 3D game
  99658. if (!VirtualJoystick.vjCanvas) {
  99659. window.addEventListener("resize", this._onResize, false);
  99660. VirtualJoystick.vjCanvas = document.createElement("canvas");
  99661. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  99662. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  99663. VirtualJoystick.vjCanvas.width = window.innerWidth;
  99664. VirtualJoystick.vjCanvas.height = window.innerHeight;
  99665. VirtualJoystick.vjCanvas.style.width = "100%";
  99666. VirtualJoystick.vjCanvas.style.height = "100%";
  99667. VirtualJoystick.vjCanvas.style.position = "absolute";
  99668. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  99669. VirtualJoystick.vjCanvas.style.top = "0px";
  99670. VirtualJoystick.vjCanvas.style.left = "0px";
  99671. VirtualJoystick.vjCanvas.style.zIndex = "5";
  99672. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  99673. // Support for jQuery PEP polyfill
  99674. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  99675. var context = VirtualJoystick.vjCanvas.getContext('2d');
  99676. if (!context) {
  99677. throw new Error("Unable to create canvas for virtual joystick");
  99678. }
  99679. VirtualJoystick.vjCanvasContext = context;
  99680. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  99681. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  99682. document.body.appendChild(VirtualJoystick.vjCanvas);
  99683. }
  99684. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  99685. this.pressed = false;
  99686. // default joystick color
  99687. this._joystickColor = "cyan";
  99688. this._joystickPointerID = -1;
  99689. // current joystick position
  99690. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  99691. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  99692. // origin joystick position
  99693. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  99694. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  99695. this._onPointerDownHandlerRef = function (evt) {
  99696. _this._onPointerDown(evt);
  99697. };
  99698. this._onPointerMoveHandlerRef = function (evt) {
  99699. _this._onPointerMove(evt);
  99700. };
  99701. this._onPointerUpHandlerRef = function (evt) {
  99702. _this._onPointerUp(evt);
  99703. };
  99704. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  99705. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  99706. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  99707. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  99708. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  99709. evt.preventDefault(); // Disables system menu
  99710. }, false);
  99711. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  99712. }
  99713. /**
  99714. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  99715. * @param newJoystickSensibility defines the new sensibility
  99716. */
  99717. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  99718. this._joystickSensibility = newJoystickSensibility;
  99719. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  99720. };
  99721. VirtualJoystick.prototype._onPointerDown = function (e) {
  99722. var positionOnScreenCondition;
  99723. e.preventDefault();
  99724. if (this._leftJoystick === true) {
  99725. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  99726. }
  99727. else {
  99728. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  99729. }
  99730. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  99731. // First contact will be dedicated to the virtual joystick
  99732. this._joystickPointerID = e.pointerId;
  99733. this._joystickPointerStartPos.x = e.clientX;
  99734. this._joystickPointerStartPos.y = e.clientY;
  99735. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  99736. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  99737. this._deltaJoystickVector.x = 0;
  99738. this._deltaJoystickVector.y = 0;
  99739. this.pressed = true;
  99740. this._touches.add(e.pointerId.toString(), e);
  99741. }
  99742. else {
  99743. // You can only trigger the action buttons with a joystick declared
  99744. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  99745. this._action();
  99746. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  99747. }
  99748. }
  99749. };
  99750. VirtualJoystick.prototype._onPointerMove = function (e) {
  99751. // If the current pointer is the one associated to the joystick (first touch contact)
  99752. if (this._joystickPointerID == e.pointerId) {
  99753. this._joystickPointerPos.x = e.clientX;
  99754. this._joystickPointerPos.y = e.clientY;
  99755. this._deltaJoystickVector = this._joystickPointerPos.clone();
  99756. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  99757. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  99758. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  99759. switch (this._axisTargetedByLeftAndRight) {
  99760. case JoystickAxis.X:
  99761. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  99762. break;
  99763. case JoystickAxis.Y:
  99764. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  99765. break;
  99766. case JoystickAxis.Z:
  99767. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  99768. break;
  99769. }
  99770. var directionUpDown = this.reverseUpDown ? 1 : -1;
  99771. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  99772. switch (this._axisTargetedByUpAndDown) {
  99773. case JoystickAxis.X:
  99774. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  99775. break;
  99776. case JoystickAxis.Y:
  99777. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  99778. break;
  99779. case JoystickAxis.Z:
  99780. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  99781. break;
  99782. }
  99783. }
  99784. else {
  99785. var data = this._touches.get(e.pointerId.toString());
  99786. if (data) {
  99787. data.x = e.clientX;
  99788. data.y = e.clientY;
  99789. }
  99790. }
  99791. };
  99792. VirtualJoystick.prototype._onPointerUp = function (e) {
  99793. if (this._joystickPointerID == e.pointerId) {
  99794. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  99795. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  99796. this._joystickPointerID = -1;
  99797. this.pressed = false;
  99798. }
  99799. else {
  99800. var touch = this._touches.get(e.pointerId.toString());
  99801. if (touch) {
  99802. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99803. }
  99804. }
  99805. this._deltaJoystickVector.x = 0;
  99806. this._deltaJoystickVector.y = 0;
  99807. this._touches.remove(e.pointerId.toString());
  99808. };
  99809. /**
  99810. * Change the color of the virtual joystick
  99811. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  99812. */
  99813. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  99814. this._joystickColor = newColor;
  99815. };
  99816. /**
  99817. * Defines a callback to call when the joystick is touched
  99818. * @param action defines the callback
  99819. */
  99820. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  99821. this._action = action;
  99822. };
  99823. /**
  99824. * Defines which axis you'd like to control for left & right
  99825. * @param axis defines the axis to use
  99826. */
  99827. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  99828. switch (axis) {
  99829. case JoystickAxis.X:
  99830. case JoystickAxis.Y:
  99831. case JoystickAxis.Z:
  99832. this._axisTargetedByLeftAndRight = axis;
  99833. break;
  99834. default:
  99835. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  99836. break;
  99837. }
  99838. };
  99839. /**
  99840. * Defines which axis you'd like to control for up & down
  99841. * @param axis defines the axis to use
  99842. */
  99843. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  99844. switch (axis) {
  99845. case JoystickAxis.X:
  99846. case JoystickAxis.Y:
  99847. case JoystickAxis.Z:
  99848. this._axisTargetedByUpAndDown = axis;
  99849. break;
  99850. default:
  99851. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  99852. break;
  99853. }
  99854. };
  99855. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  99856. var _this = this;
  99857. if (this.pressed) {
  99858. this._touches.forEach(function (key, touch) {
  99859. if (touch.pointerId === _this._joystickPointerID) {
  99860. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  99861. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  99862. VirtualJoystick.vjCanvasContext.beginPath();
  99863. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99864. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99865. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  99866. VirtualJoystick.vjCanvasContext.stroke();
  99867. VirtualJoystick.vjCanvasContext.closePath();
  99868. VirtualJoystick.vjCanvasContext.beginPath();
  99869. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99870. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  99871. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  99872. VirtualJoystick.vjCanvasContext.stroke();
  99873. VirtualJoystick.vjCanvasContext.closePath();
  99874. VirtualJoystick.vjCanvasContext.beginPath();
  99875. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99876. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  99877. VirtualJoystick.vjCanvasContext.stroke();
  99878. VirtualJoystick.vjCanvasContext.closePath();
  99879. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  99880. }
  99881. else {
  99882. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99883. VirtualJoystick.vjCanvasContext.beginPath();
  99884. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  99885. VirtualJoystick.vjCanvasContext.beginPath();
  99886. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  99887. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99888. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  99889. VirtualJoystick.vjCanvasContext.stroke();
  99890. VirtualJoystick.vjCanvasContext.closePath();
  99891. touch.prevX = touch.x;
  99892. touch.prevY = touch.y;
  99893. }
  99894. ;
  99895. });
  99896. }
  99897. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  99898. };
  99899. /**
  99900. * Release internal HTML canvas
  99901. */
  99902. VirtualJoystick.prototype.releaseCanvas = function () {
  99903. if (VirtualJoystick.vjCanvas) {
  99904. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  99905. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  99906. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  99907. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  99908. window.removeEventListener("resize", this._onResize);
  99909. document.body.removeChild(VirtualJoystick.vjCanvas);
  99910. VirtualJoystick.vjCanvas = null;
  99911. }
  99912. };
  99913. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  99914. VirtualJoystick._globalJoystickIndex = 0;
  99915. return VirtualJoystick;
  99916. }());
  99917. BABYLON.VirtualJoystick = VirtualJoystick;
  99918. })(BABYLON || (BABYLON = {}));
  99919. //# sourceMappingURL=babylon.virtualJoystick.js.map
  99920. var BABYLON;
  99921. (function (BABYLON) {
  99922. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  99923. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  99924. });
  99925. // We're mainly based on the logic defined into the FreeCamera code
  99926. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  99927. __extends(VirtualJoysticksCamera, _super);
  99928. function VirtualJoysticksCamera(name, position, scene) {
  99929. var _this = _super.call(this, name, position, scene) || this;
  99930. _this.inputs.addVirtualJoystick();
  99931. return _this;
  99932. }
  99933. VirtualJoysticksCamera.prototype.getClassName = function () {
  99934. return "VirtualJoysticksCamera";
  99935. };
  99936. return VirtualJoysticksCamera;
  99937. }(BABYLON.FreeCamera));
  99938. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  99939. })(BABYLON || (BABYLON = {}));
  99940. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  99941. var BABYLON;
  99942. (function (BABYLON) {
  99943. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  99944. function FreeCameraVirtualJoystickInput() {
  99945. }
  99946. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  99947. return this._leftjoystick;
  99948. };
  99949. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  99950. return this._rightjoystick;
  99951. };
  99952. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  99953. if (this._leftjoystick) {
  99954. var camera = this.camera;
  99955. var speed = camera._computeLocalCameraSpeed() * 50;
  99956. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  99957. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  99958. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  99959. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  99960. if (!this._leftjoystick.pressed) {
  99961. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  99962. }
  99963. if (!this._rightjoystick.pressed) {
  99964. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  99965. }
  99966. }
  99967. };
  99968. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  99969. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  99970. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  99971. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  99972. this._leftjoystick.setJoystickSensibility(0.15);
  99973. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  99974. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  99975. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  99976. this._rightjoystick.reverseUpDown = true;
  99977. this._rightjoystick.setJoystickSensibility(0.05);
  99978. this._rightjoystick.setJoystickColor("yellow");
  99979. };
  99980. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  99981. this._leftjoystick.releaseCanvas();
  99982. this._rightjoystick.releaseCanvas();
  99983. };
  99984. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  99985. return "FreeCameraVirtualJoystickInput";
  99986. };
  99987. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  99988. return "virtualJoystick";
  99989. };
  99990. return FreeCameraVirtualJoystickInput;
  99991. }());
  99992. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  99993. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  99994. })(BABYLON || (BABYLON = {}));
  99995. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  99996. var BABYLON;
  99997. (function (BABYLON) {
  99998. var SimplificationSettings = /** @class */ (function () {
  99999. function SimplificationSettings(quality, distance, optimizeMesh) {
  100000. this.quality = quality;
  100001. this.distance = distance;
  100002. this.optimizeMesh = optimizeMesh;
  100003. }
  100004. return SimplificationSettings;
  100005. }());
  100006. BABYLON.SimplificationSettings = SimplificationSettings;
  100007. var SimplificationQueue = /** @class */ (function () {
  100008. function SimplificationQueue() {
  100009. this.running = false;
  100010. this._simplificationArray = [];
  100011. }
  100012. SimplificationQueue.prototype.addTask = function (task) {
  100013. this._simplificationArray.push(task);
  100014. };
  100015. SimplificationQueue.prototype.executeNext = function () {
  100016. var task = this._simplificationArray.pop();
  100017. if (task) {
  100018. this.running = true;
  100019. this.runSimplification(task);
  100020. }
  100021. else {
  100022. this.running = false;
  100023. }
  100024. };
  100025. SimplificationQueue.prototype.runSimplification = function (task) {
  100026. var _this = this;
  100027. if (task.parallelProcessing) {
  100028. //parallel simplifier
  100029. task.settings.forEach(function (setting) {
  100030. var simplifier = _this.getSimplifier(task);
  100031. simplifier.simplify(setting, function (newMesh) {
  100032. task.mesh.addLODLevel(setting.distance, newMesh);
  100033. newMesh.isVisible = true;
  100034. //check if it is the last
  100035. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  100036. //all done, run the success callback.
  100037. task.successCallback();
  100038. }
  100039. _this.executeNext();
  100040. });
  100041. });
  100042. }
  100043. else {
  100044. //single simplifier.
  100045. var simplifier = this.getSimplifier(task);
  100046. var runDecimation = function (setting, callback) {
  100047. simplifier.simplify(setting, function (newMesh) {
  100048. task.mesh.addLODLevel(setting.distance, newMesh);
  100049. newMesh.isVisible = true;
  100050. //run the next quality level
  100051. callback();
  100052. });
  100053. };
  100054. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  100055. runDecimation(task.settings[loop.index], function () {
  100056. loop.executeNext();
  100057. });
  100058. }, function () {
  100059. //execution ended, run the success callback.
  100060. if (task.successCallback) {
  100061. task.successCallback();
  100062. }
  100063. _this.executeNext();
  100064. });
  100065. }
  100066. };
  100067. SimplificationQueue.prototype.getSimplifier = function (task) {
  100068. switch (task.simplificationType) {
  100069. case SimplificationType.QUADRATIC:
  100070. default:
  100071. return new QuadraticErrorSimplification(task.mesh);
  100072. }
  100073. };
  100074. return SimplificationQueue;
  100075. }());
  100076. BABYLON.SimplificationQueue = SimplificationQueue;
  100077. /**
  100078. * The implemented types of simplification
  100079. * At the moment only Quadratic Error Decimation is implemented
  100080. */
  100081. var SimplificationType;
  100082. (function (SimplificationType) {
  100083. /** Quadratic error decimation */
  100084. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  100085. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  100086. var DecimationTriangle = /** @class */ (function () {
  100087. function DecimationTriangle(vertices) {
  100088. this.vertices = vertices;
  100089. this.error = new Array(4);
  100090. this.deleted = false;
  100091. this.isDirty = false;
  100092. this.deletePending = false;
  100093. this.borderFactor = 0;
  100094. }
  100095. return DecimationTriangle;
  100096. }());
  100097. BABYLON.DecimationTriangle = DecimationTriangle;
  100098. var DecimationVertex = /** @class */ (function () {
  100099. function DecimationVertex(position, id) {
  100100. this.position = position;
  100101. this.id = id;
  100102. this.isBorder = true;
  100103. this.q = new QuadraticMatrix();
  100104. this.triangleCount = 0;
  100105. this.triangleStart = 0;
  100106. this.originalOffsets = [];
  100107. }
  100108. DecimationVertex.prototype.updatePosition = function (newPosition) {
  100109. this.position.copyFrom(newPosition);
  100110. };
  100111. return DecimationVertex;
  100112. }());
  100113. BABYLON.DecimationVertex = DecimationVertex;
  100114. var QuadraticMatrix = /** @class */ (function () {
  100115. function QuadraticMatrix(data) {
  100116. this.data = new Array(10);
  100117. for (var i = 0; i < 10; ++i) {
  100118. if (data && data[i]) {
  100119. this.data[i] = data[i];
  100120. }
  100121. else {
  100122. this.data[i] = 0;
  100123. }
  100124. }
  100125. }
  100126. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  100127. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  100128. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  100129. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  100130. return det;
  100131. };
  100132. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  100133. for (var i = 0; i < 10; ++i) {
  100134. this.data[i] += matrix.data[i];
  100135. }
  100136. };
  100137. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  100138. for (var i = 0; i < 10; ++i) {
  100139. this.data[i] += data[i];
  100140. }
  100141. };
  100142. QuadraticMatrix.prototype.add = function (matrix) {
  100143. var m = new QuadraticMatrix();
  100144. for (var i = 0; i < 10; ++i) {
  100145. m.data[i] = this.data[i] + matrix.data[i];
  100146. }
  100147. return m;
  100148. };
  100149. QuadraticMatrix.FromData = function (a, b, c, d) {
  100150. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  100151. };
  100152. //returning an array to avoid garbage collection
  100153. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  100154. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  100155. };
  100156. return QuadraticMatrix;
  100157. }());
  100158. BABYLON.QuadraticMatrix = QuadraticMatrix;
  100159. var Reference = /** @class */ (function () {
  100160. function Reference(vertexId, triangleId) {
  100161. this.vertexId = vertexId;
  100162. this.triangleId = triangleId;
  100163. }
  100164. return Reference;
  100165. }());
  100166. BABYLON.Reference = Reference;
  100167. /**
  100168. * An implementation of the Quadratic Error simplification algorithm.
  100169. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  100170. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  100171. * @author RaananW
  100172. */
  100173. var QuadraticErrorSimplification = /** @class */ (function () {
  100174. function QuadraticErrorSimplification(_mesh) {
  100175. this._mesh = _mesh;
  100176. this.syncIterations = 5000;
  100177. this.aggressiveness = 7;
  100178. this.decimationIterations = 100;
  100179. this.boundingBoxEpsilon = BABYLON.Epsilon;
  100180. }
  100181. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  100182. var _this = this;
  100183. this.initDecimatedMesh();
  100184. //iterating through the submeshes array, one after the other.
  100185. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  100186. _this.initWithMesh(loop.index, function () {
  100187. _this.runDecimation(settings, loop.index, function () {
  100188. loop.executeNext();
  100189. });
  100190. }, settings.optimizeMesh);
  100191. }, function () {
  100192. setTimeout(function () {
  100193. successCallback(_this._reconstructedMesh);
  100194. }, 0);
  100195. });
  100196. };
  100197. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  100198. var _this = this;
  100199. var targetCount = ~~(this.triangles.length * settings.quality);
  100200. var deletedTriangles = 0;
  100201. var triangleCount = this.triangles.length;
  100202. var iterationFunction = function (iteration, callback) {
  100203. setTimeout(function () {
  100204. if (iteration % 5 === 0) {
  100205. _this.updateMesh(iteration === 0);
  100206. }
  100207. for (var i = 0; i < _this.triangles.length; ++i) {
  100208. _this.triangles[i].isDirty = false;
  100209. }
  100210. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  100211. var trianglesIterator = function (i) {
  100212. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  100213. var t = _this.triangles[tIdx];
  100214. if (!t)
  100215. return;
  100216. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  100217. return;
  100218. }
  100219. for (var j = 0; j < 3; ++j) {
  100220. if (t.error[j] < threshold) {
  100221. var deleted0 = [];
  100222. var deleted1 = [];
  100223. var v0 = t.vertices[j];
  100224. var v1 = t.vertices[(j + 1) % 3];
  100225. if (v0.isBorder || v1.isBorder)
  100226. continue;
  100227. var p = BABYLON.Vector3.Zero();
  100228. var n = BABYLON.Vector3.Zero();
  100229. var uv = BABYLON.Vector2.Zero();
  100230. var color = new BABYLON.Color4(0, 0, 0, 1);
  100231. _this.calculateError(v0, v1, p, n, uv, color);
  100232. var delTr = new Array();
  100233. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  100234. continue;
  100235. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  100236. continue;
  100237. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  100238. continue;
  100239. var uniqueArray = new Array();
  100240. delTr.forEach(function (deletedT) {
  100241. if (uniqueArray.indexOf(deletedT) === -1) {
  100242. deletedT.deletePending = true;
  100243. uniqueArray.push(deletedT);
  100244. }
  100245. });
  100246. if (uniqueArray.length % 2 !== 0) {
  100247. continue;
  100248. }
  100249. v0.q = v1.q.add(v0.q);
  100250. v0.updatePosition(p);
  100251. var tStart = _this.references.length;
  100252. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  100253. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  100254. var tCount = _this.references.length - tStart;
  100255. if (tCount <= v0.triangleCount) {
  100256. if (tCount) {
  100257. for (var c = 0; c < tCount; c++) {
  100258. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  100259. }
  100260. }
  100261. }
  100262. else {
  100263. v0.triangleStart = tStart;
  100264. }
  100265. v0.triangleCount = tCount;
  100266. break;
  100267. }
  100268. }
  100269. };
  100270. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  100271. }, 0);
  100272. };
  100273. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  100274. if (triangleCount - deletedTriangles <= targetCount)
  100275. loop.breakLoop();
  100276. else {
  100277. iterationFunction(loop.index, function () {
  100278. loop.executeNext();
  100279. });
  100280. }
  100281. }, function () {
  100282. setTimeout(function () {
  100283. //reconstruct this part of the mesh
  100284. _this.reconstructMesh(submeshIndex);
  100285. successCallback();
  100286. }, 0);
  100287. });
  100288. };
  100289. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  100290. var _this = this;
  100291. this.vertices = [];
  100292. this.triangles = [];
  100293. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  100294. var indices = this._mesh.getIndices();
  100295. var submesh = this._mesh.subMeshes[submeshIndex];
  100296. var findInVertices = function (positionToSearch) {
  100297. if (optimizeMesh) {
  100298. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  100299. if (_this.vertices[ii].position.equals(positionToSearch)) {
  100300. return _this.vertices[ii];
  100301. }
  100302. }
  100303. }
  100304. return null;
  100305. };
  100306. var vertexReferences = [];
  100307. var vertexInit = function (i) {
  100308. if (!positionData) {
  100309. return;
  100310. }
  100311. var offset = i + submesh.verticesStart;
  100312. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  100313. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  100314. vertex.originalOffsets.push(offset);
  100315. if (vertex.id === _this.vertices.length) {
  100316. _this.vertices.push(vertex);
  100317. }
  100318. vertexReferences.push(vertex.id);
  100319. };
  100320. //var totalVertices = mesh.getTotalVertices();
  100321. var totalVertices = submesh.verticesCount;
  100322. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  100323. var indicesInit = function (i) {
  100324. if (!indices) {
  100325. return;
  100326. }
  100327. var offset = (submesh.indexStart / 3) + i;
  100328. var pos = (offset * 3);
  100329. var i0 = indices[pos + 0];
  100330. var i1 = indices[pos + 1];
  100331. var i2 = indices[pos + 2];
  100332. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  100333. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  100334. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  100335. var triangle = new DecimationTriangle([v0, v1, v2]);
  100336. triangle.originalOffset = pos;
  100337. _this.triangles.push(triangle);
  100338. };
  100339. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  100340. _this.init(callback);
  100341. });
  100342. });
  100343. };
  100344. QuadraticErrorSimplification.prototype.init = function (callback) {
  100345. var _this = this;
  100346. var triangleInit1 = function (i) {
  100347. var t = _this.triangles[i];
  100348. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  100349. for (var j = 0; j < 3; j++) {
  100350. 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))));
  100351. }
  100352. };
  100353. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  100354. var triangleInit2 = function (i) {
  100355. var t = _this.triangles[i];
  100356. for (var j = 0; j < 3; ++j) {
  100357. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  100358. }
  100359. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  100360. };
  100361. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  100362. callback();
  100363. });
  100364. });
  100365. };
  100366. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  100367. var newTriangles = [];
  100368. var i;
  100369. for (i = 0; i < this.vertices.length; ++i) {
  100370. this.vertices[i].triangleCount = 0;
  100371. }
  100372. var t;
  100373. var j;
  100374. for (i = 0; i < this.triangles.length; ++i) {
  100375. if (!this.triangles[i].deleted) {
  100376. t = this.triangles[i];
  100377. for (j = 0; j < 3; ++j) {
  100378. t.vertices[j].triangleCount = 1;
  100379. }
  100380. newTriangles.push(t);
  100381. }
  100382. }
  100383. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  100384. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  100385. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  100386. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  100387. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  100388. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  100389. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  100390. var vertexCount = 0;
  100391. for (i = 0; i < this.vertices.length; ++i) {
  100392. var vertex = this.vertices[i];
  100393. vertex.id = vertexCount;
  100394. if (vertex.triangleCount) {
  100395. vertex.originalOffsets.forEach(function (originalOffset) {
  100396. if (!normalData) {
  100397. return;
  100398. }
  100399. newPositionData.push(vertex.position.x);
  100400. newPositionData.push(vertex.position.y);
  100401. newPositionData.push(vertex.position.z);
  100402. newNormalData.push(normalData[originalOffset * 3]);
  100403. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  100404. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  100405. if (uvs && uvs.length) {
  100406. newUVsData.push(uvs[(originalOffset * 2)]);
  100407. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  100408. }
  100409. else if (colorsData && colorsData.length) {
  100410. newColorsData.push(colorsData[(originalOffset * 4)]);
  100411. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  100412. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  100413. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  100414. }
  100415. ++vertexCount;
  100416. });
  100417. }
  100418. }
  100419. var startingIndex = this._reconstructedMesh.getTotalIndices();
  100420. var startingVertex = this._reconstructedMesh.getTotalVertices();
  100421. var submeshesArray = this._reconstructedMesh.subMeshes;
  100422. this._reconstructedMesh.subMeshes = [];
  100423. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  100424. var originalIndices = this._mesh.getIndices();
  100425. for (i = 0; i < newTriangles.length; ++i) {
  100426. t = newTriangles[i]; //now get the new referencing point for each vertex
  100427. [0, 1, 2].forEach(function (idx) {
  100428. var id = originalIndices[t.originalOffset + idx];
  100429. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  100430. if (offset < 0)
  100431. offset = 0;
  100432. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  100433. });
  100434. }
  100435. //overwriting the old vertex buffers and indices.
  100436. this._reconstructedMesh.setIndices(newIndicesArray);
  100437. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  100438. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  100439. if (newUVsData.length > 0)
  100440. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  100441. if (newColorsData.length > 0)
  100442. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  100443. //create submesh
  100444. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  100445. if (submeshIndex > 0) {
  100446. this._reconstructedMesh.subMeshes = [];
  100447. submeshesArray.forEach(function (submesh) {
  100448. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  100449. });
  100450. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  100451. }
  100452. };
  100453. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  100454. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  100455. this._reconstructedMesh.material = this._mesh.material;
  100456. this._reconstructedMesh.parent = this._mesh.parent;
  100457. this._reconstructedMesh.isVisible = false;
  100458. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  100459. };
  100460. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  100461. for (var i = 0; i < vertex1.triangleCount; ++i) {
  100462. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  100463. if (t.deleted)
  100464. continue;
  100465. var s = this.references[vertex1.triangleStart + i].vertexId;
  100466. var v1 = t.vertices[(s + 1) % 3];
  100467. var v2 = t.vertices[(s + 2) % 3];
  100468. if ((v1 === vertex2 || v2 === vertex2)) {
  100469. deletedArray[i] = true;
  100470. delTr.push(t);
  100471. continue;
  100472. }
  100473. var d1 = v1.position.subtract(point);
  100474. d1 = d1.normalize();
  100475. var d2 = v2.position.subtract(point);
  100476. d2 = d2.normalize();
  100477. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  100478. return true;
  100479. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  100480. deletedArray[i] = false;
  100481. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  100482. return true;
  100483. }
  100484. return false;
  100485. };
  100486. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  100487. var newDeleted = deletedTriangles;
  100488. for (var i = 0; i < vertex.triangleCount; ++i) {
  100489. var ref = this.references[vertex.triangleStart + i];
  100490. var t = this.triangles[ref.triangleId];
  100491. if (t.deleted)
  100492. continue;
  100493. if (deletedArray[i] && t.deletePending) {
  100494. t.deleted = true;
  100495. newDeleted++;
  100496. continue;
  100497. }
  100498. t.vertices[ref.vertexId] = origVertex;
  100499. t.isDirty = true;
  100500. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  100501. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  100502. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  100503. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  100504. this.references.push(ref);
  100505. }
  100506. return newDeleted;
  100507. };
  100508. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  100509. for (var i = 0; i < this.vertices.length; ++i) {
  100510. var vCount = [];
  100511. var vId = [];
  100512. var v = this.vertices[i];
  100513. var j;
  100514. for (j = 0; j < v.triangleCount; ++j) {
  100515. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  100516. for (var ii = 0; ii < 3; ii++) {
  100517. var ofs = 0;
  100518. var vv = triangle.vertices[ii];
  100519. while (ofs < vCount.length) {
  100520. if (vId[ofs] === vv.id)
  100521. break;
  100522. ++ofs;
  100523. }
  100524. if (ofs === vCount.length) {
  100525. vCount.push(1);
  100526. vId.push(vv.id);
  100527. }
  100528. else {
  100529. vCount[ofs]++;
  100530. }
  100531. }
  100532. }
  100533. for (j = 0; j < vCount.length; ++j) {
  100534. if (vCount[j] === 1) {
  100535. this.vertices[vId[j]].isBorder = true;
  100536. }
  100537. else {
  100538. this.vertices[vId[j]].isBorder = false;
  100539. }
  100540. }
  100541. }
  100542. };
  100543. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  100544. if (identifyBorders === void 0) { identifyBorders = false; }
  100545. var i;
  100546. if (!identifyBorders) {
  100547. var newTrianglesVector = [];
  100548. for (i = 0; i < this.triangles.length; ++i) {
  100549. if (!this.triangles[i].deleted) {
  100550. newTrianglesVector.push(this.triangles[i]);
  100551. }
  100552. }
  100553. this.triangles = newTrianglesVector;
  100554. }
  100555. for (i = 0; i < this.vertices.length; ++i) {
  100556. this.vertices[i].triangleCount = 0;
  100557. this.vertices[i].triangleStart = 0;
  100558. }
  100559. var t;
  100560. var j;
  100561. var v;
  100562. for (i = 0; i < this.triangles.length; ++i) {
  100563. t = this.triangles[i];
  100564. for (j = 0; j < 3; ++j) {
  100565. v = t.vertices[j];
  100566. v.triangleCount++;
  100567. }
  100568. }
  100569. var tStart = 0;
  100570. for (i = 0; i < this.vertices.length; ++i) {
  100571. this.vertices[i].triangleStart = tStart;
  100572. tStart += this.vertices[i].triangleCount;
  100573. this.vertices[i].triangleCount = 0;
  100574. }
  100575. var newReferences = new Array(this.triangles.length * 3);
  100576. for (i = 0; i < this.triangles.length; ++i) {
  100577. t = this.triangles[i];
  100578. for (j = 0; j < 3; ++j) {
  100579. v = t.vertices[j];
  100580. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  100581. v.triangleCount++;
  100582. }
  100583. }
  100584. this.references = newReferences;
  100585. if (identifyBorders) {
  100586. this.identifyBorder();
  100587. }
  100588. };
  100589. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  100590. var x = point.x;
  100591. var y = point.y;
  100592. var z = point.z;
  100593. 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
  100594. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  100595. };
  100596. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  100597. var q = vertex1.q.add(vertex2.q);
  100598. var border = vertex1.isBorder && vertex2.isBorder;
  100599. var error = 0;
  100600. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  100601. if (qDet !== 0 && !border) {
  100602. if (!pointResult) {
  100603. pointResult = BABYLON.Vector3.Zero();
  100604. }
  100605. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  100606. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  100607. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  100608. error = this.vertexError(q, pointResult);
  100609. }
  100610. else {
  100611. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  100612. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  100613. var error1 = this.vertexError(q, vertex1.position);
  100614. var error2 = this.vertexError(q, vertex2.position);
  100615. var error3 = this.vertexError(q, p3);
  100616. error = Math.min(error1, error2, error3);
  100617. if (error === error1) {
  100618. if (pointResult) {
  100619. pointResult.copyFrom(vertex1.position);
  100620. }
  100621. }
  100622. else if (error === error2) {
  100623. if (pointResult) {
  100624. pointResult.copyFrom(vertex2.position);
  100625. }
  100626. }
  100627. else {
  100628. if (pointResult) {
  100629. pointResult.copyFrom(p3);
  100630. }
  100631. }
  100632. }
  100633. return error;
  100634. };
  100635. return QuadraticErrorSimplification;
  100636. }());
  100637. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  100638. })(BABYLON || (BABYLON = {}));
  100639. //# sourceMappingURL=babylon.meshSimplification.js.map
  100640. var BABYLON;
  100641. (function (BABYLON) {
  100642. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  100643. get: function () {
  100644. if (!this._simplificationQueue) {
  100645. this._simplificationQueue = new BABYLON.SimplificationQueue();
  100646. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  100647. if (!component) {
  100648. component = new SimplicationQueueSceneComponent(this);
  100649. this._addComponent(component);
  100650. }
  100651. }
  100652. return this._simplificationQueue;
  100653. },
  100654. set: function (value) {
  100655. this._simplificationQueue = value;
  100656. },
  100657. enumerable: true,
  100658. configurable: true
  100659. });
  100660. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  100661. if (parallelProcessing === void 0) { parallelProcessing = true; }
  100662. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  100663. this.getScene().simplificationQueue.addTask({
  100664. settings: settings,
  100665. parallelProcessing: parallelProcessing,
  100666. mesh: this,
  100667. simplificationType: simplificationType,
  100668. successCallback: successCallback
  100669. });
  100670. return this;
  100671. };
  100672. /**
  100673. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  100674. * created in a scene
  100675. */
  100676. var SimplicationQueueSceneComponent = /** @class */ (function () {
  100677. /**
  100678. * Creates a new instance of the component for the given scene
  100679. * @param scene Defines the scene to register the component in
  100680. */
  100681. function SimplicationQueueSceneComponent(scene) {
  100682. /**
  100683. * The component name helpfull to identify the component in the list of scene components.
  100684. */
  100685. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  100686. this.scene = scene;
  100687. }
  100688. /**
  100689. * Registers the component in a given scene
  100690. */
  100691. SimplicationQueueSceneComponent.prototype.register = function () {
  100692. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  100693. };
  100694. /**
  100695. * Rebuilds the elements related to this component in case of
  100696. * context lost for instance.
  100697. */
  100698. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  100699. // Nothing to do for this component
  100700. };
  100701. /**
  100702. * Disposes the component and the associated ressources
  100703. */
  100704. SimplicationQueueSceneComponent.prototype.dispose = function () {
  100705. // Nothing to do for this component
  100706. };
  100707. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  100708. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  100709. this.scene._simplificationQueue.executeNext();
  100710. }
  100711. };
  100712. return SimplicationQueueSceneComponent;
  100713. }());
  100714. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  100715. })(BABYLON || (BABYLON = {}));
  100716. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  100717. var BABYLON;
  100718. (function (BABYLON) {
  100719. var MeshLODLevel = /** @class */ (function () {
  100720. function MeshLODLevel(distance, mesh) {
  100721. this.distance = distance;
  100722. this.mesh = mesh;
  100723. }
  100724. return MeshLODLevel;
  100725. }());
  100726. BABYLON.MeshLODLevel = MeshLODLevel;
  100727. })(BABYLON || (BABYLON = {}));
  100728. //# sourceMappingURL=babylon.meshLODLevel.js.map
  100729. var BABYLON;
  100730. (function (BABYLON) {
  100731. /**
  100732. * Defines the root class used to create scene optimization to use with SceneOptimizer
  100733. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100734. */
  100735. var SceneOptimization = /** @class */ (function () {
  100736. /**
  100737. * Creates the SceneOptimization object
  100738. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100739. * @param desc defines the description associated with the optimization
  100740. */
  100741. function SceneOptimization(
  100742. /**
  100743. * Defines the priority of this optimization (0 by default which means first in the list)
  100744. */
  100745. priority) {
  100746. if (priority === void 0) { priority = 0; }
  100747. this.priority = priority;
  100748. }
  100749. /**
  100750. * Gets a string describing the action executed by the current optimization
  100751. * @returns description string
  100752. */
  100753. SceneOptimization.prototype.getDescription = function () {
  100754. return "";
  100755. };
  100756. /**
  100757. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100758. * @param scene defines the current scene where to apply this optimization
  100759. * @param optimizer defines the current optimizer
  100760. * @returns true if everything that can be done was applied
  100761. */
  100762. SceneOptimization.prototype.apply = function (scene, optimizer) {
  100763. return true;
  100764. };
  100765. ;
  100766. return SceneOptimization;
  100767. }());
  100768. BABYLON.SceneOptimization = SceneOptimization;
  100769. /**
  100770. * Defines an optimization used to reduce the size of render target textures
  100771. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100772. */
  100773. var TextureOptimization = /** @class */ (function (_super) {
  100774. __extends(TextureOptimization, _super);
  100775. /**
  100776. * Creates the TextureOptimization object
  100777. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100778. * @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
  100779. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  100780. */
  100781. function TextureOptimization(
  100782. /**
  100783. * Defines the priority of this optimization (0 by default which means first in the list)
  100784. */
  100785. priority,
  100786. /**
  100787. * 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
  100788. */
  100789. maximumSize,
  100790. /**
  100791. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  100792. */
  100793. step) {
  100794. if (priority === void 0) { priority = 0; }
  100795. if (maximumSize === void 0) { maximumSize = 1024; }
  100796. if (step === void 0) { step = 0.5; }
  100797. var _this = _super.call(this, priority) || this;
  100798. _this.priority = priority;
  100799. _this.maximumSize = maximumSize;
  100800. _this.step = step;
  100801. return _this;
  100802. }
  100803. /**
  100804. * Gets a string describing the action executed by the current optimization
  100805. * @returns description string
  100806. */
  100807. TextureOptimization.prototype.getDescription = function () {
  100808. return "Reducing render target texture size to " + this.maximumSize;
  100809. };
  100810. /**
  100811. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100812. * @param scene defines the current scene where to apply this optimization
  100813. * @param optimizer defines the current optimizer
  100814. * @returns true if everything that can be done was applied
  100815. */
  100816. TextureOptimization.prototype.apply = function (scene, optimizer) {
  100817. var allDone = true;
  100818. for (var index = 0; index < scene.textures.length; index++) {
  100819. var texture = scene.textures[index];
  100820. if (!texture.canRescale || texture.getContext) {
  100821. continue;
  100822. }
  100823. var currentSize = texture.getSize();
  100824. var maxDimension = Math.max(currentSize.width, currentSize.height);
  100825. if (maxDimension > this.maximumSize) {
  100826. texture.scale(this.step);
  100827. allDone = false;
  100828. }
  100829. }
  100830. return allDone;
  100831. };
  100832. return TextureOptimization;
  100833. }(SceneOptimization));
  100834. BABYLON.TextureOptimization = TextureOptimization;
  100835. /**
  100836. * Defines an optimization used to increase or decrease the rendering resolution
  100837. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100838. */
  100839. var HardwareScalingOptimization = /** @class */ (function (_super) {
  100840. __extends(HardwareScalingOptimization, _super);
  100841. /**
  100842. * Creates the HardwareScalingOptimization object
  100843. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100844. * @param maximumScale defines the maximum scale to use (2 by default)
  100845. * @param step defines the step to use between two passes (0.5 by default)
  100846. */
  100847. function HardwareScalingOptimization(
  100848. /**
  100849. * Defines the priority of this optimization (0 by default which means first in the list)
  100850. */
  100851. priority,
  100852. /**
  100853. * Defines the maximum scale to use (2 by default)
  100854. */
  100855. maximumScale,
  100856. /**
  100857. * Defines the step to use between two passes (0.5 by default)
  100858. */
  100859. step) {
  100860. if (priority === void 0) { priority = 0; }
  100861. if (maximumScale === void 0) { maximumScale = 2; }
  100862. if (step === void 0) { step = 0.25; }
  100863. var _this = _super.call(this, priority) || this;
  100864. _this.priority = priority;
  100865. _this.maximumScale = maximumScale;
  100866. _this.step = step;
  100867. _this._currentScale = -1;
  100868. _this._directionOffset = 1;
  100869. return _this;
  100870. }
  100871. /**
  100872. * Gets a string describing the action executed by the current optimization
  100873. * @return description string
  100874. */
  100875. HardwareScalingOptimization.prototype.getDescription = function () {
  100876. return "Setting hardware scaling level to " + this._currentScale;
  100877. };
  100878. /**
  100879. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100880. * @param scene defines the current scene where to apply this optimization
  100881. * @param optimizer defines the current optimizer
  100882. * @returns true if everything that can be done was applied
  100883. */
  100884. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  100885. if (this._currentScale === -1) {
  100886. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  100887. if (this._currentScale > this.maximumScale) {
  100888. this._directionOffset = -1;
  100889. }
  100890. }
  100891. this._currentScale += this._directionOffset * this.step;
  100892. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  100893. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  100894. };
  100895. ;
  100896. return HardwareScalingOptimization;
  100897. }(SceneOptimization));
  100898. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  100899. /**
  100900. * Defines an optimization used to remove shadows
  100901. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100902. */
  100903. var ShadowsOptimization = /** @class */ (function (_super) {
  100904. __extends(ShadowsOptimization, _super);
  100905. function ShadowsOptimization() {
  100906. return _super !== null && _super.apply(this, arguments) || this;
  100907. }
  100908. /**
  100909. * Gets a string describing the action executed by the current optimization
  100910. * @return description string
  100911. */
  100912. ShadowsOptimization.prototype.getDescription = function () {
  100913. return "Turning shadows on/off";
  100914. };
  100915. /**
  100916. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100917. * @param scene defines the current scene where to apply this optimization
  100918. * @param optimizer defines the current optimizer
  100919. * @returns true if everything that can be done was applied
  100920. */
  100921. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  100922. scene.shadowsEnabled = optimizer.isInImprovementMode;
  100923. return true;
  100924. };
  100925. ;
  100926. return ShadowsOptimization;
  100927. }(SceneOptimization));
  100928. BABYLON.ShadowsOptimization = ShadowsOptimization;
  100929. /**
  100930. * Defines an optimization used to turn post-processes off
  100931. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100932. */
  100933. var PostProcessesOptimization = /** @class */ (function (_super) {
  100934. __extends(PostProcessesOptimization, _super);
  100935. function PostProcessesOptimization() {
  100936. return _super !== null && _super.apply(this, arguments) || this;
  100937. }
  100938. /**
  100939. * Gets a string describing the action executed by the current optimization
  100940. * @return description string
  100941. */
  100942. PostProcessesOptimization.prototype.getDescription = function () {
  100943. return "Turning post-processes on/off";
  100944. };
  100945. /**
  100946. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100947. * @param scene defines the current scene where to apply this optimization
  100948. * @param optimizer defines the current optimizer
  100949. * @returns true if everything that can be done was applied
  100950. */
  100951. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  100952. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  100953. return true;
  100954. };
  100955. ;
  100956. return PostProcessesOptimization;
  100957. }(SceneOptimization));
  100958. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  100959. /**
  100960. * Defines an optimization used to turn lens flares off
  100961. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100962. */
  100963. var LensFlaresOptimization = /** @class */ (function (_super) {
  100964. __extends(LensFlaresOptimization, _super);
  100965. function LensFlaresOptimization() {
  100966. return _super !== null && _super.apply(this, arguments) || this;
  100967. }
  100968. /**
  100969. * Gets a string describing the action executed by the current optimization
  100970. * @return description string
  100971. */
  100972. LensFlaresOptimization.prototype.getDescription = function () {
  100973. return "Turning lens flares on/off";
  100974. };
  100975. /**
  100976. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100977. * @param scene defines the current scene where to apply this optimization
  100978. * @param optimizer defines the current optimizer
  100979. * @returns true if everything that can be done was applied
  100980. */
  100981. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  100982. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  100983. return true;
  100984. };
  100985. ;
  100986. return LensFlaresOptimization;
  100987. }(SceneOptimization));
  100988. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  100989. /**
  100990. * Defines an optimization based on user defined callback.
  100991. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100992. */
  100993. var CustomOptimization = /** @class */ (function (_super) {
  100994. __extends(CustomOptimization, _super);
  100995. function CustomOptimization() {
  100996. return _super !== null && _super.apply(this, arguments) || this;
  100997. }
  100998. /**
  100999. * Gets a string describing the action executed by the current optimization
  101000. * @returns description string
  101001. */
  101002. CustomOptimization.prototype.getDescription = function () {
  101003. if (this.onGetDescription) {
  101004. return this.onGetDescription();
  101005. }
  101006. return "Running user defined callback";
  101007. };
  101008. /**
  101009. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  101010. * @param scene defines the current scene where to apply this optimization
  101011. * @param optimizer defines the current optimizer
  101012. * @returns true if everything that can be done was applied
  101013. */
  101014. CustomOptimization.prototype.apply = function (scene, optimizer) {
  101015. if (this.onApply) {
  101016. return this.onApply(scene, optimizer);
  101017. }
  101018. return true;
  101019. };
  101020. ;
  101021. return CustomOptimization;
  101022. }(SceneOptimization));
  101023. BABYLON.CustomOptimization = CustomOptimization;
  101024. /**
  101025. * Defines an optimization used to turn particles off
  101026. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  101027. */
  101028. var ParticlesOptimization = /** @class */ (function (_super) {
  101029. __extends(ParticlesOptimization, _super);
  101030. function ParticlesOptimization() {
  101031. return _super !== null && _super.apply(this, arguments) || this;
  101032. }
  101033. /**
  101034. * Gets a string describing the action executed by the current optimization
  101035. * @return description string
  101036. */
  101037. ParticlesOptimization.prototype.getDescription = function () {
  101038. return "Turning particles on/off";
  101039. };
  101040. /**
  101041. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  101042. * @param scene defines the current scene where to apply this optimization
  101043. * @param optimizer defines the current optimizer
  101044. * @returns true if everything that can be done was applied
  101045. */
  101046. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  101047. scene.particlesEnabled = optimizer.isInImprovementMode;
  101048. return true;
  101049. };
  101050. ;
  101051. return ParticlesOptimization;
  101052. }(SceneOptimization));
  101053. BABYLON.ParticlesOptimization = ParticlesOptimization;
  101054. /**
  101055. * Defines an optimization used to turn render targets off
  101056. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  101057. */
  101058. var RenderTargetsOptimization = /** @class */ (function (_super) {
  101059. __extends(RenderTargetsOptimization, _super);
  101060. function RenderTargetsOptimization() {
  101061. return _super !== null && _super.apply(this, arguments) || this;
  101062. }
  101063. /**
  101064. * Gets a string describing the action executed by the current optimization
  101065. * @return description string
  101066. */
  101067. RenderTargetsOptimization.prototype.getDescription = function () {
  101068. return "Turning render targets off";
  101069. };
  101070. /**
  101071. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  101072. * @param scene defines the current scene where to apply this optimization
  101073. * @param optimizer defines the current optimizer
  101074. * @returns true if everything that can be done was applied
  101075. */
  101076. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  101077. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  101078. return true;
  101079. };
  101080. ;
  101081. return RenderTargetsOptimization;
  101082. }(SceneOptimization));
  101083. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  101084. /**
  101085. * Defines an optimization used to merge meshes with compatible materials
  101086. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  101087. */
  101088. var MergeMeshesOptimization = /** @class */ (function (_super) {
  101089. __extends(MergeMeshesOptimization, _super);
  101090. function MergeMeshesOptimization() {
  101091. var _this = _super !== null && _super.apply(this, arguments) || this;
  101092. _this._canBeMerged = function (abstractMesh) {
  101093. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  101094. return false;
  101095. }
  101096. var mesh = abstractMesh;
  101097. if (mesh.isDisposed()) {
  101098. return false;
  101099. }
  101100. if (!mesh.isVisible || !mesh.isEnabled()) {
  101101. return false;
  101102. }
  101103. if (mesh.instances.length > 0) {
  101104. return false;
  101105. }
  101106. if (mesh.skeleton || mesh.hasLODLevels) {
  101107. return false;
  101108. }
  101109. return true;
  101110. };
  101111. return _this;
  101112. }
  101113. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  101114. /**
  101115. * Gets or sets a boolean which defines if optimization octree has to be updated
  101116. */
  101117. get: function () {
  101118. return MergeMeshesOptimization._UpdateSelectionTree;
  101119. },
  101120. /**
  101121. * Gets or sets a boolean which defines if optimization octree has to be updated
  101122. */
  101123. set: function (value) {
  101124. MergeMeshesOptimization._UpdateSelectionTree = value;
  101125. },
  101126. enumerable: true,
  101127. configurable: true
  101128. });
  101129. /**
  101130. * Gets a string describing the action executed by the current optimization
  101131. * @return description string
  101132. */
  101133. MergeMeshesOptimization.prototype.getDescription = function () {
  101134. return "Merging similar meshes together";
  101135. };
  101136. /**
  101137. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  101138. * @param scene defines the current scene where to apply this optimization
  101139. * @param optimizer defines the current optimizer
  101140. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  101141. * @returns true if everything that can be done was applied
  101142. */
  101143. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  101144. var globalPool = scene.meshes.slice(0);
  101145. var globalLength = globalPool.length;
  101146. for (var index = 0; index < globalLength; index++) {
  101147. var currentPool = new Array();
  101148. var current = globalPool[index];
  101149. // Checks
  101150. if (!this._canBeMerged(current)) {
  101151. continue;
  101152. }
  101153. currentPool.push(current);
  101154. // Find compatible meshes
  101155. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  101156. var otherMesh = globalPool[subIndex];
  101157. if (!this._canBeMerged(otherMesh)) {
  101158. continue;
  101159. }
  101160. if (otherMesh.material !== current.material) {
  101161. continue;
  101162. }
  101163. if (otherMesh.checkCollisions !== current.checkCollisions) {
  101164. continue;
  101165. }
  101166. currentPool.push(otherMesh);
  101167. globalLength--;
  101168. globalPool.splice(subIndex, 1);
  101169. subIndex--;
  101170. }
  101171. if (currentPool.length < 2) {
  101172. continue;
  101173. }
  101174. // Merge meshes
  101175. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  101176. }
  101177. // Call the octree system optimization if it is defined.
  101178. var sceneAsAny = scene;
  101179. if (sceneAsAny.createOrUpdateSelectionOctree) {
  101180. if (updateSelectionTree != undefined) {
  101181. if (updateSelectionTree) {
  101182. sceneAsAny.createOrUpdateSelectionOctree();
  101183. }
  101184. }
  101185. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  101186. sceneAsAny.createOrUpdateSelectionOctree();
  101187. }
  101188. }
  101189. return true;
  101190. };
  101191. ;
  101192. MergeMeshesOptimization._UpdateSelectionTree = false;
  101193. return MergeMeshesOptimization;
  101194. }(SceneOptimization));
  101195. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  101196. /**
  101197. * Defines a list of options used by SceneOptimizer
  101198. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  101199. */
  101200. var SceneOptimizerOptions = /** @class */ (function () {
  101201. /**
  101202. * Creates a new list of options used by SceneOptimizer
  101203. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  101204. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  101205. */
  101206. function SceneOptimizerOptions(
  101207. /**
  101208. * Defines the target frame rate to reach (60 by default)
  101209. */
  101210. targetFrameRate,
  101211. /**
  101212. * Defines the interval between two checkes (2000ms by default)
  101213. */
  101214. trackerDuration) {
  101215. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  101216. if (trackerDuration === void 0) { trackerDuration = 2000; }
  101217. this.targetFrameRate = targetFrameRate;
  101218. this.trackerDuration = trackerDuration;
  101219. /**
  101220. * Gets the list of optimizations to apply
  101221. */
  101222. this.optimizations = new Array();
  101223. }
  101224. /**
  101225. * Add a new optimization
  101226. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  101227. * @returns the current SceneOptimizerOptions
  101228. */
  101229. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  101230. this.optimizations.push(optimization);
  101231. return this;
  101232. };
  101233. /**
  101234. * Add a new custom optimization
  101235. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  101236. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  101237. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  101238. * @returns the current SceneOptimizerOptions
  101239. */
  101240. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  101241. if (priority === void 0) { priority = 0; }
  101242. var optimization = new CustomOptimization(priority);
  101243. optimization.onApply = onApply;
  101244. optimization.onGetDescription = onGetDescription;
  101245. this.optimizations.push(optimization);
  101246. return this;
  101247. };
  101248. /**
  101249. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  101250. * @param targetFrameRate defines the target frame rate (60 by default)
  101251. * @returns a SceneOptimizerOptions object
  101252. */
  101253. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  101254. var result = new SceneOptimizerOptions(targetFrameRate);
  101255. var priority = 0;
  101256. result.addOptimization(new MergeMeshesOptimization(priority));
  101257. result.addOptimization(new ShadowsOptimization(priority));
  101258. result.addOptimization(new LensFlaresOptimization(priority));
  101259. // Next priority
  101260. priority++;
  101261. result.addOptimization(new PostProcessesOptimization(priority));
  101262. result.addOptimization(new ParticlesOptimization(priority));
  101263. // Next priority
  101264. priority++;
  101265. result.addOptimization(new TextureOptimization(priority, 1024));
  101266. return result;
  101267. };
  101268. /**
  101269. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  101270. * @param targetFrameRate defines the target frame rate (60 by default)
  101271. * @returns a SceneOptimizerOptions object
  101272. */
  101273. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  101274. var result = new SceneOptimizerOptions(targetFrameRate);
  101275. var priority = 0;
  101276. result.addOptimization(new MergeMeshesOptimization(priority));
  101277. result.addOptimization(new ShadowsOptimization(priority));
  101278. result.addOptimization(new LensFlaresOptimization(priority));
  101279. // Next priority
  101280. priority++;
  101281. result.addOptimization(new PostProcessesOptimization(priority));
  101282. result.addOptimization(new ParticlesOptimization(priority));
  101283. // Next priority
  101284. priority++;
  101285. result.addOptimization(new TextureOptimization(priority, 512));
  101286. // Next priority
  101287. priority++;
  101288. result.addOptimization(new RenderTargetsOptimization(priority));
  101289. // Next priority
  101290. priority++;
  101291. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  101292. return result;
  101293. };
  101294. /**
  101295. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  101296. * @param targetFrameRate defines the target frame rate (60 by default)
  101297. * @returns a SceneOptimizerOptions object
  101298. */
  101299. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  101300. var result = new SceneOptimizerOptions(targetFrameRate);
  101301. var priority = 0;
  101302. result.addOptimization(new MergeMeshesOptimization(priority));
  101303. result.addOptimization(new ShadowsOptimization(priority));
  101304. result.addOptimization(new LensFlaresOptimization(priority));
  101305. // Next priority
  101306. priority++;
  101307. result.addOptimization(new PostProcessesOptimization(priority));
  101308. result.addOptimization(new ParticlesOptimization(priority));
  101309. // Next priority
  101310. priority++;
  101311. result.addOptimization(new TextureOptimization(priority, 256));
  101312. // Next priority
  101313. priority++;
  101314. result.addOptimization(new RenderTargetsOptimization(priority));
  101315. // Next priority
  101316. priority++;
  101317. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  101318. return result;
  101319. };
  101320. return SceneOptimizerOptions;
  101321. }());
  101322. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  101323. /**
  101324. * Class used to run optimizations in order to reach a target frame rate
  101325. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  101326. */
  101327. var SceneOptimizer = /** @class */ (function () {
  101328. /**
  101329. * Creates a new SceneOptimizer
  101330. * @param scene defines the scene to work on
  101331. * @param options defines the options to use with the SceneOptimizer
  101332. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  101333. * @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)
  101334. */
  101335. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  101336. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  101337. if (improvementMode === void 0) { improvementMode = false; }
  101338. var _this = this;
  101339. this._isRunning = false;
  101340. this._currentPriorityLevel = 0;
  101341. this._targetFrameRate = 60;
  101342. this._trackerDuration = 2000;
  101343. this._currentFrameRate = 0;
  101344. this._improvementMode = false;
  101345. /**
  101346. * Defines an observable called when the optimizer reaches the target frame rate
  101347. */
  101348. this.onSuccessObservable = new BABYLON.Observable();
  101349. /**
  101350. * Defines an observable called when the optimizer enables an optimization
  101351. */
  101352. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  101353. /**
  101354. * Defines an observable called when the optimizer is not able to reach the target frame rate
  101355. */
  101356. this.onFailureObservable = new BABYLON.Observable();
  101357. if (!options) {
  101358. this._options = new SceneOptimizerOptions();
  101359. }
  101360. else {
  101361. this._options = options;
  101362. }
  101363. if (this._options.targetFrameRate) {
  101364. this._targetFrameRate = this._options.targetFrameRate;
  101365. }
  101366. if (this._options.trackerDuration) {
  101367. this._trackerDuration = this._options.trackerDuration;
  101368. }
  101369. if (autoGeneratePriorities) {
  101370. var priority = 0;
  101371. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  101372. var optim = _a[_i];
  101373. optim.priority = priority++;
  101374. }
  101375. }
  101376. this._improvementMode = improvementMode;
  101377. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  101378. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  101379. _this._sceneDisposeObserver = null;
  101380. _this.dispose();
  101381. });
  101382. }
  101383. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  101384. /**
  101385. * Gets a boolean indicating if the optimizer is in improvement mode
  101386. */
  101387. get: function () {
  101388. return this._improvementMode;
  101389. },
  101390. enumerable: true,
  101391. configurable: true
  101392. });
  101393. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  101394. /**
  101395. * Gets the current priority level (0 at start)
  101396. */
  101397. get: function () {
  101398. return this._currentPriorityLevel;
  101399. },
  101400. enumerable: true,
  101401. configurable: true
  101402. });
  101403. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  101404. /**
  101405. * Gets the current frame rate checked by the SceneOptimizer
  101406. */
  101407. get: function () {
  101408. return this._currentFrameRate;
  101409. },
  101410. enumerable: true,
  101411. configurable: true
  101412. });
  101413. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  101414. /**
  101415. * Gets or sets the current target frame rate (60 by default)
  101416. */
  101417. get: function () {
  101418. return this._targetFrameRate;
  101419. },
  101420. /**
  101421. * Gets or sets the current target frame rate (60 by default)
  101422. */
  101423. set: function (value) {
  101424. this._targetFrameRate = value;
  101425. },
  101426. enumerable: true,
  101427. configurable: true
  101428. });
  101429. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  101430. /**
  101431. * Gets or sets the current interval between two checks (every 2000ms by default)
  101432. */
  101433. get: function () {
  101434. return this._trackerDuration;
  101435. },
  101436. /**
  101437. * Gets or sets the current interval between two checks (every 2000ms by default)
  101438. */
  101439. set: function (value) {
  101440. this._trackerDuration = value;
  101441. },
  101442. enumerable: true,
  101443. configurable: true
  101444. });
  101445. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  101446. /**
  101447. * Gets the list of active optimizations
  101448. */
  101449. get: function () {
  101450. return this._options.optimizations;
  101451. },
  101452. enumerable: true,
  101453. configurable: true
  101454. });
  101455. /**
  101456. * Stops the current optimizer
  101457. */
  101458. SceneOptimizer.prototype.stop = function () {
  101459. this._isRunning = false;
  101460. };
  101461. /**
  101462. * Reset the optimizer to initial step (current priority level = 0)
  101463. */
  101464. SceneOptimizer.prototype.reset = function () {
  101465. this._currentPriorityLevel = 0;
  101466. };
  101467. /**
  101468. * Start the optimizer. By default it will try to reach a specific framerate
  101469. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  101470. */
  101471. SceneOptimizer.prototype.start = function () {
  101472. var _this = this;
  101473. if (this._isRunning) {
  101474. return;
  101475. }
  101476. this._isRunning = true;
  101477. // Let's wait for the scene to be ready before running our check
  101478. this._scene.executeWhenReady(function () {
  101479. setTimeout(function () {
  101480. _this._checkCurrentState();
  101481. }, _this._trackerDuration);
  101482. });
  101483. };
  101484. SceneOptimizer.prototype._checkCurrentState = function () {
  101485. var _this = this;
  101486. if (!this._isRunning) {
  101487. return;
  101488. }
  101489. var scene = this._scene;
  101490. var options = this._options;
  101491. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  101492. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  101493. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  101494. this._isRunning = false;
  101495. this.onSuccessObservable.notifyObservers(this);
  101496. return;
  101497. }
  101498. // Apply current level of optimizations
  101499. var allDone = true;
  101500. var noOptimizationApplied = true;
  101501. for (var index = 0; index < options.optimizations.length; index++) {
  101502. var optimization = options.optimizations[index];
  101503. if (optimization.priority === this._currentPriorityLevel) {
  101504. noOptimizationApplied = false;
  101505. allDone = allDone && optimization.apply(scene, this);
  101506. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  101507. }
  101508. }
  101509. // If no optimization was applied, this is a failure :(
  101510. if (noOptimizationApplied) {
  101511. this._isRunning = false;
  101512. this.onFailureObservable.notifyObservers(this);
  101513. return;
  101514. }
  101515. // If all optimizations were done, move to next level
  101516. if (allDone) {
  101517. this._currentPriorityLevel++;
  101518. }
  101519. // Let's the system running for a specific amount of time before checking FPS
  101520. scene.executeWhenReady(function () {
  101521. setTimeout(function () {
  101522. _this._checkCurrentState();
  101523. }, _this._trackerDuration);
  101524. });
  101525. };
  101526. /**
  101527. * Release all resources
  101528. */
  101529. SceneOptimizer.prototype.dispose = function () {
  101530. this.stop();
  101531. this.onSuccessObservable.clear();
  101532. this.onFailureObservable.clear();
  101533. this.onNewOptimizationAppliedObservable.clear();
  101534. if (this._sceneDisposeObserver) {
  101535. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  101536. }
  101537. };
  101538. /**
  101539. * Helper function to create a SceneOptimizer with one single line of code
  101540. * @param scene defines the scene to work on
  101541. * @param options defines the options to use with the SceneOptimizer
  101542. * @param onSuccess defines a callback to call on success
  101543. * @param onFailure defines a callback to call on failure
  101544. * @returns the new SceneOptimizer object
  101545. */
  101546. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  101547. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  101548. if (onSuccess) {
  101549. optimizer.onSuccessObservable.add(function () {
  101550. onSuccess();
  101551. });
  101552. }
  101553. if (onFailure) {
  101554. optimizer.onFailureObservable.add(function () {
  101555. onFailure();
  101556. });
  101557. }
  101558. optimizer.start();
  101559. return optimizer;
  101560. };
  101561. return SceneOptimizer;
  101562. }());
  101563. BABYLON.SceneOptimizer = SceneOptimizer;
  101564. })(BABYLON || (BABYLON = {}));
  101565. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  101566. var BABYLON;
  101567. (function (BABYLON) {
  101568. /**
  101569. * Gets the outline renderer associated with the scene
  101570. * @returns a OutlineRenderer
  101571. */
  101572. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  101573. if (!this._outlineRenderer) {
  101574. this._outlineRenderer = new OutlineRenderer(this);
  101575. }
  101576. return this._outlineRenderer;
  101577. };
  101578. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  101579. get: function () {
  101580. return this._renderOutline;
  101581. },
  101582. set: function (value) {
  101583. if (value) {
  101584. // Lazy Load the component.
  101585. this.getScene().getOutlineRenderer();
  101586. }
  101587. this._renderOutline = value;
  101588. },
  101589. enumerable: true,
  101590. configurable: true
  101591. });
  101592. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  101593. get: function () {
  101594. return this._renderOverlay;
  101595. },
  101596. set: function (value) {
  101597. if (value) {
  101598. // Lazy Load the component.
  101599. this.getScene().getOutlineRenderer();
  101600. }
  101601. this._renderOverlay = value;
  101602. },
  101603. enumerable: true,
  101604. configurable: true
  101605. });
  101606. /**
  101607. * This class is responsible to draw bothe outline/overlay of meshes.
  101608. * It should not be used directly but through the available method on mesh.
  101609. */
  101610. var OutlineRenderer = /** @class */ (function () {
  101611. /**
  101612. * Instantiates a new outline renderer. (There could be only one per scene).
  101613. * @param scene Defines the scene it belongs to
  101614. */
  101615. function OutlineRenderer(scene) {
  101616. /**
  101617. * The name of the component. Each component must have a unique name.
  101618. */
  101619. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  101620. /**
  101621. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  101622. */
  101623. this.zOffset = 1;
  101624. this.scene = scene;
  101625. this._engine = scene.getEngine();
  101626. this.scene._addComponent(this);
  101627. }
  101628. /**
  101629. * Register the component to one instance of a scene.
  101630. */
  101631. OutlineRenderer.prototype.register = function () {
  101632. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  101633. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  101634. };
  101635. /**
  101636. * Rebuilds the elements related to this component in case of
  101637. * context lost for instance.
  101638. */
  101639. OutlineRenderer.prototype.rebuild = function () {
  101640. // Nothing to do here.
  101641. };
  101642. /**
  101643. * Disposes the component and the associated ressources.
  101644. */
  101645. OutlineRenderer.prototype.dispose = function () {
  101646. // Nothing to do here.
  101647. };
  101648. /**
  101649. * Renders the outline in the canvas.
  101650. * @param subMesh Defines the sumesh to render
  101651. * @param batch Defines the batch of meshes in case of instances
  101652. * @param useOverlay Defines if the rendering is for the overlay or the outline
  101653. */
  101654. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  101655. var _this = this;
  101656. if (useOverlay === void 0) { useOverlay = false; }
  101657. var scene = this.scene;
  101658. var engine = scene.getEngine();
  101659. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  101660. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  101661. return;
  101662. }
  101663. var mesh = subMesh.getRenderingMesh();
  101664. var material = subMesh.getMaterial();
  101665. if (!material || !scene.activeCamera) {
  101666. return;
  101667. }
  101668. engine.enableEffect(this._effect);
  101669. // Logarithmic depth
  101670. if (material.useLogarithmicDepth) {
  101671. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  101672. }
  101673. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  101674. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  101675. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  101676. // Bones
  101677. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  101678. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  101679. }
  101680. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  101681. // Alpha test
  101682. if (material && material.needAlphaTesting()) {
  101683. var alphaTexture = material.getAlphaTestTexture();
  101684. if (alphaTexture) {
  101685. this._effect.setTexture("diffuseSampler", alphaTexture);
  101686. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  101687. }
  101688. }
  101689. engine.setZOffset(-this.zOffset);
  101690. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  101691. engine.setZOffset(0);
  101692. };
  101693. /**
  101694. * Returns whether or not the outline renderer is ready for a given submesh.
  101695. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  101696. * @param subMesh Defines the submesh to check readyness for
  101697. * @param useInstances Defines wheter wee are trying to render instances or not
  101698. * @returns true if ready otherwise false
  101699. */
  101700. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  101701. var defines = [];
  101702. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  101703. var mesh = subMesh.getMesh();
  101704. var material = subMesh.getMaterial();
  101705. if (material) {
  101706. // Alpha test
  101707. if (material.needAlphaTesting()) {
  101708. defines.push("#define ALPHATEST");
  101709. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101710. attribs.push(BABYLON.VertexBuffer.UVKind);
  101711. defines.push("#define UV1");
  101712. }
  101713. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  101714. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101715. defines.push("#define UV2");
  101716. }
  101717. }
  101718. //Logarithmic depth
  101719. if (material.useLogarithmicDepth) {
  101720. defines.push("#define LOGARITHMICDEPTH");
  101721. }
  101722. }
  101723. // Bones
  101724. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  101725. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  101726. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  101727. if (mesh.numBoneInfluencers > 4) {
  101728. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  101729. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  101730. }
  101731. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  101732. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  101733. }
  101734. else {
  101735. defines.push("#define NUM_BONE_INFLUENCERS 0");
  101736. }
  101737. // Instances
  101738. if (useInstances) {
  101739. defines.push("#define INSTANCES");
  101740. attribs.push("world0");
  101741. attribs.push("world1");
  101742. attribs.push("world2");
  101743. attribs.push("world3");
  101744. }
  101745. // Get correct effect
  101746. var join = defines.join("\n");
  101747. if (this._cachedDefines !== join) {
  101748. this._cachedDefines = join;
  101749. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  101750. }
  101751. return this._effect.isReady();
  101752. };
  101753. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  101754. // Outline - step 1
  101755. this._savedDepthWrite = this._engine.getDepthWrite();
  101756. if (mesh.renderOutline) {
  101757. this._engine.setDepthWrite(false);
  101758. this.render(subMesh, batch);
  101759. this._engine.setDepthWrite(this._savedDepthWrite);
  101760. }
  101761. };
  101762. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  101763. // Outline - step 2
  101764. if (mesh.renderOutline && this._savedDepthWrite) {
  101765. this._engine.setDepthWrite(true);
  101766. this._engine.setColorWrite(false);
  101767. this.render(subMesh, batch);
  101768. this._engine.setColorWrite(true);
  101769. }
  101770. // Overlay
  101771. if (mesh.renderOverlay) {
  101772. var currentMode = this._engine.getAlphaMode();
  101773. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  101774. this.render(subMesh, batch, true);
  101775. this._engine.setAlphaMode(currentMode);
  101776. }
  101777. };
  101778. return OutlineRenderer;
  101779. }());
  101780. BABYLON.OutlineRenderer = OutlineRenderer;
  101781. })(BABYLON || (BABYLON = {}));
  101782. //# sourceMappingURL=babylon.outlineRenderer.js.map
  101783. var BABYLON;
  101784. (function (BABYLON) {
  101785. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  101786. if (this._edgesRenderer) {
  101787. this._edgesRenderer.dispose();
  101788. this._edgesRenderer = null;
  101789. }
  101790. return this;
  101791. };
  101792. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  101793. if (epsilon === void 0) { epsilon = 0.95; }
  101794. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101795. this.disableEdgesRendering();
  101796. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  101797. return this;
  101798. };
  101799. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  101800. get: function () {
  101801. return this._edgesRenderer;
  101802. },
  101803. enumerable: true,
  101804. configurable: true
  101805. });
  101806. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  101807. if (epsilon === void 0) { epsilon = 0.95; }
  101808. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101809. this.disableEdgesRendering();
  101810. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  101811. return this;
  101812. };
  101813. /**
  101814. * FaceAdjacencies Helper class to generate edges
  101815. */
  101816. var FaceAdjacencies = /** @class */ (function () {
  101817. function FaceAdjacencies() {
  101818. this.edges = new Array();
  101819. this.edgesConnectedCount = 0;
  101820. }
  101821. return FaceAdjacencies;
  101822. }());
  101823. /**
  101824. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  101825. */
  101826. var EdgesRenderer = /** @class */ (function () {
  101827. /**
  101828. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  101829. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  101830. * @param source Mesh used to create edges
  101831. * @param epsilon sum of angles in adjacency to check for edge
  101832. * @param checkVerticesInsteadOfIndices
  101833. * @param generateEdgesLines - should generate Lines or only prepare resources.
  101834. */
  101835. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  101836. if (epsilon === void 0) { epsilon = 0.95; }
  101837. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101838. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  101839. var _this = this;
  101840. this.edgesWidthScalerForOrthographic = 1000.0;
  101841. this.edgesWidthScalerForPerspective = 50.0;
  101842. this._linesPositions = new Array();
  101843. this._linesNormals = new Array();
  101844. this._linesIndices = new Array();
  101845. this._buffers = {};
  101846. this._checkVerticesInsteadOfIndices = false;
  101847. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  101848. this.isEnabled = true;
  101849. this._source = source;
  101850. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  101851. this._epsilon = epsilon;
  101852. this._prepareRessources();
  101853. if (generateEdgesLines) {
  101854. this._generateEdgesLines();
  101855. }
  101856. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  101857. _this._rebuild();
  101858. });
  101859. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  101860. _this.dispose();
  101861. });
  101862. }
  101863. EdgesRenderer.prototype._prepareRessources = function () {
  101864. if (this._lineShader) {
  101865. return;
  101866. }
  101867. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  101868. attributes: ["position", "normal"],
  101869. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  101870. });
  101871. this._lineShader.disableDepthWrite = true;
  101872. this._lineShader.backFaceCulling = false;
  101873. };
  101874. /** @hidden */
  101875. EdgesRenderer.prototype._rebuild = function () {
  101876. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101877. if (buffer) {
  101878. buffer._rebuild();
  101879. }
  101880. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101881. if (buffer) {
  101882. buffer._rebuild();
  101883. }
  101884. var scene = this._source.getScene();
  101885. var engine = scene.getEngine();
  101886. this._ib = engine.createIndexBuffer(this._linesIndices);
  101887. };
  101888. /**
  101889. * Releases the required resources for the edges renderer
  101890. */
  101891. EdgesRenderer.prototype.dispose = function () {
  101892. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  101893. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  101894. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101895. if (buffer) {
  101896. buffer.dispose();
  101897. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  101898. }
  101899. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101900. if (buffer) {
  101901. buffer.dispose();
  101902. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  101903. }
  101904. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  101905. this._lineShader.dispose();
  101906. };
  101907. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  101908. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  101909. return 0;
  101910. }
  101911. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  101912. return 1;
  101913. }
  101914. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  101915. return 2;
  101916. }
  101917. return -1;
  101918. };
  101919. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  101920. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  101921. return 0;
  101922. }
  101923. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  101924. return 1;
  101925. }
  101926. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  101927. return 2;
  101928. }
  101929. return -1;
  101930. };
  101931. /**
  101932. * Checks if the pair of p0 and p1 is en edge
  101933. * @param faceIndex
  101934. * @param edge
  101935. * @param faceNormals
  101936. * @param p0
  101937. * @param p1
  101938. * @private
  101939. */
  101940. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101941. var needToCreateLine;
  101942. if (edge === undefined) {
  101943. needToCreateLine = true;
  101944. }
  101945. else {
  101946. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  101947. needToCreateLine = dotProduct < this._epsilon;
  101948. }
  101949. if (needToCreateLine) {
  101950. var offset = this._linesPositions.length / 3;
  101951. var normal = p0.subtract(p1);
  101952. normal.normalize();
  101953. // Positions
  101954. this._linesPositions.push(p0.x);
  101955. this._linesPositions.push(p0.y);
  101956. this._linesPositions.push(p0.z);
  101957. this._linesPositions.push(p0.x);
  101958. this._linesPositions.push(p0.y);
  101959. this._linesPositions.push(p0.z);
  101960. this._linesPositions.push(p1.x);
  101961. this._linesPositions.push(p1.y);
  101962. this._linesPositions.push(p1.z);
  101963. this._linesPositions.push(p1.x);
  101964. this._linesPositions.push(p1.y);
  101965. this._linesPositions.push(p1.z);
  101966. // Normals
  101967. this._linesNormals.push(p1.x);
  101968. this._linesNormals.push(p1.y);
  101969. this._linesNormals.push(p1.z);
  101970. this._linesNormals.push(-1);
  101971. this._linesNormals.push(p1.x);
  101972. this._linesNormals.push(p1.y);
  101973. this._linesNormals.push(p1.z);
  101974. this._linesNormals.push(1);
  101975. this._linesNormals.push(p0.x);
  101976. this._linesNormals.push(p0.y);
  101977. this._linesNormals.push(p0.z);
  101978. this._linesNormals.push(-1);
  101979. this._linesNormals.push(p0.x);
  101980. this._linesNormals.push(p0.y);
  101981. this._linesNormals.push(p0.z);
  101982. this._linesNormals.push(1);
  101983. // Indices
  101984. this._linesIndices.push(offset);
  101985. this._linesIndices.push(offset + 1);
  101986. this._linesIndices.push(offset + 2);
  101987. this._linesIndices.push(offset);
  101988. this._linesIndices.push(offset + 2);
  101989. this._linesIndices.push(offset + 3);
  101990. }
  101991. };
  101992. /**
  101993. * Generates lines edges from adjacencjes
  101994. * @private
  101995. */
  101996. EdgesRenderer.prototype._generateEdgesLines = function () {
  101997. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101998. var indices = this._source.getIndices();
  101999. if (!indices || !positions) {
  102000. return;
  102001. }
  102002. // First let's find adjacencies
  102003. var adjacencies = new Array();
  102004. var faceNormals = new Array();
  102005. var index;
  102006. var faceAdjacencies;
  102007. // Prepare faces
  102008. for (index = 0; index < indices.length; index += 3) {
  102009. faceAdjacencies = new FaceAdjacencies();
  102010. var p0Index = indices[index];
  102011. var p1Index = indices[index + 1];
  102012. var p2Index = indices[index + 2];
  102013. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  102014. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  102015. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  102016. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  102017. faceNormal.normalize();
  102018. faceNormals.push(faceNormal);
  102019. adjacencies.push(faceAdjacencies);
  102020. }
  102021. // Scan
  102022. for (index = 0; index < adjacencies.length; index++) {
  102023. faceAdjacencies = adjacencies[index];
  102024. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  102025. var otherFaceAdjacencies = adjacencies[otherIndex];
  102026. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  102027. break;
  102028. }
  102029. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  102030. continue;
  102031. }
  102032. var otherP0 = indices[otherIndex * 3];
  102033. var otherP1 = indices[otherIndex * 3 + 1];
  102034. var otherP2 = indices[otherIndex * 3 + 2];
  102035. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  102036. var otherEdgeIndex = 0;
  102037. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  102038. continue;
  102039. }
  102040. switch (edgeIndex) {
  102041. case 0:
  102042. if (this._checkVerticesInsteadOfIndices) {
  102043. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  102044. }
  102045. else {
  102046. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  102047. }
  102048. break;
  102049. case 1:
  102050. if (this._checkVerticesInsteadOfIndices) {
  102051. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  102052. }
  102053. else {
  102054. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  102055. }
  102056. break;
  102057. case 2:
  102058. if (this._checkVerticesInsteadOfIndices) {
  102059. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  102060. }
  102061. else {
  102062. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  102063. }
  102064. break;
  102065. }
  102066. if (otherEdgeIndex === -1) {
  102067. continue;
  102068. }
  102069. faceAdjacencies.edges[edgeIndex] = otherIndex;
  102070. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  102071. faceAdjacencies.edgesConnectedCount++;
  102072. otherFaceAdjacencies.edgesConnectedCount++;
  102073. if (faceAdjacencies.edgesConnectedCount === 3) {
  102074. break;
  102075. }
  102076. }
  102077. }
  102078. }
  102079. // Create lines
  102080. for (index = 0; index < adjacencies.length; index++) {
  102081. // 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
  102082. var current = adjacencies[index];
  102083. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  102084. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  102085. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  102086. }
  102087. // Merge into a single mesh
  102088. var engine = this._source.getScene().getEngine();
  102089. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  102090. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  102091. this._ib = engine.createIndexBuffer(this._linesIndices);
  102092. this._indicesCount = this._linesIndices.length;
  102093. };
  102094. /**
  102095. * Checks wether or not the edges renderer is ready to render.
  102096. * @return true if ready, otherwise false.
  102097. */
  102098. EdgesRenderer.prototype.isReady = function () {
  102099. return this._lineShader.isReady();
  102100. };
  102101. /**
  102102. * Renders the edges of the attached mesh,
  102103. */
  102104. EdgesRenderer.prototype.render = function () {
  102105. var scene = this._source.getScene();
  102106. if (!this.isReady() || !scene.activeCamera) {
  102107. return;
  102108. }
  102109. var engine = scene.getEngine();
  102110. this._lineShader._preBind();
  102111. if (this._source.edgesColor.a !== 1) {
  102112. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  102113. }
  102114. else {
  102115. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  102116. }
  102117. // VBOs
  102118. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  102119. scene.resetCachedMaterial();
  102120. this._lineShader.setColor4("color", this._source.edgesColor);
  102121. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  102122. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  102123. }
  102124. else {
  102125. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  102126. }
  102127. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  102128. this._lineShader.bind(this._source.getWorldMatrix());
  102129. // Draw order
  102130. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  102131. this._lineShader.unbind();
  102132. };
  102133. return EdgesRenderer;
  102134. }());
  102135. BABYLON.EdgesRenderer = EdgesRenderer;
  102136. })(BABYLON || (BABYLON = {}));
  102137. //# sourceMappingURL=babylon.edgesRenderer.js.map
  102138. var BABYLON;
  102139. (function (BABYLON) {
  102140. /**
  102141. * FaceAdjacencies Helper class to generate edges
  102142. */
  102143. var FaceAdjacencies = /** @class */ (function () {
  102144. function FaceAdjacencies() {
  102145. this.edges = new Array();
  102146. this.edgesConnectedCount = 0;
  102147. }
  102148. return FaceAdjacencies;
  102149. }());
  102150. /**
  102151. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  102152. */
  102153. var LineEdgesRenderer = /** @class */ (function (_super) {
  102154. __extends(LineEdgesRenderer, _super);
  102155. /**
  102156. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  102157. * @param source LineMesh used to generate edges
  102158. * @param epsilon not important (specified angle for edge detection)
  102159. * @param checkVerticesInsteadOfIndices not important for LineMesh
  102160. */
  102161. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  102162. if (epsilon === void 0) { epsilon = 0.95; }
  102163. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  102164. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  102165. _this._generateEdgesLines();
  102166. return _this;
  102167. }
  102168. /**
  102169. * Always create the edge since its a line so only important things are p0 and p1
  102170. * @param faceIndex not important for LineMesh
  102171. * @param edge not important for LineMesh
  102172. * @param faceNormals not important for LineMesh
  102173. * @param p0 beginnig of line
  102174. * @param p1 end of line
  102175. */
  102176. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  102177. var offset = this._linesPositions.length / 3;
  102178. var normal = p0.subtract(p1);
  102179. normal.normalize();
  102180. // Positions
  102181. this._linesPositions.push(p0.x);
  102182. this._linesPositions.push(p0.y);
  102183. this._linesPositions.push(p0.z);
  102184. this._linesPositions.push(p0.x);
  102185. this._linesPositions.push(p0.y);
  102186. this._linesPositions.push(p0.z);
  102187. this._linesPositions.push(p1.x);
  102188. this._linesPositions.push(p1.y);
  102189. this._linesPositions.push(p1.z);
  102190. this._linesPositions.push(p1.x);
  102191. this._linesPositions.push(p1.y);
  102192. this._linesPositions.push(p1.z);
  102193. // Normals
  102194. this._linesNormals.push(p1.x);
  102195. this._linesNormals.push(p1.y);
  102196. this._linesNormals.push(p1.z);
  102197. this._linesNormals.push(-1);
  102198. this._linesNormals.push(p1.x);
  102199. this._linesNormals.push(p1.y);
  102200. this._linesNormals.push(p1.z);
  102201. this._linesNormals.push(1);
  102202. this._linesNormals.push(p0.x);
  102203. this._linesNormals.push(p0.y);
  102204. this._linesNormals.push(p0.z);
  102205. this._linesNormals.push(-1);
  102206. this._linesNormals.push(p0.x);
  102207. this._linesNormals.push(p0.y);
  102208. this._linesNormals.push(p0.z);
  102209. this._linesNormals.push(1);
  102210. // Indices
  102211. this._linesIndices.push(offset);
  102212. this._linesIndices.push(offset + 1);
  102213. this._linesIndices.push(offset + 2);
  102214. this._linesIndices.push(offset);
  102215. this._linesIndices.push(offset + 2);
  102216. this._linesIndices.push(offset + 3);
  102217. };
  102218. /**
  102219. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  102220. */
  102221. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  102222. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  102223. var indices = this._source.getIndices();
  102224. if (!indices || !positions) {
  102225. return;
  102226. }
  102227. // First let's find adjacencies
  102228. var adjacencies = new Array();
  102229. var faceNormals = new Array();
  102230. var index;
  102231. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  102232. var currentAdjecancy = new FaceAdjacencies();
  102233. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  102234. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  102235. adjacencies.push(currentAdjecancy);
  102236. }
  102237. // Create lines
  102238. for (index = 0; index < adjacencies.length; index++) {
  102239. // 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
  102240. var current = adjacencies[index];
  102241. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  102242. }
  102243. // Merge into a single mesh
  102244. var engine = this._source.getScene().getEngine();
  102245. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  102246. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  102247. this._ib = engine.createIndexBuffer(this._linesIndices);
  102248. this._indicesCount = this._linesIndices.length;
  102249. };
  102250. return LineEdgesRenderer;
  102251. }(BABYLON.EdgesRenderer));
  102252. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  102253. })(BABYLON || (BABYLON = {}));
  102254. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  102255. var BABYLON;
  102256. (function (BABYLON) {
  102257. // Adds the parser to the scene parsers.
  102258. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  102259. if (parsedData.effectLayers) {
  102260. if (!container.effectLayers) {
  102261. container.effectLayers = new Array();
  102262. }
  102263. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  102264. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  102265. container.effectLayers.push(effectLayer);
  102266. }
  102267. }
  102268. });
  102269. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  102270. var index = this.effectLayers.indexOf(toRemove);
  102271. if (index !== -1) {
  102272. this.effectLayers.splice(index, 1);
  102273. }
  102274. return index;
  102275. };
  102276. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  102277. this.effectLayers.push(newEffectLayer);
  102278. };
  102279. /**
  102280. * Defines the layer scene component responsible to manage any effect layers
  102281. * in a given scene.
  102282. */
  102283. var EffectLayerSceneComponent = /** @class */ (function () {
  102284. /**
  102285. * Creates a new instance of the component for the given scene
  102286. * @param scene Defines the scene to register the component in
  102287. */
  102288. function EffectLayerSceneComponent(scene) {
  102289. /**
  102290. * The component name helpfull to identify the component in the list of scene components.
  102291. */
  102292. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  102293. this._renderEffects = false;
  102294. this._needStencil = false;
  102295. this._previousStencilState = false;
  102296. this.scene = scene;
  102297. this._engine = scene.getEngine();
  102298. scene.effectLayers = new Array();
  102299. }
  102300. /**
  102301. * Registers the component in a given scene
  102302. */
  102303. EffectLayerSceneComponent.prototype.register = function () {
  102304. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  102305. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  102306. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  102307. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  102308. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  102309. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  102310. };
  102311. /**
  102312. * Rebuilds the elements related to this component in case of
  102313. * context lost for instance.
  102314. */
  102315. EffectLayerSceneComponent.prototype.rebuild = function () {
  102316. var layers = this.scene.effectLayers;
  102317. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  102318. var effectLayer = layers_1[_i];
  102319. effectLayer._rebuild();
  102320. }
  102321. };
  102322. /**
  102323. * Serializes the component data to the specified json object
  102324. * @param serializationObject The object to serialize to
  102325. */
  102326. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  102327. // Effect layers
  102328. serializationObject.effectLayers = [];
  102329. var layers = this.scene.effectLayers;
  102330. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  102331. var effectLayer = layers_2[_i];
  102332. if (effectLayer.serialize) {
  102333. serializationObject.effectLayers.push(effectLayer.serialize());
  102334. }
  102335. }
  102336. };
  102337. /**
  102338. * Adds all the element from the container to the scene
  102339. * @param container the container holding the elements
  102340. */
  102341. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  102342. var _this = this;
  102343. if (!container.effectLayers) {
  102344. return;
  102345. }
  102346. container.effectLayers.forEach(function (o) {
  102347. _this.scene.addEffectLayer(o);
  102348. });
  102349. };
  102350. /**
  102351. * Removes all the elements in the container from the scene
  102352. * @param container contains the elements to remove
  102353. */
  102354. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  102355. var _this = this;
  102356. if (!container.effectLayers) {
  102357. return;
  102358. }
  102359. container.effectLayers.forEach(function (o) {
  102360. _this.scene.removeEffectLayer(o);
  102361. });
  102362. };
  102363. /**
  102364. * Disposes the component and the associated ressources.
  102365. */
  102366. EffectLayerSceneComponent.prototype.dispose = function () {
  102367. var layers = this.scene.effectLayers;
  102368. while (layers.length) {
  102369. layers[0].dispose();
  102370. }
  102371. };
  102372. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  102373. var layers = this.scene.effectLayers;
  102374. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  102375. var layer = layers_3[_i];
  102376. if (!layer.hasMesh(mesh)) {
  102377. continue;
  102378. }
  102379. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  102380. var subMesh = _b[_a];
  102381. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  102382. return false;
  102383. }
  102384. }
  102385. }
  102386. return true;
  102387. };
  102388. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  102389. this._renderEffects = false;
  102390. this._needStencil = false;
  102391. var layers = this.scene.effectLayers;
  102392. if (layers && layers.length > 0) {
  102393. this._previousStencilState = this._engine.getStencilBuffer();
  102394. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  102395. var effectLayer = layers_4[_i];
  102396. if (effectLayer.shouldRender() &&
  102397. (!effectLayer.camera ||
  102398. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  102399. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  102400. this._renderEffects = true;
  102401. this._needStencil = this._needStencil || effectLayer.needStencil();
  102402. var renderTarget = effectLayer._mainTexture;
  102403. if (renderTarget._shouldRender()) {
  102404. this.scene.incrementRenderId();
  102405. renderTarget.render(false, false);
  102406. }
  102407. }
  102408. }
  102409. this.scene.incrementRenderId();
  102410. }
  102411. };
  102412. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  102413. // Activate effect Layer stencil
  102414. if (this._needStencil) {
  102415. this._engine.setStencilBuffer(true);
  102416. }
  102417. };
  102418. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  102419. // Restore effect Layer stencil
  102420. if (this._needStencil) {
  102421. this._engine.setStencilBuffer(this._previousStencilState);
  102422. }
  102423. };
  102424. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  102425. if (this._renderEffects) {
  102426. this._engine.setDepthBuffer(false);
  102427. var layers = this.scene.effectLayers;
  102428. for (var i = 0; i < layers.length; i++) {
  102429. var effectLayer = layers[i];
  102430. if (effectLayer.renderingGroupId === renderingGroupId) {
  102431. if (effectLayer.shouldRender()) {
  102432. effectLayer.render();
  102433. }
  102434. }
  102435. }
  102436. this._engine.setDepthBuffer(true);
  102437. }
  102438. };
  102439. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  102440. if (this._renderEffects) {
  102441. this._draw(-1);
  102442. }
  102443. };
  102444. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  102445. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  102446. this._draw(index);
  102447. }
  102448. };
  102449. return EffectLayerSceneComponent;
  102450. }());
  102451. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  102452. })(BABYLON || (BABYLON = {}));
  102453. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  102454. var __assign = (this && this.__assign) || function () {
  102455. __assign = Object.assign || function(t) {
  102456. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102457. s = arguments[i];
  102458. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102459. t[p] = s[p];
  102460. }
  102461. return t;
  102462. };
  102463. return __assign.apply(this, arguments);
  102464. };
  102465. var BABYLON;
  102466. (function (BABYLON) {
  102467. /**
  102468. * The effect layer Helps adding post process effect blended with the main pass.
  102469. *
  102470. * This can be for instance use to generate glow or higlight effects on the scene.
  102471. *
  102472. * The effect layer class can not be used directly and is intented to inherited from to be
  102473. * customized per effects.
  102474. */
  102475. var EffectLayer = /** @class */ (function () {
  102476. /**
  102477. * Instantiates a new effect Layer and references it in the scene.
  102478. * @param name The name of the layer
  102479. * @param scene The scene to use the layer in
  102480. */
  102481. function EffectLayer(
  102482. /** The Friendly of the effect in the scene */
  102483. name, scene) {
  102484. this._vertexBuffers = {};
  102485. this._maxSize = 0;
  102486. this._mainTextureDesiredSize = { width: 0, height: 0 };
  102487. this._shouldRender = true;
  102488. this._postProcesses = [];
  102489. this._textures = [];
  102490. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  102491. /**
  102492. * The clear color of the texture used to generate the glow map.
  102493. */
  102494. this.neutralColor = new BABYLON.Color4();
  102495. /**
  102496. * Specifies wether the highlight layer is enabled or not.
  102497. */
  102498. this.isEnabled = true;
  102499. /**
  102500. * An event triggered when the effect layer has been disposed.
  102501. */
  102502. this.onDisposeObservable = new BABYLON.Observable();
  102503. /**
  102504. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  102505. */
  102506. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  102507. /**
  102508. * An event triggered when the generated texture is being merged in the scene.
  102509. */
  102510. this.onBeforeComposeObservable = new BABYLON.Observable();
  102511. /**
  102512. * An event triggered when the generated texture has been merged in the scene.
  102513. */
  102514. this.onAfterComposeObservable = new BABYLON.Observable();
  102515. /**
  102516. * An event triggered when the efffect layer changes its size.
  102517. */
  102518. this.onSizeChangedObservable = new BABYLON.Observable();
  102519. this.name = name;
  102520. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  102521. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  102522. if (!component) {
  102523. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  102524. this._scene._addComponent(component);
  102525. }
  102526. this._engine = this._scene.getEngine();
  102527. this._maxSize = this._engine.getCaps().maxTextureSize;
  102528. this._scene.effectLayers.push(this);
  102529. // Generate Buffers
  102530. this._generateIndexBuffer();
  102531. this._genrateVertexBuffer();
  102532. }
  102533. Object.defineProperty(EffectLayer.prototype, "camera", {
  102534. /**
  102535. * Gets the camera attached to the layer.
  102536. */
  102537. get: function () {
  102538. return this._effectLayerOptions.camera;
  102539. },
  102540. enumerable: true,
  102541. configurable: true
  102542. });
  102543. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  102544. /**
  102545. * Gets the rendering group id the layer should render in.
  102546. */
  102547. get: function () {
  102548. return this._effectLayerOptions.renderingGroupId;
  102549. },
  102550. enumerable: true,
  102551. configurable: true
  102552. });
  102553. /**
  102554. * Initializes the effect layer with the required options.
  102555. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  102556. */
  102557. EffectLayer.prototype._init = function (options) {
  102558. // Adapt options
  102559. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  102560. this._setMainTextureSize();
  102561. this._createMainTexture();
  102562. this._createTextureAndPostProcesses();
  102563. this._mergeEffect = this._createMergeEffect();
  102564. };
  102565. /**
  102566. * Generates the index buffer of the full screen quad blending to the main canvas.
  102567. */
  102568. EffectLayer.prototype._generateIndexBuffer = function () {
  102569. // Indices
  102570. var indices = [];
  102571. indices.push(0);
  102572. indices.push(1);
  102573. indices.push(2);
  102574. indices.push(0);
  102575. indices.push(2);
  102576. indices.push(3);
  102577. this._indexBuffer = this._engine.createIndexBuffer(indices);
  102578. };
  102579. /**
  102580. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  102581. */
  102582. EffectLayer.prototype._genrateVertexBuffer = function () {
  102583. // VBO
  102584. var vertices = [];
  102585. vertices.push(1, 1);
  102586. vertices.push(-1, 1);
  102587. vertices.push(-1, -1);
  102588. vertices.push(1, -1);
  102589. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  102590. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  102591. };
  102592. /**
  102593. * Sets the main texture desired size which is the closest power of two
  102594. * of the engine canvas size.
  102595. */
  102596. EffectLayer.prototype._setMainTextureSize = function () {
  102597. if (this._effectLayerOptions.mainTextureFixedSize) {
  102598. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  102599. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  102600. }
  102601. else {
  102602. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  102603. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  102604. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  102605. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  102606. }
  102607. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  102608. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  102609. };
  102610. /**
  102611. * Creates the main texture for the effect layer.
  102612. */
  102613. EffectLayer.prototype._createMainTexture = function () {
  102614. var _this = this;
  102615. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  102616. width: this._mainTextureDesiredSize.width,
  102617. height: this._mainTextureDesiredSize.height
  102618. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  102619. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  102620. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102621. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102622. this._mainTexture.anisotropicFilteringLevel = 1;
  102623. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102624. this._mainTexture.renderParticles = false;
  102625. this._mainTexture.renderList = null;
  102626. this._mainTexture.ignoreCameraViewport = true;
  102627. // Custom render function
  102628. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  102629. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  102630. var index;
  102631. var engine = _this._scene.getEngine();
  102632. if (depthOnlySubMeshes.length) {
  102633. engine.setColorWrite(false);
  102634. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  102635. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  102636. }
  102637. engine.setColorWrite(true);
  102638. }
  102639. for (index = 0; index < opaqueSubMeshes.length; index++) {
  102640. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  102641. }
  102642. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  102643. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  102644. }
  102645. for (index = 0; index < transparentSubMeshes.length; index++) {
  102646. _this._renderSubMesh(transparentSubMeshes.data[index]);
  102647. }
  102648. };
  102649. this._mainTexture.onClearObservable.add(function (engine) {
  102650. engine.clear(_this.neutralColor, true, true, true);
  102651. });
  102652. };
  102653. /**
  102654. * Checks for the readiness of the element composing the layer.
  102655. * @param subMesh the mesh to check for
  102656. * @param useInstances specify wether or not to use instances to render the mesh
  102657. * @param emissiveTexture the associated emissive texture used to generate the glow
  102658. * @return true if ready otherwise, false
  102659. */
  102660. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  102661. var material = subMesh.getMaterial();
  102662. if (!material) {
  102663. return false;
  102664. }
  102665. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  102666. return false;
  102667. }
  102668. var defines = [];
  102669. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102670. var mesh = subMesh.getMesh();
  102671. var uv1 = false;
  102672. var uv2 = false;
  102673. // Alpha test
  102674. if (material && material.needAlphaTesting()) {
  102675. var alphaTexture = material.getAlphaTestTexture();
  102676. if (alphaTexture) {
  102677. defines.push("#define ALPHATEST");
  102678. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  102679. alphaTexture.coordinatesIndex === 1) {
  102680. defines.push("#define DIFFUSEUV2");
  102681. uv2 = true;
  102682. }
  102683. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  102684. defines.push("#define DIFFUSEUV1");
  102685. uv1 = true;
  102686. }
  102687. }
  102688. }
  102689. // Emissive
  102690. if (emissiveTexture) {
  102691. defines.push("#define EMISSIVE");
  102692. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  102693. emissiveTexture.coordinatesIndex === 1) {
  102694. defines.push("#define EMISSIVEUV2");
  102695. uv2 = true;
  102696. }
  102697. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  102698. defines.push("#define EMISSIVEUV1");
  102699. uv1 = true;
  102700. }
  102701. }
  102702. if (uv1) {
  102703. attribs.push(BABYLON.VertexBuffer.UVKind);
  102704. defines.push("#define UV1");
  102705. }
  102706. if (uv2) {
  102707. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102708. defines.push("#define UV2");
  102709. }
  102710. // Bones
  102711. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  102712. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  102713. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  102714. if (mesh.numBoneInfluencers > 4) {
  102715. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  102716. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  102717. }
  102718. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  102719. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  102720. }
  102721. else {
  102722. defines.push("#define NUM_BONE_INFLUENCERS 0");
  102723. }
  102724. // Morph targets
  102725. var manager = mesh.morphTargetManager;
  102726. var morphInfluencers = 0;
  102727. if (manager) {
  102728. if (manager.numInfluencers > 0) {
  102729. defines.push("#define MORPHTARGETS");
  102730. morphInfluencers = manager.numInfluencers;
  102731. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  102732. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  102733. }
  102734. }
  102735. // Instances
  102736. if (useInstances) {
  102737. defines.push("#define INSTANCES");
  102738. attribs.push("world0");
  102739. attribs.push("world1");
  102740. attribs.push("world2");
  102741. attribs.push("world3");
  102742. }
  102743. // Get correct effect
  102744. var join = defines.join("\n");
  102745. if (this._cachedDefines !== join) {
  102746. this._cachedDefines = join;
  102747. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  102748. }
  102749. return this._effectLayerMapGenerationEffect.isReady();
  102750. };
  102751. /**
  102752. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  102753. */
  102754. EffectLayer.prototype.render = function () {
  102755. var currentEffect = this._mergeEffect;
  102756. // Check
  102757. if (!currentEffect.isReady())
  102758. return;
  102759. for (var i = 0; i < this._postProcesses.length; i++) {
  102760. if (!this._postProcesses[i].isReady()) {
  102761. return;
  102762. }
  102763. }
  102764. var engine = this._scene.getEngine();
  102765. this.onBeforeComposeObservable.notifyObservers(this);
  102766. // Render
  102767. engine.enableEffect(currentEffect);
  102768. engine.setState(false);
  102769. // VBOs
  102770. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  102771. // Cache
  102772. var previousAlphaMode = engine.getAlphaMode();
  102773. // Go Blend.
  102774. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  102775. // Blends the map on the main canvas.
  102776. this._internalRender(currentEffect);
  102777. // Restore Alpha
  102778. engine.setAlphaMode(previousAlphaMode);
  102779. this.onAfterComposeObservable.notifyObservers(this);
  102780. // Handle size changes.
  102781. var size = this._mainTexture.getSize();
  102782. this._setMainTextureSize();
  102783. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  102784. // Recreate RTT and post processes on size change.
  102785. this.onSizeChangedObservable.notifyObservers(this);
  102786. this._disposeTextureAndPostProcesses();
  102787. this._createMainTexture();
  102788. this._createTextureAndPostProcesses();
  102789. }
  102790. };
  102791. /**
  102792. * Determine if a given mesh will be used in the current effect.
  102793. * @param mesh mesh to test
  102794. * @returns true if the mesh will be used
  102795. */
  102796. EffectLayer.prototype.hasMesh = function (mesh) {
  102797. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  102798. return true;
  102799. }
  102800. return false;
  102801. };
  102802. /**
  102803. * Returns true if the layer contains information to display, otherwise false.
  102804. * @returns true if the glow layer should be rendered
  102805. */
  102806. EffectLayer.prototype.shouldRender = function () {
  102807. return this.isEnabled && this._shouldRender;
  102808. };
  102809. /**
  102810. * Returns true if the mesh should render, otherwise false.
  102811. * @param mesh The mesh to render
  102812. * @returns true if it should render otherwise false
  102813. */
  102814. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  102815. return true;
  102816. };
  102817. /**
  102818. * Returns true if the mesh should render, otherwise false.
  102819. * @param mesh The mesh to render
  102820. * @returns true if it should render otherwise false
  102821. */
  102822. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  102823. return true;
  102824. };
  102825. /**
  102826. * Renders the submesh passed in parameter to the generation map.
  102827. */
  102828. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  102829. var _this = this;
  102830. if (!this.shouldRender()) {
  102831. return;
  102832. }
  102833. var material = subMesh.getMaterial();
  102834. var mesh = subMesh.getRenderingMesh();
  102835. var scene = this._scene;
  102836. var engine = scene.getEngine();
  102837. if (!material) {
  102838. return;
  102839. }
  102840. // Do not block in blend mode.
  102841. if (material.needAlphaBlendingForMesh(mesh)) {
  102842. return;
  102843. }
  102844. // Culling
  102845. engine.setState(material.backFaceCulling);
  102846. // Managing instances
  102847. var batch = mesh._getInstancesRenderList(subMesh._id);
  102848. if (batch.mustReturn) {
  102849. return;
  102850. }
  102851. // Early Exit per mesh
  102852. if (!this._shouldRenderMesh(mesh)) {
  102853. return;
  102854. }
  102855. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  102856. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  102857. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  102858. engine.enableEffect(this._effectLayerMapGenerationEffect);
  102859. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  102860. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  102861. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  102862. // Alpha test
  102863. if (material && material.needAlphaTesting()) {
  102864. var alphaTexture = material.getAlphaTestTexture();
  102865. if (alphaTexture) {
  102866. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  102867. var textureMatrix = alphaTexture.getTextureMatrix();
  102868. if (textureMatrix) {
  102869. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  102870. }
  102871. }
  102872. }
  102873. // Glow emissive only
  102874. if (this._emissiveTextureAndColor.texture) {
  102875. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  102876. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  102877. }
  102878. // Bones
  102879. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  102880. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  102881. }
  102882. // Morph targets
  102883. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  102884. // Draw
  102885. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  102886. }
  102887. else {
  102888. // Need to reset refresh rate of the main map
  102889. this._mainTexture.resetRefreshCounter();
  102890. }
  102891. };
  102892. /**
  102893. * Rebuild the required buffers.
  102894. * @hidden Internal use only.
  102895. */
  102896. EffectLayer.prototype._rebuild = function () {
  102897. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102898. if (vb) {
  102899. vb._rebuild();
  102900. }
  102901. this._generateIndexBuffer();
  102902. };
  102903. /**
  102904. * Dispose only the render target textures and post process.
  102905. */
  102906. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  102907. this._mainTexture.dispose();
  102908. for (var i = 0; i < this._postProcesses.length; i++) {
  102909. if (this._postProcesses[i]) {
  102910. this._postProcesses[i].dispose();
  102911. }
  102912. }
  102913. this._postProcesses = [];
  102914. for (var i = 0; i < this._textures.length; i++) {
  102915. if (this._textures[i]) {
  102916. this._textures[i].dispose();
  102917. }
  102918. }
  102919. this._textures = [];
  102920. };
  102921. /**
  102922. * Dispose the highlight layer and free resources.
  102923. */
  102924. EffectLayer.prototype.dispose = function () {
  102925. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102926. if (vertexBuffer) {
  102927. vertexBuffer.dispose();
  102928. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  102929. }
  102930. if (this._indexBuffer) {
  102931. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  102932. this._indexBuffer = null;
  102933. }
  102934. // Clean textures and post processes
  102935. this._disposeTextureAndPostProcesses();
  102936. // Remove from scene
  102937. var index = this._scene.effectLayers.indexOf(this, 0);
  102938. if (index > -1) {
  102939. this._scene.effectLayers.splice(index, 1);
  102940. }
  102941. // Callback
  102942. this.onDisposeObservable.notifyObservers(this);
  102943. this.onDisposeObservable.clear();
  102944. this.onBeforeRenderMainTextureObservable.clear();
  102945. this.onBeforeComposeObservable.clear();
  102946. this.onAfterComposeObservable.clear();
  102947. this.onSizeChangedObservable.clear();
  102948. };
  102949. /**
  102950. * Gets the class name of the effect layer
  102951. * @returns the string with the class name of the effect layer
  102952. */
  102953. EffectLayer.prototype.getClassName = function () {
  102954. return "EffectLayer";
  102955. };
  102956. /**
  102957. * Creates an effect layer from parsed effect layer data
  102958. * @param parsedEffectLayer defines effect layer data
  102959. * @param scene defines the current scene
  102960. * @param rootUrl defines the root URL containing the effect layer information
  102961. * @returns a parsed effect Layer
  102962. */
  102963. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  102964. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  102965. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  102966. };
  102967. __decorate([
  102968. BABYLON.serialize()
  102969. ], EffectLayer.prototype, "name", void 0);
  102970. __decorate([
  102971. BABYLON.serializeAsColor4()
  102972. ], EffectLayer.prototype, "neutralColor", void 0);
  102973. __decorate([
  102974. BABYLON.serialize()
  102975. ], EffectLayer.prototype, "isEnabled", void 0);
  102976. __decorate([
  102977. BABYLON.serializeAsCameraReference()
  102978. ], EffectLayer.prototype, "camera", null);
  102979. __decorate([
  102980. BABYLON.serialize()
  102981. ], EffectLayer.prototype, "renderingGroupId", null);
  102982. return EffectLayer;
  102983. }());
  102984. BABYLON.EffectLayer = EffectLayer;
  102985. })(BABYLON || (BABYLON = {}));
  102986. //# sourceMappingURL=babylon.effectLayer.js.map
  102987. var BABYLON;
  102988. (function (BABYLON) {
  102989. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  102990. for (var index = 0; index < this.effectLayers.length; index++) {
  102991. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  102992. return this.effectLayers[index];
  102993. }
  102994. }
  102995. return null;
  102996. };
  102997. /**
  102998. * Special Glow Blur post process only blurring the alpha channel
  102999. * It enforces keeping the most luminous color in the color channel.
  103000. */
  103001. var GlowBlurPostProcess = /** @class */ (function (_super) {
  103002. __extends(GlowBlurPostProcess, _super);
  103003. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  103004. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  103005. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  103006. _this.direction = direction;
  103007. _this.kernel = kernel;
  103008. _this.onApplyObservable.add(function (effect) {
  103009. effect.setFloat2("screenSize", _this.width, _this.height);
  103010. effect.setVector2("direction", _this.direction);
  103011. effect.setFloat("blurWidth", _this.kernel);
  103012. });
  103013. return _this;
  103014. }
  103015. return GlowBlurPostProcess;
  103016. }(BABYLON.PostProcess));
  103017. /**
  103018. * The highlight layer Helps adding a glow effect around a mesh.
  103019. *
  103020. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  103021. * glowy meshes to your scene.
  103022. *
  103023. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  103024. */
  103025. var HighlightLayer = /** @class */ (function (_super) {
  103026. __extends(HighlightLayer, _super);
  103027. /**
  103028. * Instantiates a new highlight Layer and references it to the scene..
  103029. * @param name The name of the layer
  103030. * @param scene The scene to use the layer in
  103031. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  103032. */
  103033. function HighlightLayer(name, scene, options) {
  103034. var _this = _super.call(this, name, scene) || this;
  103035. _this.name = name;
  103036. /**
  103037. * Specifies whether or not the inner glow is ACTIVE in the layer.
  103038. */
  103039. _this.innerGlow = true;
  103040. /**
  103041. * Specifies whether or not the outer glow is ACTIVE in the layer.
  103042. */
  103043. _this.outerGlow = true;
  103044. /**
  103045. * An event triggered when the highlight layer is being blurred.
  103046. */
  103047. _this.onBeforeBlurObservable = new BABYLON.Observable();
  103048. /**
  103049. * An event triggered when the highlight layer has been blurred.
  103050. */
  103051. _this.onAfterBlurObservable = new BABYLON.Observable();
  103052. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  103053. _this._meshes = {};
  103054. _this._excludedMeshes = {};
  103055. _this.neutralColor = HighlightLayer.NeutralColor;
  103056. // Warn on stencil
  103057. if (!_this._engine.isStencilEnable) {
  103058. 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 }");
  103059. }
  103060. // Adapt options
  103061. _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);
  103062. // Initialize the layer
  103063. _this._init({
  103064. alphaBlendingMode: _this._options.alphaBlendingMode,
  103065. camera: _this._options.camera,
  103066. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  103067. mainTextureRatio: _this._options.mainTextureRatio,
  103068. renderingGroupId: _this._options.renderingGroupId
  103069. });
  103070. // Do not render as long as no meshes have been added
  103071. _this._shouldRender = false;
  103072. return _this;
  103073. }
  103074. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  103075. /**
  103076. * Gets the horizontal size of the blur.
  103077. */
  103078. get: function () {
  103079. return this._horizontalBlurPostprocess.kernel;
  103080. },
  103081. /**
  103082. * Specifies the horizontal size of the blur.
  103083. */
  103084. set: function (value) {
  103085. this._horizontalBlurPostprocess.kernel = value;
  103086. },
  103087. enumerable: true,
  103088. configurable: true
  103089. });
  103090. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  103091. /**
  103092. * Gets the vertical size of the blur.
  103093. */
  103094. get: function () {
  103095. return this._verticalBlurPostprocess.kernel;
  103096. },
  103097. /**
  103098. * Specifies the vertical size of the blur.
  103099. */
  103100. set: function (value) {
  103101. this._verticalBlurPostprocess.kernel = value;
  103102. },
  103103. enumerable: true,
  103104. configurable: true
  103105. });
  103106. /**
  103107. * Get the effect name of the layer.
  103108. * @return The effect name
  103109. */
  103110. HighlightLayer.prototype.getEffectName = function () {
  103111. return HighlightLayer.EffectName;
  103112. };
  103113. /**
  103114. * Create the merge effect. This is the shader use to blit the information back
  103115. * to the main canvas at the end of the scene rendering.
  103116. */
  103117. HighlightLayer.prototype._createMergeEffect = function () {
  103118. // Effect
  103119. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  103120. };
  103121. /**
  103122. * Creates the render target textures and post processes used in the highlight layer.
  103123. */
  103124. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  103125. var _this = this;
  103126. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  103127. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  103128. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  103129. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  103130. var textureType = 0;
  103131. if (this._engine.getCaps().textureHalfFloatRender) {
  103132. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  103133. }
  103134. else {
  103135. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  103136. }
  103137. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  103138. width: blurTextureWidth,
  103139. height: blurTextureHeight
  103140. }, this._scene, false, true, textureType);
  103141. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103142. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103143. this._blurTexture.anisotropicFilteringLevel = 16;
  103144. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  103145. this._blurTexture.renderParticles = false;
  103146. this._blurTexture.ignoreCameraViewport = true;
  103147. this._textures = [this._blurTexture];
  103148. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  103149. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  103150. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  103151. effect.setTexture("textureSampler", _this._mainTexture);
  103152. });
  103153. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  103154. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  103155. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  103156. });
  103157. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  103158. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  103159. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  103160. });
  103161. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  103162. }
  103163. else {
  103164. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  103165. width: blurTextureWidth,
  103166. height: blurTextureHeight
  103167. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103168. this._horizontalBlurPostprocess.width = blurTextureWidth;
  103169. this._horizontalBlurPostprocess.height = blurTextureHeight;
  103170. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  103171. effect.setTexture("textureSampler", _this._mainTexture);
  103172. });
  103173. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  103174. width: blurTextureWidth,
  103175. height: blurTextureHeight
  103176. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103177. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  103178. }
  103179. this._mainTexture.onAfterUnbindObservable.add(function () {
  103180. _this.onBeforeBlurObservable.notifyObservers(_this);
  103181. var internalTexture = _this._blurTexture.getInternalTexture();
  103182. if (internalTexture) {
  103183. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  103184. }
  103185. _this.onAfterBlurObservable.notifyObservers(_this);
  103186. });
  103187. // Prevent autoClear.
  103188. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  103189. };
  103190. /**
  103191. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  103192. */
  103193. HighlightLayer.prototype.needStencil = function () {
  103194. return true;
  103195. };
  103196. /**
  103197. * Checks for the readiness of the element composing the layer.
  103198. * @param subMesh the mesh to check for
  103199. * @param useInstances specify wether or not to use instances to render the mesh
  103200. * @param emissiveTexture the associated emissive texture used to generate the glow
  103201. * @return true if ready otherwise, false
  103202. */
  103203. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  103204. var material = subMesh.getMaterial();
  103205. var mesh = subMesh.getRenderingMesh();
  103206. if (!material || !mesh || !this._meshes) {
  103207. return false;
  103208. }
  103209. var emissiveTexture = null;
  103210. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  103211. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  103212. emissiveTexture = material.emissiveTexture;
  103213. }
  103214. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  103215. };
  103216. /**
  103217. * Implementation specific of rendering the generating effect on the main canvas.
  103218. * @param effect The effect used to render through
  103219. */
  103220. HighlightLayer.prototype._internalRender = function (effect) {
  103221. // Texture
  103222. effect.setTexture("textureSampler", this._blurTexture);
  103223. // Cache
  103224. var engine = this._engine;
  103225. var previousStencilBuffer = engine.getStencilBuffer();
  103226. var previousStencilFunction = engine.getStencilFunction();
  103227. var previousStencilMask = engine.getStencilMask();
  103228. var previousStencilOperationPass = engine.getStencilOperationPass();
  103229. var previousStencilOperationFail = engine.getStencilOperationFail();
  103230. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  103231. var previousStencilReference = engine.getStencilFunctionReference();
  103232. // Stencil operations
  103233. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  103234. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  103235. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  103236. // Draw order
  103237. engine.setStencilMask(0x00);
  103238. engine.setStencilBuffer(true);
  103239. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  103240. // 2 passes inner outer
  103241. if (this.outerGlow) {
  103242. effect.setFloat("offset", 0);
  103243. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  103244. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103245. }
  103246. if (this.innerGlow) {
  103247. effect.setFloat("offset", 1);
  103248. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  103249. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103250. }
  103251. // Restore Cache
  103252. engine.setStencilFunction(previousStencilFunction);
  103253. engine.setStencilMask(previousStencilMask);
  103254. engine.setStencilBuffer(previousStencilBuffer);
  103255. engine.setStencilOperationPass(previousStencilOperationPass);
  103256. engine.setStencilOperationFail(previousStencilOperationFail);
  103257. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  103258. engine.setStencilFunctionReference(previousStencilReference);
  103259. };
  103260. /**
  103261. * Returns true if the layer contains information to display, otherwise false.
  103262. */
  103263. HighlightLayer.prototype.shouldRender = function () {
  103264. if (_super.prototype.shouldRender.call(this)) {
  103265. return this._meshes ? true : false;
  103266. }
  103267. return false;
  103268. };
  103269. /**
  103270. * Returns true if the mesh should render, otherwise false.
  103271. * @param mesh The mesh to render
  103272. * @returns true if it should render otherwise false
  103273. */
  103274. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  103275. // Excluded Mesh
  103276. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  103277. return false;
  103278. }
  103279. ;
  103280. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103281. return false;
  103282. }
  103283. return true;
  103284. };
  103285. /**
  103286. * Sets the required values for both the emissive texture and and the main color.
  103287. */
  103288. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  103289. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  103290. if (highlightLayerMesh) {
  103291. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  103292. }
  103293. else {
  103294. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  103295. }
  103296. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  103297. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  103298. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  103299. }
  103300. else {
  103301. this._emissiveTextureAndColor.texture = null;
  103302. }
  103303. };
  103304. /**
  103305. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  103306. * @param mesh The mesh to exclude from the highlight layer
  103307. */
  103308. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  103309. if (!this._excludedMeshes) {
  103310. return;
  103311. }
  103312. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  103313. if (!meshExcluded) {
  103314. this._excludedMeshes[mesh.uniqueId] = {
  103315. mesh: mesh,
  103316. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  103317. mesh.getEngine().setStencilBuffer(false);
  103318. }),
  103319. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  103320. mesh.getEngine().setStencilBuffer(true);
  103321. }),
  103322. };
  103323. }
  103324. };
  103325. /**
  103326. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  103327. * @param mesh The mesh to highlight
  103328. */
  103329. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  103330. if (!this._excludedMeshes) {
  103331. return;
  103332. }
  103333. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  103334. if (meshExcluded) {
  103335. if (meshExcluded.beforeRender) {
  103336. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  103337. }
  103338. if (meshExcluded.afterRender) {
  103339. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  103340. }
  103341. }
  103342. this._excludedMeshes[mesh.uniqueId] = null;
  103343. };
  103344. /**
  103345. * Determine if a given mesh will be highlighted by the current HighlightLayer
  103346. * @param mesh mesh to test
  103347. * @returns true if the mesh will be highlighted by the current HighlightLayer
  103348. */
  103349. HighlightLayer.prototype.hasMesh = function (mesh) {
  103350. if (!this._meshes) {
  103351. return false;
  103352. }
  103353. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103354. return false;
  103355. }
  103356. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  103357. };
  103358. /**
  103359. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  103360. * @param mesh The mesh to highlight
  103361. * @param color The color of the highlight
  103362. * @param glowEmissiveOnly Extract the glow from the emissive texture
  103363. */
  103364. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  103365. var _this = this;
  103366. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  103367. if (!this._meshes) {
  103368. return;
  103369. }
  103370. var meshHighlight = this._meshes[mesh.uniqueId];
  103371. if (meshHighlight) {
  103372. meshHighlight.color = color;
  103373. }
  103374. else {
  103375. this._meshes[mesh.uniqueId] = {
  103376. mesh: mesh,
  103377. color: color,
  103378. // Lambda required for capture due to Observable this context
  103379. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  103380. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  103381. _this._defaultStencilReference(mesh);
  103382. }
  103383. else {
  103384. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  103385. }
  103386. }),
  103387. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  103388. glowEmissiveOnly: glowEmissiveOnly
  103389. };
  103390. mesh.onDisposeObservable.add(function () {
  103391. _this._disposeMesh(mesh);
  103392. });
  103393. }
  103394. this._shouldRender = true;
  103395. };
  103396. /**
  103397. * Remove a mesh from the highlight layer in order to make it stop glowing.
  103398. * @param mesh The mesh to highlight
  103399. */
  103400. HighlightLayer.prototype.removeMesh = function (mesh) {
  103401. if (!this._meshes) {
  103402. return;
  103403. }
  103404. var meshHighlight = this._meshes[mesh.uniqueId];
  103405. if (meshHighlight) {
  103406. if (meshHighlight.observerHighlight) {
  103407. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  103408. }
  103409. if (meshHighlight.observerDefault) {
  103410. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  103411. }
  103412. delete this._meshes[mesh.uniqueId];
  103413. }
  103414. this._shouldRender = false;
  103415. for (var meshHighlightToCheck in this._meshes) {
  103416. if (this._meshes[meshHighlightToCheck]) {
  103417. this._shouldRender = true;
  103418. break;
  103419. }
  103420. }
  103421. };
  103422. /**
  103423. * Force the stencil to the normal expected value for none glowing parts
  103424. */
  103425. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  103426. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  103427. };
  103428. /**
  103429. * Free any resources and references associated to a mesh.
  103430. * Internal use
  103431. * @param mesh The mesh to free.
  103432. * @hidden
  103433. */
  103434. HighlightLayer.prototype._disposeMesh = function (mesh) {
  103435. this.removeMesh(mesh);
  103436. this.removeExcludedMesh(mesh);
  103437. };
  103438. /**
  103439. * Dispose the highlight layer and free resources.
  103440. */
  103441. HighlightLayer.prototype.dispose = function () {
  103442. if (this._meshes) {
  103443. // Clean mesh references
  103444. for (var id in this._meshes) {
  103445. var meshHighlight = this._meshes[id];
  103446. if (meshHighlight && meshHighlight.mesh) {
  103447. if (meshHighlight.observerHighlight) {
  103448. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  103449. }
  103450. if (meshHighlight.observerDefault) {
  103451. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  103452. }
  103453. }
  103454. }
  103455. this._meshes = null;
  103456. }
  103457. if (this._excludedMeshes) {
  103458. for (var id in this._excludedMeshes) {
  103459. var meshHighlight = this._excludedMeshes[id];
  103460. if (meshHighlight) {
  103461. if (meshHighlight.beforeRender) {
  103462. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  103463. }
  103464. if (meshHighlight.afterRender) {
  103465. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  103466. }
  103467. }
  103468. }
  103469. this._excludedMeshes = null;
  103470. }
  103471. _super.prototype.dispose.call(this);
  103472. };
  103473. /**
  103474. * Gets the class name of the effect layer
  103475. * @returns the string with the class name of the effect layer
  103476. */
  103477. HighlightLayer.prototype.getClassName = function () {
  103478. return "HighlightLayer";
  103479. };
  103480. /**
  103481. * Serializes this Highlight layer
  103482. * @returns a serialized Highlight layer object
  103483. */
  103484. HighlightLayer.prototype.serialize = function () {
  103485. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103486. serializationObject.customType = "BABYLON.HighlightLayer";
  103487. // Highlighted meshes
  103488. serializationObject.meshes = [];
  103489. if (this._meshes) {
  103490. for (var m in this._meshes) {
  103491. var mesh = this._meshes[m];
  103492. if (mesh) {
  103493. serializationObject.meshes.push({
  103494. glowEmissiveOnly: mesh.glowEmissiveOnly,
  103495. color: mesh.color.asArray(),
  103496. meshId: mesh.mesh.id
  103497. });
  103498. }
  103499. }
  103500. }
  103501. // Excluded meshes
  103502. serializationObject.excludedMeshes = [];
  103503. if (this._excludedMeshes) {
  103504. for (var e in this._excludedMeshes) {
  103505. var excludedMesh = this._excludedMeshes[e];
  103506. if (excludedMesh) {
  103507. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  103508. }
  103509. }
  103510. }
  103511. return serializationObject;
  103512. };
  103513. /**
  103514. * Creates a Highlight layer from parsed Highlight layer data
  103515. * @param parsedHightlightLayer defines the Highlight layer data
  103516. * @param scene defines the current scene
  103517. * @param rootUrl defines the root URL containing the Highlight layer information
  103518. * @returns a parsed Highlight layer
  103519. */
  103520. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  103521. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  103522. var index;
  103523. // Excluded meshes
  103524. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  103525. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  103526. if (mesh) {
  103527. hl.addExcludedMesh(mesh);
  103528. }
  103529. }
  103530. // Included meshes
  103531. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  103532. var highlightedMesh = parsedHightlightLayer.meshes[index];
  103533. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  103534. if (mesh) {
  103535. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  103536. }
  103537. }
  103538. return hl;
  103539. };
  103540. /**
  103541. * Effect Name of the highlight layer.
  103542. */
  103543. HighlightLayer.EffectName = "HighlightLayer";
  103544. /**
  103545. * The neutral color used during the preparation of the glow effect.
  103546. * This is black by default as the blend operation is a blend operation.
  103547. */
  103548. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  103549. /**
  103550. * Stencil value used for glowing meshes.
  103551. */
  103552. HighlightLayer.GlowingMeshStencilReference = 0x02;
  103553. /**
  103554. * Stencil value used for the other meshes in the scene.
  103555. */
  103556. HighlightLayer.NormalMeshStencilReference = 0x01;
  103557. __decorate([
  103558. BABYLON.serialize()
  103559. ], HighlightLayer.prototype, "innerGlow", void 0);
  103560. __decorate([
  103561. BABYLON.serialize()
  103562. ], HighlightLayer.prototype, "outerGlow", void 0);
  103563. __decorate([
  103564. BABYLON.serialize()
  103565. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  103566. __decorate([
  103567. BABYLON.serialize()
  103568. ], HighlightLayer.prototype, "blurVerticalSize", null);
  103569. __decorate([
  103570. BABYLON.serialize("options")
  103571. ], HighlightLayer.prototype, "_options", void 0);
  103572. return HighlightLayer;
  103573. }(BABYLON.EffectLayer));
  103574. BABYLON.HighlightLayer = HighlightLayer;
  103575. })(BABYLON || (BABYLON = {}));
  103576. //# sourceMappingURL=babylon.highlightLayer.js.map
  103577. var BABYLON;
  103578. (function (BABYLON) {
  103579. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  103580. for (var index = 0; index < this.effectLayers.length; index++) {
  103581. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  103582. return this.effectLayers[index];
  103583. }
  103584. }
  103585. return null;
  103586. };
  103587. /**
  103588. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  103589. *
  103590. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  103591. * glowy meshes to your scene.
  103592. *
  103593. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  103594. */
  103595. var GlowLayer = /** @class */ (function (_super) {
  103596. __extends(GlowLayer, _super);
  103597. /**
  103598. * Instantiates a new glow Layer and references it to the scene.
  103599. * @param name The name of the layer
  103600. * @param scene The scene to use the layer in
  103601. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  103602. */
  103603. function GlowLayer(name, scene, options) {
  103604. var _this = _super.call(this, name, scene) || this;
  103605. _this._intensity = 1.0;
  103606. _this._includedOnlyMeshes = [];
  103607. _this._excludedMeshes = [];
  103608. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  103609. // Adapt options
  103610. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  103611. // Initialize the layer
  103612. _this._init({
  103613. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  103614. camera: _this._options.camera,
  103615. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  103616. mainTextureRatio: _this._options.mainTextureRatio,
  103617. renderingGroupId: _this._options.renderingGroupId
  103618. });
  103619. return _this;
  103620. }
  103621. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  103622. /**
  103623. * Gets the kernel size of the blur.
  103624. */
  103625. get: function () {
  103626. return this._horizontalBlurPostprocess1.kernel;
  103627. },
  103628. /**
  103629. * Sets the kernel size of the blur.
  103630. */
  103631. set: function (value) {
  103632. this._horizontalBlurPostprocess1.kernel = value;
  103633. this._verticalBlurPostprocess1.kernel = value;
  103634. this._horizontalBlurPostprocess2.kernel = value;
  103635. this._verticalBlurPostprocess2.kernel = value;
  103636. },
  103637. enumerable: true,
  103638. configurable: true
  103639. });
  103640. Object.defineProperty(GlowLayer.prototype, "intensity", {
  103641. /**
  103642. * Gets the glow intensity.
  103643. */
  103644. get: function () {
  103645. return this._intensity;
  103646. },
  103647. /**
  103648. * Sets the glow intensity.
  103649. */
  103650. set: function (value) {
  103651. this._intensity = value;
  103652. },
  103653. enumerable: true,
  103654. configurable: true
  103655. });
  103656. /**
  103657. * Get the effect name of the layer.
  103658. * @return The effect name
  103659. */
  103660. GlowLayer.prototype.getEffectName = function () {
  103661. return GlowLayer.EffectName;
  103662. };
  103663. /**
  103664. * Create the merge effect. This is the shader use to blit the information back
  103665. * to the main canvas at the end of the scene rendering.
  103666. */
  103667. GlowLayer.prototype._createMergeEffect = function () {
  103668. // Effect
  103669. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  103670. };
  103671. /**
  103672. * Creates the render target textures and post processes used in the glow layer.
  103673. */
  103674. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  103675. var _this = this;
  103676. var blurTextureWidth = this._mainTextureDesiredSize.width;
  103677. var blurTextureHeight = this._mainTextureDesiredSize.height;
  103678. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  103679. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  103680. var textureType = 0;
  103681. if (this._engine.getCaps().textureHalfFloatRender) {
  103682. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  103683. }
  103684. else {
  103685. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  103686. }
  103687. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  103688. width: blurTextureWidth,
  103689. height: blurTextureHeight
  103690. }, this._scene, false, true, textureType);
  103691. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103692. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103693. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  103694. this._blurTexture1.renderParticles = false;
  103695. this._blurTexture1.ignoreCameraViewport = true;
  103696. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  103697. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  103698. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  103699. width: blurTextureWidth2,
  103700. height: blurTextureHeight2
  103701. }, this._scene, false, true, textureType);
  103702. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103703. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103704. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  103705. this._blurTexture2.renderParticles = false;
  103706. this._blurTexture2.ignoreCameraViewport = true;
  103707. this._textures = [this._blurTexture1, this._blurTexture2];
  103708. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  103709. width: blurTextureWidth,
  103710. height: blurTextureHeight
  103711. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103712. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  103713. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  103714. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  103715. effect.setTexture("textureSampler", _this._mainTexture);
  103716. });
  103717. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  103718. width: blurTextureWidth,
  103719. height: blurTextureHeight
  103720. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103721. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  103722. width: blurTextureWidth2,
  103723. height: blurTextureHeight2
  103724. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103725. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  103726. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  103727. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  103728. effect.setTexture("textureSampler", _this._blurTexture1);
  103729. });
  103730. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  103731. width: blurTextureWidth2,
  103732. height: blurTextureHeight2
  103733. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103734. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  103735. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  103736. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  103737. this._mainTexture.samples = this._options.mainTextureSamples;
  103738. this._mainTexture.onAfterUnbindObservable.add(function () {
  103739. var internalTexture = _this._blurTexture1.getInternalTexture();
  103740. if (internalTexture) {
  103741. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  103742. internalTexture = _this._blurTexture2.getInternalTexture();
  103743. if (internalTexture) {
  103744. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  103745. }
  103746. }
  103747. });
  103748. // Prevent autoClear.
  103749. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  103750. };
  103751. /**
  103752. * Checks for the readiness of the element composing the layer.
  103753. * @param subMesh the mesh to check for
  103754. * @param useInstances specify wether or not to use instances to render the mesh
  103755. * @param emissiveTexture the associated emissive texture used to generate the glow
  103756. * @return true if ready otherwise, false
  103757. */
  103758. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  103759. var material = subMesh.getMaterial();
  103760. var mesh = subMesh.getRenderingMesh();
  103761. if (!material || !mesh) {
  103762. return false;
  103763. }
  103764. var emissiveTexture = material.emissiveTexture;
  103765. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  103766. };
  103767. /**
  103768. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  103769. */
  103770. GlowLayer.prototype.needStencil = function () {
  103771. return false;
  103772. };
  103773. /**
  103774. * Implementation specific of rendering the generating effect on the main canvas.
  103775. * @param effect The effect used to render through
  103776. */
  103777. GlowLayer.prototype._internalRender = function (effect) {
  103778. // Texture
  103779. effect.setTexture("textureSampler", this._blurTexture1);
  103780. effect.setTexture("textureSampler2", this._blurTexture2);
  103781. effect.setFloat("offset", this._intensity);
  103782. // Cache
  103783. var engine = this._engine;
  103784. var previousStencilBuffer = engine.getStencilBuffer();
  103785. // Draw order
  103786. engine.setStencilBuffer(false);
  103787. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103788. // Draw order
  103789. engine.setStencilBuffer(previousStencilBuffer);
  103790. };
  103791. /**
  103792. * Sets the required values for both the emissive texture and and the main color.
  103793. */
  103794. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  103795. var textureLevel = 1.0;
  103796. if (this.customEmissiveTextureSelector) {
  103797. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  103798. }
  103799. else {
  103800. if (material) {
  103801. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  103802. if (this._emissiveTextureAndColor.texture) {
  103803. textureLevel = this._emissiveTextureAndColor.texture.level;
  103804. }
  103805. }
  103806. else {
  103807. this._emissiveTextureAndColor.texture = null;
  103808. }
  103809. }
  103810. if (this.customEmissiveColorSelector) {
  103811. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  103812. }
  103813. else {
  103814. if (material.emissiveColor) {
  103815. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  103816. }
  103817. else {
  103818. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  103819. }
  103820. }
  103821. };
  103822. /**
  103823. * Returns true if the mesh should render, otherwise false.
  103824. * @param mesh The mesh to render
  103825. * @returns true if it should render otherwise false
  103826. */
  103827. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  103828. return this.hasMesh(mesh);
  103829. };
  103830. /**
  103831. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  103832. * @param mesh The mesh to exclude from the glow layer
  103833. */
  103834. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  103835. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  103836. this._excludedMeshes.push(mesh.uniqueId);
  103837. }
  103838. };
  103839. /**
  103840. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  103841. * @param mesh The mesh to remove
  103842. */
  103843. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  103844. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  103845. if (index !== -1) {
  103846. this._excludedMeshes.splice(index, 1);
  103847. }
  103848. };
  103849. /**
  103850. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  103851. * @param mesh The mesh to include in the glow layer
  103852. */
  103853. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  103854. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  103855. this._includedOnlyMeshes.push(mesh.uniqueId);
  103856. }
  103857. };
  103858. /**
  103859. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  103860. * @param mesh The mesh to remove
  103861. */
  103862. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  103863. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  103864. if (index !== -1) {
  103865. this._includedOnlyMeshes.splice(index, 1);
  103866. }
  103867. };
  103868. /**
  103869. * Determine if a given mesh will be used in the glow layer
  103870. * @param mesh The mesh to test
  103871. * @returns true if the mesh will be highlighted by the current glow layer
  103872. */
  103873. GlowLayer.prototype.hasMesh = function (mesh) {
  103874. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103875. return false;
  103876. }
  103877. // Included Mesh
  103878. if (this._includedOnlyMeshes.length) {
  103879. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  103880. }
  103881. ;
  103882. // Excluded Mesh
  103883. if (this._excludedMeshes.length) {
  103884. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  103885. }
  103886. ;
  103887. return true;
  103888. };
  103889. /**
  103890. * Free any resources and references associated to a mesh.
  103891. * Internal use
  103892. * @param mesh The mesh to free.
  103893. * @hidden
  103894. */
  103895. GlowLayer.prototype._disposeMesh = function (mesh) {
  103896. this.removeIncludedOnlyMesh(mesh);
  103897. this.removeExcludedMesh(mesh);
  103898. };
  103899. /**
  103900. * Gets the class name of the effect layer
  103901. * @returns the string with the class name of the effect layer
  103902. */
  103903. GlowLayer.prototype.getClassName = function () {
  103904. return "GlowLayer";
  103905. };
  103906. /**
  103907. * Serializes this glow layer
  103908. * @returns a serialized glow layer object
  103909. */
  103910. GlowLayer.prototype.serialize = function () {
  103911. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103912. serializationObject.customType = "BABYLON.GlowLayer";
  103913. var index;
  103914. // Included meshes
  103915. serializationObject.includedMeshes = [];
  103916. if (this._includedOnlyMeshes.length) {
  103917. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  103918. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  103919. if (mesh) {
  103920. serializationObject.includedMeshes.push(mesh.id);
  103921. }
  103922. }
  103923. }
  103924. // Excluded meshes
  103925. serializationObject.excludedMeshes = [];
  103926. if (this._excludedMeshes.length) {
  103927. for (index = 0; index < this._excludedMeshes.length; index++) {
  103928. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  103929. if (mesh) {
  103930. serializationObject.excludedMeshes.push(mesh.id);
  103931. }
  103932. }
  103933. }
  103934. return serializationObject;
  103935. };
  103936. /**
  103937. * Creates a Glow Layer from parsed glow layer data
  103938. * @param parsedGlowLayer defines glow layer data
  103939. * @param scene defines the current scene
  103940. * @param rootUrl defines the root URL containing the glow layer information
  103941. * @returns a parsed Glow Layer
  103942. */
  103943. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  103944. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  103945. var index;
  103946. // Excluded meshes
  103947. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  103948. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  103949. if (mesh) {
  103950. gl.addExcludedMesh(mesh);
  103951. }
  103952. }
  103953. // Included meshes
  103954. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  103955. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  103956. if (mesh) {
  103957. gl.addIncludedOnlyMesh(mesh);
  103958. }
  103959. }
  103960. return gl;
  103961. };
  103962. /**
  103963. * Effect Name of the layer.
  103964. */
  103965. GlowLayer.EffectName = "GlowLayer";
  103966. /**
  103967. * The default blur kernel size used for the glow.
  103968. */
  103969. GlowLayer.DefaultBlurKernelSize = 32;
  103970. /**
  103971. * The default texture size ratio used for the glow.
  103972. */
  103973. GlowLayer.DefaultTextureRatio = 0.5;
  103974. __decorate([
  103975. BABYLON.serialize()
  103976. ], GlowLayer.prototype, "blurKernelSize", null);
  103977. __decorate([
  103978. BABYLON.serialize()
  103979. ], GlowLayer.prototype, "intensity", null);
  103980. __decorate([
  103981. BABYLON.serialize("options")
  103982. ], GlowLayer.prototype, "_options", void 0);
  103983. return GlowLayer;
  103984. }(BABYLON.EffectLayer));
  103985. BABYLON.GlowLayer = GlowLayer;
  103986. })(BABYLON || (BABYLON = {}));
  103987. //# sourceMappingURL=babylon.glowLayer.js.map
  103988. var BABYLON;
  103989. (function (BABYLON) {
  103990. /**
  103991. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  103992. */
  103993. var AssetTaskState;
  103994. (function (AssetTaskState) {
  103995. /**
  103996. * Initialization
  103997. */
  103998. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  103999. /**
  104000. * Running
  104001. */
  104002. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  104003. /**
  104004. * Done
  104005. */
  104006. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  104007. /**
  104008. * Error
  104009. */
  104010. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  104011. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  104012. /**
  104013. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  104014. */
  104015. var AbstractAssetTask = /** @class */ (function () {
  104016. /**
  104017. * Creates a new {BABYLON.AssetsManager}
  104018. * @param name defines the name of the task
  104019. */
  104020. function AbstractAssetTask(
  104021. /**
  104022. * Task name
  104023. */ name) {
  104024. this.name = name;
  104025. this._isCompleted = false;
  104026. this._taskState = AssetTaskState.INIT;
  104027. }
  104028. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  104029. /**
  104030. * Get if the task is completed
  104031. */
  104032. get: function () {
  104033. return this._isCompleted;
  104034. },
  104035. enumerable: true,
  104036. configurable: true
  104037. });
  104038. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  104039. /**
  104040. * Gets the current state of the task
  104041. */
  104042. get: function () {
  104043. return this._taskState;
  104044. },
  104045. enumerable: true,
  104046. configurable: true
  104047. });
  104048. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  104049. /**
  104050. * Gets the current error object (if task is in error)
  104051. */
  104052. get: function () {
  104053. return this._errorObject;
  104054. },
  104055. enumerable: true,
  104056. configurable: true
  104057. });
  104058. /**
  104059. * Internal only
  104060. * @hidden
  104061. */
  104062. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  104063. if (this._errorObject) {
  104064. return;
  104065. }
  104066. this._errorObject = {
  104067. message: message,
  104068. exception: exception
  104069. };
  104070. };
  104071. /**
  104072. * Execute the current task
  104073. * @param scene defines the scene where you want your assets to be loaded
  104074. * @param onSuccess is a callback called when the task is successfully executed
  104075. * @param onError is a callback called if an error occurs
  104076. */
  104077. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  104078. var _this = this;
  104079. this._taskState = AssetTaskState.RUNNING;
  104080. this.runTask(scene, function () {
  104081. _this.onDoneCallback(onSuccess, onError);
  104082. }, function (msg, exception) {
  104083. _this.onErrorCallback(onError, msg, exception);
  104084. });
  104085. };
  104086. /**
  104087. * Execute the current task
  104088. * @param scene defines the scene where you want your assets to be loaded
  104089. * @param onSuccess is a callback called when the task is successfully executed
  104090. * @param onError is a callback called if an error occurs
  104091. */
  104092. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104093. throw new Error("runTask is not implemented");
  104094. };
  104095. /**
  104096. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  104097. * This can be used with failed tasks that have the reason for failure fixed.
  104098. */
  104099. AbstractAssetTask.prototype.reset = function () {
  104100. this._taskState = AssetTaskState.INIT;
  104101. };
  104102. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  104103. this._taskState = AssetTaskState.ERROR;
  104104. this._errorObject = {
  104105. message: message,
  104106. exception: exception
  104107. };
  104108. if (this.onError) {
  104109. this.onError(this, message, exception);
  104110. }
  104111. onError();
  104112. };
  104113. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  104114. try {
  104115. this._taskState = AssetTaskState.DONE;
  104116. this._isCompleted = true;
  104117. if (this.onSuccess) {
  104118. this.onSuccess(this);
  104119. }
  104120. onSuccess();
  104121. }
  104122. catch (e) {
  104123. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  104124. }
  104125. };
  104126. return AbstractAssetTask;
  104127. }());
  104128. BABYLON.AbstractAssetTask = AbstractAssetTask;
  104129. /**
  104130. * Class used to share progress information about assets loading
  104131. */
  104132. var AssetsProgressEvent = /** @class */ (function () {
  104133. /**
  104134. * Creates a {BABYLON.AssetsProgressEvent}
  104135. * @param remainingCount defines the number of remaining tasks to process
  104136. * @param totalCount defines the total number of tasks
  104137. * @param task defines the task that was just processed
  104138. */
  104139. function AssetsProgressEvent(remainingCount, totalCount, task) {
  104140. this.remainingCount = remainingCount;
  104141. this.totalCount = totalCount;
  104142. this.task = task;
  104143. }
  104144. return AssetsProgressEvent;
  104145. }());
  104146. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  104147. /**
  104148. * Define a task used by {BABYLON.AssetsManager} to load meshes
  104149. */
  104150. var MeshAssetTask = /** @class */ (function (_super) {
  104151. __extends(MeshAssetTask, _super);
  104152. /**
  104153. * Creates a new {BABYLON.MeshAssetTask}
  104154. * @param name defines the name of the task
  104155. * @param meshesNames defines the list of mesh's names you want to load
  104156. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  104157. * @param sceneFilename defines the filename of the scene to load from
  104158. */
  104159. function MeshAssetTask(
  104160. /**
  104161. * Defines the name of the task
  104162. */
  104163. name,
  104164. /**
  104165. * Defines the list of mesh's names you want to load
  104166. */
  104167. meshesNames,
  104168. /**
  104169. * Defines the root url to use as a base to load your meshes and associated resources
  104170. */
  104171. rootUrl,
  104172. /**
  104173. * Defines the filename of the scene to load from
  104174. */
  104175. sceneFilename) {
  104176. var _this = _super.call(this, name) || this;
  104177. _this.name = name;
  104178. _this.meshesNames = meshesNames;
  104179. _this.rootUrl = rootUrl;
  104180. _this.sceneFilename = sceneFilename;
  104181. return _this;
  104182. }
  104183. /**
  104184. * Execute the current task
  104185. * @param scene defines the scene where you want your assets to be loaded
  104186. * @param onSuccess is a callback called when the task is successfully executed
  104187. * @param onError is a callback called if an error occurs
  104188. */
  104189. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104190. var _this = this;
  104191. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  104192. _this.loadedMeshes = meshes;
  104193. _this.loadedParticleSystems = particleSystems;
  104194. _this.loadedSkeletons = skeletons;
  104195. onSuccess();
  104196. }, null, function (scene, message, exception) {
  104197. onError(message, exception);
  104198. });
  104199. };
  104200. return MeshAssetTask;
  104201. }(AbstractAssetTask));
  104202. BABYLON.MeshAssetTask = MeshAssetTask;
  104203. /**
  104204. * Define a task used by {BABYLON.AssetsManager} to load text content
  104205. */
  104206. var TextFileAssetTask = /** @class */ (function (_super) {
  104207. __extends(TextFileAssetTask, _super);
  104208. /**
  104209. * Creates a new TextFileAssetTask object
  104210. * @param name defines the name of the task
  104211. * @param url defines the location of the file to load
  104212. */
  104213. function TextFileAssetTask(
  104214. /**
  104215. * Defines the name of the task
  104216. */
  104217. name,
  104218. /**
  104219. * Defines the location of the file to load
  104220. */
  104221. url) {
  104222. var _this = _super.call(this, name) || this;
  104223. _this.name = name;
  104224. _this.url = url;
  104225. return _this;
  104226. }
  104227. /**
  104228. * Execute the current task
  104229. * @param scene defines the scene where you want your assets to be loaded
  104230. * @param onSuccess is a callback called when the task is successfully executed
  104231. * @param onError is a callback called if an error occurs
  104232. */
  104233. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104234. var _this = this;
  104235. scene._loadFile(this.url, function (data) {
  104236. _this.text = data;
  104237. onSuccess();
  104238. }, undefined, false, false, function (request, exception) {
  104239. if (request) {
  104240. onError(request.status + " " + request.statusText, exception);
  104241. }
  104242. });
  104243. };
  104244. return TextFileAssetTask;
  104245. }(AbstractAssetTask));
  104246. BABYLON.TextFileAssetTask = TextFileAssetTask;
  104247. /**
  104248. * Define a task used by {BABYLON.AssetsManager} to load binary data
  104249. */
  104250. var BinaryFileAssetTask = /** @class */ (function (_super) {
  104251. __extends(BinaryFileAssetTask, _super);
  104252. /**
  104253. * Creates a new BinaryFileAssetTask object
  104254. * @param name defines the name of the new task
  104255. * @param url defines the location of the file to load
  104256. */
  104257. function BinaryFileAssetTask(
  104258. /**
  104259. * Defines the name of the task
  104260. */
  104261. name,
  104262. /**
  104263. * Defines the location of the file to load
  104264. */
  104265. url) {
  104266. var _this = _super.call(this, name) || this;
  104267. _this.name = name;
  104268. _this.url = url;
  104269. return _this;
  104270. }
  104271. /**
  104272. * Execute the current task
  104273. * @param scene defines the scene where you want your assets to be loaded
  104274. * @param onSuccess is a callback called when the task is successfully executed
  104275. * @param onError is a callback called if an error occurs
  104276. */
  104277. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104278. var _this = this;
  104279. scene._loadFile(this.url, function (data) {
  104280. _this.data = data;
  104281. onSuccess();
  104282. }, undefined, true, true, function (request, exception) {
  104283. if (request) {
  104284. onError(request.status + " " + request.statusText, exception);
  104285. }
  104286. });
  104287. };
  104288. return BinaryFileAssetTask;
  104289. }(AbstractAssetTask));
  104290. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  104291. /**
  104292. * Define a task used by {BABYLON.AssetsManager} to load images
  104293. */
  104294. var ImageAssetTask = /** @class */ (function (_super) {
  104295. __extends(ImageAssetTask, _super);
  104296. /**
  104297. * Creates a new ImageAssetTask
  104298. * @param name defines the name of the task
  104299. * @param url defines the location of the image to load
  104300. */
  104301. function ImageAssetTask(
  104302. /**
  104303. * Defines the name of the task
  104304. */
  104305. name,
  104306. /**
  104307. * Defines the location of the image to load
  104308. */
  104309. url) {
  104310. var _this = _super.call(this, name) || this;
  104311. _this.name = name;
  104312. _this.url = url;
  104313. return _this;
  104314. }
  104315. /**
  104316. * Execute the current task
  104317. * @param scene defines the scene where you want your assets to be loaded
  104318. * @param onSuccess is a callback called when the task is successfully executed
  104319. * @param onError is a callback called if an error occurs
  104320. */
  104321. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104322. var _this = this;
  104323. var img = new Image();
  104324. BABYLON.Tools.SetCorsBehavior(this.url, img);
  104325. img.onload = function () {
  104326. _this.image = img;
  104327. onSuccess();
  104328. };
  104329. img.onerror = function (err) {
  104330. onError("Error loading image", err);
  104331. };
  104332. img.src = this.url;
  104333. };
  104334. return ImageAssetTask;
  104335. }(AbstractAssetTask));
  104336. BABYLON.ImageAssetTask = ImageAssetTask;
  104337. /**
  104338. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  104339. */
  104340. var TextureAssetTask = /** @class */ (function (_super) {
  104341. __extends(TextureAssetTask, _super);
  104342. /**
  104343. * Creates a new TextureAssetTask object
  104344. * @param name defines the name of the task
  104345. * @param url defines the location of the file to load
  104346. * @param noMipmap defines if mipmap should not be generated (default is false)
  104347. * @param invertY defines if texture must be inverted on Y axis (default is false)
  104348. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  104349. */
  104350. function TextureAssetTask(
  104351. /**
  104352. * Defines the name of the task
  104353. */
  104354. name,
  104355. /**
  104356. * Defines the location of the file to load
  104357. */
  104358. url,
  104359. /**
  104360. * Defines if mipmap should not be generated (default is false)
  104361. */
  104362. noMipmap,
  104363. /**
  104364. * Defines if texture must be inverted on Y axis (default is false)
  104365. */
  104366. invertY,
  104367. /**
  104368. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  104369. */
  104370. samplingMode) {
  104371. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104372. var _this = _super.call(this, name) || this;
  104373. _this.name = name;
  104374. _this.url = url;
  104375. _this.noMipmap = noMipmap;
  104376. _this.invertY = invertY;
  104377. _this.samplingMode = samplingMode;
  104378. return _this;
  104379. }
  104380. /**
  104381. * Execute the current task
  104382. * @param scene defines the scene where you want your assets to be loaded
  104383. * @param onSuccess is a callback called when the task is successfully executed
  104384. * @param onError is a callback called if an error occurs
  104385. */
  104386. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104387. var onload = function () {
  104388. onSuccess();
  104389. };
  104390. var onerror = function (message, exception) {
  104391. onError(message, exception);
  104392. };
  104393. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  104394. };
  104395. return TextureAssetTask;
  104396. }(AbstractAssetTask));
  104397. BABYLON.TextureAssetTask = TextureAssetTask;
  104398. /**
  104399. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  104400. */
  104401. var CubeTextureAssetTask = /** @class */ (function (_super) {
  104402. __extends(CubeTextureAssetTask, _super);
  104403. /**
  104404. * Creates a new CubeTextureAssetTask
  104405. * @param name defines the name of the task
  104406. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  104407. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  104408. * @param noMipmap defines if mipmaps should not be generated (default is false)
  104409. * @param files defines the explicit list of files (undefined by default)
  104410. */
  104411. function CubeTextureAssetTask(
  104412. /**
  104413. * Defines the name of the task
  104414. */
  104415. name,
  104416. /**
  104417. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  104418. */
  104419. url,
  104420. /**
  104421. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  104422. */
  104423. extensions,
  104424. /**
  104425. * Defines if mipmaps should not be generated (default is false)
  104426. */
  104427. noMipmap,
  104428. /**
  104429. * Defines the explicit list of files (undefined by default)
  104430. */
  104431. files) {
  104432. var _this = _super.call(this, name) || this;
  104433. _this.name = name;
  104434. _this.url = url;
  104435. _this.extensions = extensions;
  104436. _this.noMipmap = noMipmap;
  104437. _this.files = files;
  104438. return _this;
  104439. }
  104440. /**
  104441. * Execute the current task
  104442. * @param scene defines the scene where you want your assets to be loaded
  104443. * @param onSuccess is a callback called when the task is successfully executed
  104444. * @param onError is a callback called if an error occurs
  104445. */
  104446. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104447. var onload = function () {
  104448. onSuccess();
  104449. };
  104450. var onerror = function (message, exception) {
  104451. onError(message, exception);
  104452. };
  104453. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  104454. };
  104455. return CubeTextureAssetTask;
  104456. }(AbstractAssetTask));
  104457. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  104458. /**
  104459. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  104460. */
  104461. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  104462. __extends(HDRCubeTextureAssetTask, _super);
  104463. /**
  104464. * Creates a new HDRCubeTextureAssetTask object
  104465. * @param name defines the name of the task
  104466. * @param url defines the location of the file to load
  104467. * @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.
  104468. * @param noMipmap defines if mipmaps should not be generated (default is false)
  104469. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  104470. * @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)
  104471. * @param reserved Internal use only
  104472. */
  104473. function HDRCubeTextureAssetTask(
  104474. /**
  104475. * Defines the name of the task
  104476. */
  104477. name,
  104478. /**
  104479. * Defines the location of the file to load
  104480. */
  104481. url,
  104482. /**
  104483. * Defines the desired size (the more it increases the longer the generation will be)
  104484. */
  104485. size,
  104486. /**
  104487. * Defines if mipmaps should not be generated (default is false)
  104488. */
  104489. noMipmap,
  104490. /**
  104491. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  104492. */
  104493. generateHarmonics,
  104494. /**
  104495. * 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)
  104496. */
  104497. gammaSpace,
  104498. /**
  104499. * Internal Use Only
  104500. */
  104501. reserved) {
  104502. if (noMipmap === void 0) { noMipmap = false; }
  104503. if (generateHarmonics === void 0) { generateHarmonics = true; }
  104504. if (gammaSpace === void 0) { gammaSpace = false; }
  104505. if (reserved === void 0) { reserved = false; }
  104506. var _this = _super.call(this, name) || this;
  104507. _this.name = name;
  104508. _this.url = url;
  104509. _this.size = size;
  104510. _this.noMipmap = noMipmap;
  104511. _this.generateHarmonics = generateHarmonics;
  104512. _this.gammaSpace = gammaSpace;
  104513. _this.reserved = reserved;
  104514. return _this;
  104515. }
  104516. /**
  104517. * Execute the current task
  104518. * @param scene defines the scene where you want your assets to be loaded
  104519. * @param onSuccess is a callback called when the task is successfully executed
  104520. * @param onError is a callback called if an error occurs
  104521. */
  104522. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  104523. var onload = function () {
  104524. onSuccess();
  104525. };
  104526. var onerror = function (message, exception) {
  104527. onError(message, exception);
  104528. };
  104529. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  104530. };
  104531. return HDRCubeTextureAssetTask;
  104532. }(AbstractAssetTask));
  104533. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  104534. /**
  104535. * This class can be used to easily import assets into a scene
  104536. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  104537. */
  104538. var AssetsManager = /** @class */ (function () {
  104539. /**
  104540. * Creates a new AssetsManager
  104541. * @param scene defines the scene to work on
  104542. */
  104543. function AssetsManager(scene) {
  104544. this._isLoading = false;
  104545. this._tasks = new Array();
  104546. this._waitingTasksCount = 0;
  104547. this._totalTasksCount = 0;
  104548. /**
  104549. * Observable called when all tasks are processed
  104550. */
  104551. this.onTaskSuccessObservable = new BABYLON.Observable();
  104552. /**
  104553. * Observable called when a task had an error
  104554. */
  104555. this.onTaskErrorObservable = new BABYLON.Observable();
  104556. /**
  104557. * Observable called when a task is successful
  104558. */
  104559. this.onTasksDoneObservable = new BABYLON.Observable();
  104560. /**
  104561. * Observable called when a task is done (whatever the result is)
  104562. */
  104563. this.onProgressObservable = new BABYLON.Observable();
  104564. /**
  104565. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  104566. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  104567. */
  104568. this.useDefaultLoadingScreen = true;
  104569. this._scene = scene;
  104570. }
  104571. /**
  104572. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  104573. * @param taskName defines the name of the new task
  104574. * @param meshesNames defines the name of meshes to load
  104575. * @param rootUrl defines the root url to use to locate files
  104576. * @param sceneFilename defines the filename of the scene file
  104577. * @returns a new {BABYLON.MeshAssetTask} object
  104578. */
  104579. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  104580. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  104581. this._tasks.push(task);
  104582. return task;
  104583. };
  104584. /**
  104585. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  104586. * @param taskName defines the name of the new task
  104587. * @param url defines the url of the file to load
  104588. * @returns a new {BABYLON.TextFileAssetTask} object
  104589. */
  104590. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  104591. var task = new TextFileAssetTask(taskName, url);
  104592. this._tasks.push(task);
  104593. return task;
  104594. };
  104595. /**
  104596. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  104597. * @param taskName defines the name of the new task
  104598. * @param url defines the url of the file to load
  104599. * @returns a new {BABYLON.BinaryFileAssetTask} object
  104600. */
  104601. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  104602. var task = new BinaryFileAssetTask(taskName, url);
  104603. this._tasks.push(task);
  104604. return task;
  104605. };
  104606. /**
  104607. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  104608. * @param taskName defines the name of the new task
  104609. * @param url defines the url of the file to load
  104610. * @returns a new {BABYLON.ImageAssetTask} object
  104611. */
  104612. AssetsManager.prototype.addImageTask = function (taskName, url) {
  104613. var task = new ImageAssetTask(taskName, url);
  104614. this._tasks.push(task);
  104615. return task;
  104616. };
  104617. /**
  104618. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  104619. * @param taskName defines the name of the new task
  104620. * @param url defines the url of the file to load
  104621. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104622. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  104623. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  104624. * @returns a new {BABYLON.TextureAssetTask} object
  104625. */
  104626. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  104627. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104628. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  104629. this._tasks.push(task);
  104630. return task;
  104631. };
  104632. /**
  104633. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  104634. * @param taskName defines the name of the new task
  104635. * @param url defines the url of the file to load
  104636. * @param extensions defines the extension to use to load the cube map (can be null)
  104637. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104638. * @param files defines the list of files to load (can be null)
  104639. * @returns a new {BABYLON.CubeTextureAssetTask} object
  104640. */
  104641. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  104642. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  104643. this._tasks.push(task);
  104644. return task;
  104645. };
  104646. /**
  104647. *
  104648. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  104649. * @param taskName defines the name of the new task
  104650. * @param url defines the url of the file to load
  104651. * @param size defines the size you want for the cubemap (can be null)
  104652. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104653. * @param generateHarmonics defines if you want to automatically generate (true by default)
  104654. * @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)
  104655. * @param reserved Internal use only
  104656. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  104657. */
  104658. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  104659. if (noMipmap === void 0) { noMipmap = false; }
  104660. if (generateHarmonics === void 0) { generateHarmonics = true; }
  104661. if (gammaSpace === void 0) { gammaSpace = false; }
  104662. if (reserved === void 0) { reserved = false; }
  104663. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  104664. this._tasks.push(task);
  104665. return task;
  104666. };
  104667. /**
  104668. * Remove a task from the assets manager.
  104669. * @param task the task to remove
  104670. */
  104671. AssetsManager.prototype.removeTask = function (task) {
  104672. var index = this._tasks.indexOf(task);
  104673. if (index > -1) {
  104674. this._tasks.splice(index, 1);
  104675. }
  104676. };
  104677. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  104678. this._waitingTasksCount--;
  104679. try {
  104680. if (this.onProgress) {
  104681. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  104682. }
  104683. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  104684. }
  104685. catch (e) {
  104686. BABYLON.Tools.Error("Error running progress callbacks.");
  104687. console.log(e);
  104688. }
  104689. if (this._waitingTasksCount === 0) {
  104690. try {
  104691. if (this.onFinish) {
  104692. this.onFinish(this._tasks);
  104693. }
  104694. // Let's remove successfull tasks
  104695. var currentTasks = this._tasks.slice();
  104696. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  104697. var task = currentTasks_1[_i];
  104698. if (task.taskState === AssetTaskState.DONE) {
  104699. var index = this._tasks.indexOf(task);
  104700. if (index > -1) {
  104701. this._tasks.splice(index, 1);
  104702. }
  104703. }
  104704. }
  104705. this.onTasksDoneObservable.notifyObservers(this._tasks);
  104706. }
  104707. catch (e) {
  104708. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  104709. console.log(e);
  104710. }
  104711. this._isLoading = false;
  104712. this._scene.getEngine().hideLoadingUI();
  104713. }
  104714. };
  104715. AssetsManager.prototype._runTask = function (task) {
  104716. var _this = this;
  104717. var done = function () {
  104718. try {
  104719. if (_this.onTaskSuccess) {
  104720. _this.onTaskSuccess(task);
  104721. }
  104722. _this.onTaskSuccessObservable.notifyObservers(task);
  104723. _this._decreaseWaitingTasksCount(task);
  104724. }
  104725. catch (e) {
  104726. error("Error executing task success callbacks", e);
  104727. }
  104728. };
  104729. var error = function (message, exception) {
  104730. task._setErrorObject(message, exception);
  104731. if (_this.onTaskError) {
  104732. _this.onTaskError(task);
  104733. }
  104734. _this.onTaskErrorObservable.notifyObservers(task);
  104735. _this._decreaseWaitingTasksCount(task);
  104736. };
  104737. task.run(this._scene, done, error);
  104738. };
  104739. /**
  104740. * Reset the {BABYLON.AssetsManager} and remove all tasks
  104741. * @return the current instance of the {BABYLON.AssetsManager}
  104742. */
  104743. AssetsManager.prototype.reset = function () {
  104744. this._isLoading = false;
  104745. this._tasks = new Array();
  104746. return this;
  104747. };
  104748. /**
  104749. * Start the loading process
  104750. * @return the current instance of the {BABYLON.AssetsManager}
  104751. */
  104752. AssetsManager.prototype.load = function () {
  104753. if (this._isLoading) {
  104754. return this;
  104755. }
  104756. this._isLoading = true;
  104757. this._waitingTasksCount = this._tasks.length;
  104758. this._totalTasksCount = this._tasks.length;
  104759. if (this._waitingTasksCount === 0) {
  104760. this._isLoading = false;
  104761. if (this.onFinish) {
  104762. this.onFinish(this._tasks);
  104763. }
  104764. this.onTasksDoneObservable.notifyObservers(this._tasks);
  104765. return this;
  104766. }
  104767. if (this.useDefaultLoadingScreen) {
  104768. this._scene.getEngine().displayLoadingUI();
  104769. }
  104770. for (var index = 0; index < this._tasks.length; index++) {
  104771. var task = this._tasks[index];
  104772. if (task.taskState === AssetTaskState.INIT) {
  104773. this._runTask(task);
  104774. }
  104775. }
  104776. return this;
  104777. };
  104778. return AssetsManager;
  104779. }());
  104780. BABYLON.AssetsManager = AssetsManager;
  104781. })(BABYLON || (BABYLON = {}));
  104782. //# sourceMappingURL=babylon.assetsManager.js.map
  104783. var BABYLON;
  104784. (function (BABYLON) {
  104785. var serializedGeometries = [];
  104786. var serializeGeometry = function (geometry, serializationGeometries) {
  104787. if (serializedGeometries[geometry.id]) {
  104788. return;
  104789. }
  104790. if (geometry.doNotSerialize) {
  104791. return;
  104792. }
  104793. if (geometry instanceof BABYLON.BoxGeometry) {
  104794. serializationGeometries.boxes.push(geometry.serialize());
  104795. }
  104796. else if (geometry instanceof BABYLON.SphereGeometry) {
  104797. serializationGeometries.spheres.push(geometry.serialize());
  104798. }
  104799. else if (geometry instanceof BABYLON.CylinderGeometry) {
  104800. serializationGeometries.cylinders.push(geometry.serialize());
  104801. }
  104802. else if (geometry instanceof BABYLON.TorusGeometry) {
  104803. serializationGeometries.toruses.push(geometry.serialize());
  104804. }
  104805. else if (geometry instanceof BABYLON.GroundGeometry) {
  104806. serializationGeometries.grounds.push(geometry.serialize());
  104807. }
  104808. else if (geometry instanceof BABYLON.Plane) {
  104809. serializationGeometries.planes.push(geometry.serialize());
  104810. }
  104811. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  104812. serializationGeometries.torusKnots.push(geometry.serialize());
  104813. }
  104814. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  104815. throw new Error("Unknown primitive type");
  104816. }
  104817. else {
  104818. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  104819. }
  104820. serializedGeometries[geometry.id] = true;
  104821. };
  104822. var serializeMesh = function (mesh, serializationScene) {
  104823. var serializationObject = {};
  104824. // Geometry
  104825. var geometry = mesh._geometry;
  104826. if (geometry) {
  104827. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  104828. // 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
  104829. serializeGeometry(geometry, serializationScene.geometries);
  104830. }
  104831. }
  104832. // Custom
  104833. if (mesh.serialize) {
  104834. mesh.serialize(serializationObject);
  104835. }
  104836. return serializationObject;
  104837. };
  104838. var finalizeSingleMesh = function (mesh, serializationObject) {
  104839. //only works if the mesh is already loaded
  104840. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  104841. //serialize material
  104842. if (mesh.material) {
  104843. if (mesh.material instanceof BABYLON.MultiMaterial) {
  104844. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  104845. serializationObject.materials = serializationObject.materials || [];
  104846. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104847. serializationObject.multiMaterials.push(mesh.material.serialize());
  104848. var _loop_1 = function (submaterial) {
  104849. if (submaterial) {
  104850. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  104851. serializationObject.materials.push(submaterial.serialize());
  104852. }
  104853. }
  104854. };
  104855. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  104856. var submaterial = _a[_i];
  104857. _loop_1(submaterial);
  104858. }
  104859. }
  104860. }
  104861. else {
  104862. serializationObject.materials = serializationObject.materials || [];
  104863. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104864. serializationObject.materials.push(mesh.material.serialize());
  104865. }
  104866. }
  104867. }
  104868. //serialize geometry
  104869. var geometry = mesh._geometry;
  104870. if (geometry) {
  104871. if (!serializationObject.geometries) {
  104872. serializationObject.geometries = {};
  104873. serializationObject.geometries.boxes = [];
  104874. serializationObject.geometries.spheres = [];
  104875. serializationObject.geometries.cylinders = [];
  104876. serializationObject.geometries.toruses = [];
  104877. serializationObject.geometries.grounds = [];
  104878. serializationObject.geometries.planes = [];
  104879. serializationObject.geometries.torusKnots = [];
  104880. serializationObject.geometries.vertexData = [];
  104881. }
  104882. serializeGeometry(geometry, serializationObject.geometries);
  104883. }
  104884. // Skeletons
  104885. if (mesh.skeleton) {
  104886. serializationObject.skeletons = serializationObject.skeletons || [];
  104887. serializationObject.skeletons.push(mesh.skeleton.serialize());
  104888. }
  104889. //serialize the actual mesh
  104890. serializationObject.meshes = serializationObject.meshes || [];
  104891. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104892. }
  104893. };
  104894. var SceneSerializer = /** @class */ (function () {
  104895. function SceneSerializer() {
  104896. }
  104897. SceneSerializer.ClearCache = function () {
  104898. serializedGeometries = [];
  104899. };
  104900. SceneSerializer.Serialize = function (scene) {
  104901. var serializationObject = {};
  104902. SceneSerializer.ClearCache();
  104903. // Scene
  104904. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  104905. serializationObject.autoClear = scene.autoClear;
  104906. serializationObject.clearColor = scene.clearColor.asArray();
  104907. serializationObject.ambientColor = scene.ambientColor.asArray();
  104908. serializationObject.gravity = scene.gravity.asArray();
  104909. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  104910. serializationObject.workerCollisions = scene.workerCollisions;
  104911. // Fog
  104912. if (scene.fogMode && scene.fogMode !== 0) {
  104913. serializationObject.fogMode = scene.fogMode;
  104914. serializationObject.fogColor = scene.fogColor.asArray();
  104915. serializationObject.fogStart = scene.fogStart;
  104916. serializationObject.fogEnd = scene.fogEnd;
  104917. serializationObject.fogDensity = scene.fogDensity;
  104918. }
  104919. //Physics
  104920. if (scene.isPhysicsEnabled()) {
  104921. var physicEngine = scene.getPhysicsEngine();
  104922. if (physicEngine) {
  104923. serializationObject.physicsEnabled = true;
  104924. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  104925. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  104926. }
  104927. }
  104928. // Metadata
  104929. if (scene.metadata) {
  104930. serializationObject.metadata = scene.metadata;
  104931. }
  104932. // Morph targets
  104933. serializationObject.morphTargetManagers = [];
  104934. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  104935. var abstractMesh = _a[_i];
  104936. var manager = abstractMesh.morphTargetManager;
  104937. if (manager) {
  104938. serializationObject.morphTargetManagers.push(manager.serialize());
  104939. }
  104940. }
  104941. // Lights
  104942. serializationObject.lights = [];
  104943. var index;
  104944. var light;
  104945. for (index = 0; index < scene.lights.length; index++) {
  104946. light = scene.lights[index];
  104947. if (!light.doNotSerialize) {
  104948. serializationObject.lights.push(light.serialize());
  104949. }
  104950. }
  104951. // Cameras
  104952. serializationObject.cameras = [];
  104953. for (index = 0; index < scene.cameras.length; index++) {
  104954. var camera = scene.cameras[index];
  104955. if (!camera.doNotSerialize) {
  104956. serializationObject.cameras.push(camera.serialize());
  104957. }
  104958. }
  104959. if (scene.activeCamera) {
  104960. serializationObject.activeCameraID = scene.activeCamera.id;
  104961. }
  104962. // Animations
  104963. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  104964. // Materials
  104965. serializationObject.materials = [];
  104966. serializationObject.multiMaterials = [];
  104967. var material;
  104968. for (index = 0; index < scene.materials.length; index++) {
  104969. material = scene.materials[index];
  104970. if (!material.doNotSerialize) {
  104971. serializationObject.materials.push(material.serialize());
  104972. }
  104973. }
  104974. // MultiMaterials
  104975. serializationObject.multiMaterials = [];
  104976. for (index = 0; index < scene.multiMaterials.length; index++) {
  104977. var multiMaterial = scene.multiMaterials[index];
  104978. serializationObject.multiMaterials.push(multiMaterial.serialize());
  104979. }
  104980. // Environment texture
  104981. if (scene.environmentTexture) {
  104982. serializationObject.environmentTexture = scene.environmentTexture.name;
  104983. }
  104984. // Skeletons
  104985. serializationObject.skeletons = [];
  104986. for (index = 0; index < scene.skeletons.length; index++) {
  104987. var skeleton = scene.skeletons[index];
  104988. if (!skeleton.doNotSerialize) {
  104989. serializationObject.skeletons.push(skeleton.serialize());
  104990. }
  104991. }
  104992. // Transform nodes
  104993. serializationObject.transformNodes = [];
  104994. for (index = 0; index < scene.transformNodes.length; index++) {
  104995. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  104996. }
  104997. // Geometries
  104998. serializationObject.geometries = {};
  104999. serializationObject.geometries.boxes = [];
  105000. serializationObject.geometries.spheres = [];
  105001. serializationObject.geometries.cylinders = [];
  105002. serializationObject.geometries.toruses = [];
  105003. serializationObject.geometries.grounds = [];
  105004. serializationObject.geometries.planes = [];
  105005. serializationObject.geometries.torusKnots = [];
  105006. serializationObject.geometries.vertexData = [];
  105007. serializedGeometries = [];
  105008. var geometries = scene.getGeometries();
  105009. for (index = 0; index < geometries.length; index++) {
  105010. var geometry = geometries[index];
  105011. if (geometry.isReady()) {
  105012. serializeGeometry(geometry, serializationObject.geometries);
  105013. }
  105014. }
  105015. // Meshes
  105016. serializationObject.meshes = [];
  105017. for (index = 0; index < scene.meshes.length; index++) {
  105018. var abstractMesh = scene.meshes[index];
  105019. if (abstractMesh instanceof BABYLON.Mesh) {
  105020. var mesh = abstractMesh;
  105021. if (!mesh.doNotSerialize) {
  105022. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  105023. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  105024. }
  105025. }
  105026. }
  105027. }
  105028. // Particles Systems
  105029. serializationObject.particleSystems = [];
  105030. for (index = 0; index < scene.particleSystems.length; index++) {
  105031. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  105032. }
  105033. // Action Manager
  105034. if (scene.actionManager) {
  105035. serializationObject.actions = scene.actionManager.serialize("scene");
  105036. }
  105037. // Components
  105038. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  105039. var component = _c[_b];
  105040. component.serialize(serializationObject);
  105041. }
  105042. return serializationObject;
  105043. };
  105044. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  105045. if (withParents === void 0) { withParents = false; }
  105046. if (withChildren === void 0) { withChildren = false; }
  105047. var serializationObject = {};
  105048. SceneSerializer.ClearCache();
  105049. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  105050. if (withParents || withChildren) {
  105051. //deliberate for loop! not for each, appended should be processed as well.
  105052. for (var i = 0; i < toSerialize.length; ++i) {
  105053. if (withChildren) {
  105054. toSerialize[i].getDescendants().forEach(function (node) {
  105055. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  105056. toSerialize.push(node);
  105057. }
  105058. });
  105059. }
  105060. //make sure the array doesn't contain the object already
  105061. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  105062. toSerialize.push(toSerialize[i].parent);
  105063. }
  105064. }
  105065. }
  105066. toSerialize.forEach(function (mesh) {
  105067. finalizeSingleMesh(mesh, serializationObject);
  105068. });
  105069. return serializationObject;
  105070. };
  105071. return SceneSerializer;
  105072. }());
  105073. BABYLON.SceneSerializer = SceneSerializer;
  105074. })(BABYLON || (BABYLON = {}));
  105075. //# sourceMappingURL=babylon.sceneSerializer.js.map
  105076. var BABYLON;
  105077. (function (BABYLON) {
  105078. /**
  105079. * Class used to generate realtime reflection / refraction cube textures
  105080. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  105081. */
  105082. var ReflectionProbe = /** @class */ (function () {
  105083. /**
  105084. * Creates a new reflection probe
  105085. * @param name defines the name of the probe
  105086. * @param size defines the texture resolution (for each face)
  105087. * @param scene defines the hosting scene
  105088. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  105089. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  105090. */
  105091. function ReflectionProbe(
  105092. /** defines the name of the probe */
  105093. name, size, scene, generateMipMaps, useFloat) {
  105094. if (generateMipMaps === void 0) { generateMipMaps = true; }
  105095. if (useFloat === void 0) { useFloat = false; }
  105096. var _this = this;
  105097. this.name = name;
  105098. this._viewMatrix = BABYLON.Matrix.Identity();
  105099. this._target = BABYLON.Vector3.Zero();
  105100. this._add = BABYLON.Vector3.Zero();
  105101. this._invertYAxis = false;
  105102. /** Gets or sets probe position (center of the cube map) */
  105103. this.position = BABYLON.Vector3.Zero();
  105104. this._scene = scene;
  105105. // Create the scene field if not exist.
  105106. if (!this._scene.reflectionProbes) {
  105107. this._scene.reflectionProbes = new Array();
  105108. }
  105109. this._scene.reflectionProbes.push(this);
  105110. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  105111. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  105112. switch (faceIndex) {
  105113. case 0:
  105114. _this._add.copyFromFloats(1, 0, 0);
  105115. break;
  105116. case 1:
  105117. _this._add.copyFromFloats(-1, 0, 0);
  105118. break;
  105119. case 2:
  105120. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  105121. break;
  105122. case 3:
  105123. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  105124. break;
  105125. case 4:
  105126. _this._add.copyFromFloats(0, 0, 1);
  105127. break;
  105128. case 5:
  105129. _this._add.copyFromFloats(0, 0, -1);
  105130. break;
  105131. }
  105132. if (_this._attachedMesh) {
  105133. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  105134. }
  105135. _this.position.addToRef(_this._add, _this._target);
  105136. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  105137. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  105138. scene._forcedViewPosition = _this.position;
  105139. });
  105140. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  105141. scene._forcedViewPosition = null;
  105142. scene.updateTransformMatrix(true);
  105143. });
  105144. if (scene.activeCamera) {
  105145. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  105146. }
  105147. }
  105148. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  105149. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  105150. get: function () {
  105151. return this._renderTargetTexture.samples;
  105152. },
  105153. set: function (value) {
  105154. this._renderTargetTexture.samples = value;
  105155. },
  105156. enumerable: true,
  105157. configurable: true
  105158. });
  105159. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  105160. /** Gets or sets the refresh rate to use (on every frame by default) */
  105161. get: function () {
  105162. return this._renderTargetTexture.refreshRate;
  105163. },
  105164. set: function (value) {
  105165. this._renderTargetTexture.refreshRate = value;
  105166. },
  105167. enumerable: true,
  105168. configurable: true
  105169. });
  105170. /**
  105171. * Gets the hosting scene
  105172. * @returns a Scene
  105173. */
  105174. ReflectionProbe.prototype.getScene = function () {
  105175. return this._scene;
  105176. };
  105177. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  105178. /** Gets the internal CubeTexture used to render to */
  105179. get: function () {
  105180. return this._renderTargetTexture;
  105181. },
  105182. enumerable: true,
  105183. configurable: true
  105184. });
  105185. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  105186. /** Gets the list of meshes to render */
  105187. get: function () {
  105188. return this._renderTargetTexture.renderList;
  105189. },
  105190. enumerable: true,
  105191. configurable: true
  105192. });
  105193. /**
  105194. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  105195. * @param mesh defines the mesh to attach to
  105196. */
  105197. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  105198. this._attachedMesh = mesh;
  105199. };
  105200. /**
  105201. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  105202. * @param renderingGroupId The rendering group id corresponding to its index
  105203. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  105204. */
  105205. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  105206. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  105207. };
  105208. /**
  105209. * Clean all associated resources
  105210. */
  105211. ReflectionProbe.prototype.dispose = function () {
  105212. var index = this._scene.reflectionProbes.indexOf(this);
  105213. if (index !== -1) {
  105214. // Remove from the scene if found
  105215. this._scene.reflectionProbes.splice(index, 1);
  105216. }
  105217. if (this._renderTargetTexture) {
  105218. this._renderTargetTexture.dispose();
  105219. this._renderTargetTexture = null;
  105220. }
  105221. };
  105222. return ReflectionProbe;
  105223. }());
  105224. BABYLON.ReflectionProbe = ReflectionProbe;
  105225. })(BABYLON || (BABYLON = {}));
  105226. //# sourceMappingURL=babylon.reflectionProbe.js.map
  105227. var BABYLON;
  105228. (function (BABYLON) {
  105229. /**
  105230. * Defines the layer scene component responsible to manage any layers
  105231. * in a given scene.
  105232. */
  105233. var LayerSceneComponent = /** @class */ (function () {
  105234. /**
  105235. * Creates a new instance of the component for the given scene
  105236. * @param scene Defines the scene to register the component in
  105237. */
  105238. function LayerSceneComponent(scene) {
  105239. /**
  105240. * The component name helpfull to identify the component in the list of scene components.
  105241. */
  105242. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  105243. this.scene = scene;
  105244. this._engine = scene.getEngine();
  105245. scene.layers = new Array();
  105246. }
  105247. /**
  105248. * Registers the component in a given scene
  105249. */
  105250. LayerSceneComponent.prototype.register = function () {
  105251. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  105252. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  105253. };
  105254. /**
  105255. * Rebuilds the elements related to this component in case of
  105256. * context lost for instance.
  105257. */
  105258. LayerSceneComponent.prototype.rebuild = function () {
  105259. var layers = this.scene.layers;
  105260. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  105261. var layer = layers_1[_i];
  105262. layer._rebuild();
  105263. }
  105264. };
  105265. /**
  105266. * Disposes the component and the associated ressources.
  105267. */
  105268. LayerSceneComponent.prototype.dispose = function () {
  105269. var layers = this.scene.layers;
  105270. while (layers.length) {
  105271. layers[0].dispose();
  105272. }
  105273. };
  105274. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  105275. var layers = this.scene.layers;
  105276. if (layers.length) {
  105277. this._engine.setDepthBuffer(false);
  105278. var cameraLayerMask = camera.layerMask;
  105279. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  105280. var layer = layers_2[_i];
  105281. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  105282. layer.render();
  105283. }
  105284. }
  105285. this._engine.setDepthBuffer(true);
  105286. }
  105287. };
  105288. LayerSceneComponent.prototype._drawBackground = function (camera) {
  105289. this._draw(camera, true);
  105290. };
  105291. LayerSceneComponent.prototype._drawForeground = function (camera) {
  105292. this._draw(camera, false);
  105293. };
  105294. return LayerSceneComponent;
  105295. }());
  105296. BABYLON.LayerSceneComponent = LayerSceneComponent;
  105297. })(BABYLON || (BABYLON = {}));
  105298. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  105299. var BABYLON;
  105300. (function (BABYLON) {
  105301. var Layer = /** @class */ (function () {
  105302. function Layer(name, imgUrl, scene, isBackground, color) {
  105303. this.name = name;
  105304. this.scale = new BABYLON.Vector2(1, 1);
  105305. this.offset = new BABYLON.Vector2(0, 0);
  105306. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  105307. this.layerMask = 0x0FFFFFFF;
  105308. this._vertexBuffers = {};
  105309. // Events
  105310. /**
  105311. * An event triggered when the layer is disposed.
  105312. */
  105313. this.onDisposeObservable = new BABYLON.Observable();
  105314. /**
  105315. * An event triggered before rendering the scene
  105316. */
  105317. this.onBeforeRenderObservable = new BABYLON.Observable();
  105318. /**
  105319. * An event triggered after rendering the scene
  105320. */
  105321. this.onAfterRenderObservable = new BABYLON.Observable();
  105322. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  105323. this.isBackground = isBackground === undefined ? true : isBackground;
  105324. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  105325. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  105326. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  105327. if (!layerComponent) {
  105328. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  105329. this._scene._addComponent(layerComponent);
  105330. }
  105331. this._scene.layers.push(this);
  105332. var engine = this._scene.getEngine();
  105333. // VBO
  105334. var vertices = [];
  105335. vertices.push(1, 1);
  105336. vertices.push(-1, 1);
  105337. vertices.push(-1, -1);
  105338. vertices.push(1, -1);
  105339. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  105340. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  105341. this._createIndexBuffer();
  105342. // Effects
  105343. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  105344. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  105345. }
  105346. Object.defineProperty(Layer.prototype, "onDispose", {
  105347. set: function (callback) {
  105348. if (this._onDisposeObserver) {
  105349. this.onDisposeObservable.remove(this._onDisposeObserver);
  105350. }
  105351. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  105352. },
  105353. enumerable: true,
  105354. configurable: true
  105355. });
  105356. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  105357. set: function (callback) {
  105358. if (this._onBeforeRenderObserver) {
  105359. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  105360. }
  105361. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  105362. },
  105363. enumerable: true,
  105364. configurable: true
  105365. });
  105366. Object.defineProperty(Layer.prototype, "onAfterRender", {
  105367. set: function (callback) {
  105368. if (this._onAfterRenderObserver) {
  105369. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  105370. }
  105371. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  105372. },
  105373. enumerable: true,
  105374. configurable: true
  105375. });
  105376. Layer.prototype._createIndexBuffer = function () {
  105377. var engine = this._scene.getEngine();
  105378. // Indices
  105379. var indices = [];
  105380. indices.push(0);
  105381. indices.push(1);
  105382. indices.push(2);
  105383. indices.push(0);
  105384. indices.push(2);
  105385. indices.push(3);
  105386. this._indexBuffer = engine.createIndexBuffer(indices);
  105387. };
  105388. /** @hidden */
  105389. Layer.prototype._rebuild = function () {
  105390. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105391. if (vb) {
  105392. vb._rebuild();
  105393. }
  105394. this._createIndexBuffer();
  105395. };
  105396. Layer.prototype.render = function () {
  105397. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  105398. // Check
  105399. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  105400. return;
  105401. var engine = this._scene.getEngine();
  105402. this.onBeforeRenderObservable.notifyObservers(this);
  105403. // Render
  105404. engine.enableEffect(currentEffect);
  105405. engine.setState(false);
  105406. // Texture
  105407. currentEffect.setTexture("textureSampler", this.texture);
  105408. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  105409. // Color
  105410. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  105411. // Scale / offset
  105412. currentEffect.setVector2("offset", this.offset);
  105413. currentEffect.setVector2("scale", this.scale);
  105414. // VBOs
  105415. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  105416. // Draw order
  105417. if (!this.alphaTest) {
  105418. engine.setAlphaMode(this.alphaBlendingMode);
  105419. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105420. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  105421. }
  105422. else {
  105423. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105424. }
  105425. this.onAfterRenderObservable.notifyObservers(this);
  105426. };
  105427. Layer.prototype.dispose = function () {
  105428. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105429. if (vertexBuffer) {
  105430. vertexBuffer.dispose();
  105431. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  105432. }
  105433. if (this._indexBuffer) {
  105434. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  105435. this._indexBuffer = null;
  105436. }
  105437. if (this.texture) {
  105438. this.texture.dispose();
  105439. this.texture = null;
  105440. }
  105441. // Remove from scene
  105442. var index = this._scene.layers.indexOf(this);
  105443. this._scene.layers.splice(index, 1);
  105444. // Callback
  105445. this.onDisposeObservable.notifyObservers(this);
  105446. this.onDisposeObservable.clear();
  105447. this.onAfterRenderObservable.clear();
  105448. this.onBeforeRenderObservable.clear();
  105449. };
  105450. return Layer;
  105451. }());
  105452. BABYLON.Layer = Layer;
  105453. })(BABYLON || (BABYLON = {}));
  105454. //# sourceMappingURL=babylon.layer.js.map
  105455. var BABYLON;
  105456. (function (BABYLON) {
  105457. var TextureTools = /** @class */ (function () {
  105458. function TextureTools() {
  105459. }
  105460. /**
  105461. * Uses the GPU to create a copy texture rescaled at a given size
  105462. * @param texture Texture to copy from
  105463. * @param width Desired width
  105464. * @param height Desired height
  105465. * @return Generated texture
  105466. */
  105467. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  105468. if (useBilinearMode === void 0) { useBilinearMode = true; }
  105469. var scene = texture.getScene();
  105470. var engine = scene.getEngine();
  105471. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  105472. rtt.wrapU = texture.wrapU;
  105473. rtt.wrapV = texture.wrapV;
  105474. rtt.uOffset = texture.uOffset;
  105475. rtt.vOffset = texture.vOffset;
  105476. rtt.uScale = texture.uScale;
  105477. rtt.vScale = texture.vScale;
  105478. rtt.uAng = texture.uAng;
  105479. rtt.vAng = texture.vAng;
  105480. rtt.wAng = texture.wAng;
  105481. rtt.coordinatesIndex = texture.coordinatesIndex;
  105482. rtt.level = texture.level;
  105483. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  105484. rtt._texture.isReady = false;
  105485. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105486. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105487. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  105488. passPostProcess.getEffect().executeWhenCompiled(function () {
  105489. passPostProcess.onApply = function (effect) {
  105490. effect.setTexture("textureSampler", texture);
  105491. };
  105492. var internalTexture = rtt.getInternalTexture();
  105493. if (internalTexture) {
  105494. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  105495. engine.unBindFramebuffer(internalTexture);
  105496. rtt.disposeFramebufferObjects();
  105497. passPostProcess.dispose();
  105498. internalTexture.isReady = true;
  105499. }
  105500. });
  105501. return rtt;
  105502. };
  105503. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  105504. if (!scene._environmentBRDFTexture) {
  105505. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105506. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105507. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105508. scene._environmentBRDFTexture = texture;
  105509. }
  105510. return scene._environmentBRDFTexture;
  105511. };
  105512. 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=";
  105513. return TextureTools;
  105514. }());
  105515. BABYLON.TextureTools = TextureTools;
  105516. })(BABYLON || (BABYLON = {}));
  105517. //# sourceMappingURL=babylon.textureTools.js.map
  105518. var BABYLON;
  105519. (function (BABYLON) {
  105520. var FramingBehavior = /** @class */ (function () {
  105521. function FramingBehavior() {
  105522. this._mode = FramingBehavior.FitFrustumSidesMode;
  105523. this._radiusScale = 1.0;
  105524. this._positionScale = 0.5;
  105525. this._defaultElevation = 0.3;
  105526. this._elevationReturnTime = 1500;
  105527. this._elevationReturnWaitTime = 1000;
  105528. this._zoomStopsAnimation = false;
  105529. this._framingTime = 1500;
  105530. this._isPointerDown = false;
  105531. this._lastInteractionTime = -Infinity;
  105532. // Framing control
  105533. this._animatables = new Array();
  105534. this._betaIsAnimating = false;
  105535. }
  105536. Object.defineProperty(FramingBehavior.prototype, "name", {
  105537. get: function () {
  105538. return "Framing";
  105539. },
  105540. enumerable: true,
  105541. configurable: true
  105542. });
  105543. Object.defineProperty(FramingBehavior.prototype, "mode", {
  105544. /**
  105545. * Gets current mode used by the behavior.
  105546. */
  105547. get: function () {
  105548. return this._mode;
  105549. },
  105550. /**
  105551. * Sets the current mode used by the behavior
  105552. */
  105553. set: function (mode) {
  105554. this._mode = mode;
  105555. },
  105556. enumerable: true,
  105557. configurable: true
  105558. });
  105559. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  105560. /**
  105561. * Gets the scale applied to the radius
  105562. */
  105563. get: function () {
  105564. return this._radiusScale;
  105565. },
  105566. /**
  105567. * Sets the scale applied to the radius (1 by default)
  105568. */
  105569. set: function (radius) {
  105570. this._radiusScale = radius;
  105571. },
  105572. enumerable: true,
  105573. configurable: true
  105574. });
  105575. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  105576. /**
  105577. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  105578. */
  105579. get: function () {
  105580. return this._positionScale;
  105581. },
  105582. /**
  105583. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  105584. */
  105585. set: function (scale) {
  105586. this._positionScale = scale;
  105587. },
  105588. enumerable: true,
  105589. configurable: true
  105590. });
  105591. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  105592. /**
  105593. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  105594. * behaviour is triggered, in radians.
  105595. */
  105596. get: function () {
  105597. return this._defaultElevation;
  105598. },
  105599. /**
  105600. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  105601. * behaviour is triggered, in radians.
  105602. */
  105603. set: function (elevation) {
  105604. this._defaultElevation = elevation;
  105605. },
  105606. enumerable: true,
  105607. configurable: true
  105608. });
  105609. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  105610. /**
  105611. * Gets the time (in milliseconds) taken to return to the default beta position.
  105612. * Negative value indicates camera should not return to default.
  105613. */
  105614. get: function () {
  105615. return this._elevationReturnTime;
  105616. },
  105617. /**
  105618. * Sets the time (in milliseconds) taken to return to the default beta position.
  105619. * Negative value indicates camera should not return to default.
  105620. */
  105621. set: function (speed) {
  105622. this._elevationReturnTime = speed;
  105623. },
  105624. enumerable: true,
  105625. configurable: true
  105626. });
  105627. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  105628. /**
  105629. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  105630. */
  105631. get: function () {
  105632. return this._elevationReturnWaitTime;
  105633. },
  105634. /**
  105635. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  105636. */
  105637. set: function (time) {
  105638. this._elevationReturnWaitTime = time;
  105639. },
  105640. enumerable: true,
  105641. configurable: true
  105642. });
  105643. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  105644. /**
  105645. * Gets the flag that indicates if user zooming should stop animation.
  105646. */
  105647. get: function () {
  105648. return this._zoomStopsAnimation;
  105649. },
  105650. /**
  105651. * Sets the flag that indicates if user zooming should stop animation.
  105652. */
  105653. set: function (flag) {
  105654. this._zoomStopsAnimation = flag;
  105655. },
  105656. enumerable: true,
  105657. configurable: true
  105658. });
  105659. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  105660. /**
  105661. * Gets the transition time when framing the mesh, in milliseconds
  105662. */
  105663. get: function () {
  105664. return this._framingTime;
  105665. },
  105666. /**
  105667. * Sets the transition time when framing the mesh, in milliseconds
  105668. */
  105669. set: function (time) {
  105670. this._framingTime = time;
  105671. },
  105672. enumerable: true,
  105673. configurable: true
  105674. });
  105675. FramingBehavior.prototype.init = function () {
  105676. // Do notihng
  105677. };
  105678. FramingBehavior.prototype.attach = function (camera) {
  105679. var _this = this;
  105680. this._attachedCamera = camera;
  105681. var scene = this._attachedCamera.getScene();
  105682. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  105683. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  105684. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  105685. _this._isPointerDown = true;
  105686. return;
  105687. }
  105688. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  105689. _this._isPointerDown = false;
  105690. }
  105691. });
  105692. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  105693. if (mesh) {
  105694. _this.zoomOnMesh(mesh);
  105695. }
  105696. });
  105697. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105698. // Stop the animation if there is user interaction and the animation should stop for this interaction
  105699. _this._applyUserInteraction();
  105700. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  105701. // back to the default position after a given timeout
  105702. _this._maintainCameraAboveGround();
  105703. });
  105704. };
  105705. FramingBehavior.prototype.detach = function () {
  105706. if (!this._attachedCamera) {
  105707. return;
  105708. }
  105709. var scene = this._attachedCamera.getScene();
  105710. if (this._onPrePointerObservableObserver) {
  105711. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  105712. }
  105713. if (this._onAfterCheckInputsObserver) {
  105714. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105715. }
  105716. if (this._onMeshTargetChangedObserver) {
  105717. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105718. }
  105719. this._attachedCamera = null;
  105720. };
  105721. /**
  105722. * Targets the given mesh and updates zoom level accordingly.
  105723. * @param mesh The mesh to target.
  105724. * @param radius Optional. If a cached radius position already exists, overrides default.
  105725. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105726. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105727. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105728. */
  105729. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  105730. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105731. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105732. mesh.computeWorldMatrix(true);
  105733. var boundingBox = mesh.getBoundingInfo().boundingBox;
  105734. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  105735. };
  105736. /**
  105737. * Targets the given mesh with its children and updates zoom level accordingly.
  105738. * @param mesh The mesh to target.
  105739. * @param radius Optional. If a cached radius position already exists, overrides default.
  105740. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105741. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105742. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105743. */
  105744. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  105745. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105746. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105747. mesh.computeWorldMatrix(true);
  105748. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  105749. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  105750. };
  105751. /**
  105752. * Targets the given meshes with their children and updates zoom level accordingly.
  105753. * @param meshes The mesh to target.
  105754. * @param radius Optional. If a cached radius position already exists, overrides default.
  105755. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105756. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105757. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105758. */
  105759. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  105760. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105761. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105762. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  105763. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  105764. for (var i = 0; i < meshes.length; i++) {
  105765. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  105766. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  105767. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  105768. }
  105769. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  105770. };
  105771. /**
  105772. * Targets the given mesh and updates zoom level accordingly.
  105773. * @param mesh The mesh to target.
  105774. * @param radius Optional. If a cached radius position already exists, overrides default.
  105775. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105776. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105777. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105778. */
  105779. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  105780. var _this = this;
  105781. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105782. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105783. var zoomTarget;
  105784. if (!this._attachedCamera) {
  105785. return;
  105786. }
  105787. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  105788. var bottom = minimumWorld.y;
  105789. var top = maximumWorld.y;
  105790. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  105791. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  105792. if (focusOnOriginXZ) {
  105793. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  105794. }
  105795. else {
  105796. var centerWorld = minimumWorld.add(radiusWorld);
  105797. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  105798. }
  105799. if (!this._vectorTransition) {
  105800. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  105801. }
  105802. this._betaIsAnimating = true;
  105803. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  105804. if (animatable) {
  105805. this._animatables.push(animatable);
  105806. }
  105807. // sets the radius and lower radius bounds
  105808. // Small delta ensures camera is not always at lower zoom limit.
  105809. var radius = 0;
  105810. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  105811. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  105812. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  105813. radius = position;
  105814. }
  105815. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105816. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  105817. if (this._attachedCamera.lowerRadiusLimit === null) {
  105818. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  105819. }
  105820. }
  105821. // Set sensibilities
  105822. var extend = maximumWorld.subtract(minimumWorld).length();
  105823. this._attachedCamera.panningSensibility = 5000 / extend;
  105824. this._attachedCamera.wheelPrecision = 100 / radius;
  105825. // transition to new radius
  105826. if (!this._radiusTransition) {
  105827. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105828. }
  105829. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  105830. _this.stopAllAnimations();
  105831. if (onAnimationEnd) {
  105832. onAnimationEnd();
  105833. }
  105834. if (_this._attachedCamera) {
  105835. _this._attachedCamera.storeState();
  105836. }
  105837. });
  105838. if (animatable) {
  105839. this._animatables.push(animatable);
  105840. }
  105841. };
  105842. /**
  105843. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  105844. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  105845. * frustum width.
  105846. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  105847. * to fully enclose the mesh in the viewing frustum.
  105848. */
  105849. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  105850. var size = maximumWorld.subtract(minimumWorld);
  105851. var boxVectorGlobalDiagonal = size.length();
  105852. var frustumSlope = this._getFrustumSlope();
  105853. // Formula for setting distance
  105854. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  105855. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  105856. // Horizon distance
  105857. var radius = radiusWithoutFraming * this._radiusScale;
  105858. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  105859. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  105860. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  105861. var camera = this._attachedCamera;
  105862. if (!camera) {
  105863. return 0;
  105864. }
  105865. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105866. // Don't exceed the requested limit
  105867. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  105868. }
  105869. // Don't exceed the upper radius limit
  105870. if (camera.upperRadiusLimit) {
  105871. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  105872. }
  105873. return distance;
  105874. };
  105875. /**
  105876. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  105877. * is automatically returned to its default position (expected to be above ground plane).
  105878. */
  105879. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  105880. var _this = this;
  105881. if (this._elevationReturnTime < 0) {
  105882. return;
  105883. }
  105884. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  105885. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  105886. var limitBeta = Math.PI * 0.5;
  105887. // Bring the camera back up if below the ground plane
  105888. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  105889. this._betaIsAnimating = true;
  105890. //Transition to new position
  105891. this.stopAllAnimations();
  105892. if (!this._betaTransition) {
  105893. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105894. }
  105895. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  105896. _this._clearAnimationLocks();
  105897. _this.stopAllAnimations();
  105898. });
  105899. if (animatabe) {
  105900. this._animatables.push(animatabe);
  105901. }
  105902. }
  105903. };
  105904. /**
  105905. * Returns the frustum slope based on the canvas ratio and camera FOV
  105906. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  105907. */
  105908. FramingBehavior.prototype._getFrustumSlope = function () {
  105909. // Calculate the viewport ratio
  105910. // Aspect Ratio is Height/Width.
  105911. var camera = this._attachedCamera;
  105912. if (!camera) {
  105913. return BABYLON.Vector2.Zero();
  105914. }
  105915. var engine = camera.getScene().getEngine();
  105916. var aspectRatio = engine.getAspectRatio(camera);
  105917. // Camera FOV is the vertical field of view (top-bottom) in radians.
  105918. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  105919. var frustumSlopeY = Math.tan(camera.fov / 2);
  105920. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  105921. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  105922. // along the forward vector.
  105923. var frustumSlopeX = frustumSlopeY * aspectRatio;
  105924. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  105925. };
  105926. /**
  105927. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  105928. */
  105929. FramingBehavior.prototype._clearAnimationLocks = function () {
  105930. this._betaIsAnimating = false;
  105931. };
  105932. /**
  105933. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  105934. */
  105935. FramingBehavior.prototype._applyUserInteraction = function () {
  105936. if (this.isUserIsMoving) {
  105937. this._lastInteractionTime = BABYLON.Tools.Now;
  105938. this.stopAllAnimations();
  105939. this._clearAnimationLocks();
  105940. }
  105941. };
  105942. /**
  105943. * Stops and removes all animations that have been applied to the camera
  105944. */
  105945. FramingBehavior.prototype.stopAllAnimations = function () {
  105946. if (this._attachedCamera) {
  105947. this._attachedCamera.animations = [];
  105948. }
  105949. while (this._animatables.length) {
  105950. if (this._animatables[0]) {
  105951. this._animatables[0].onAnimationEnd = null;
  105952. this._animatables[0].stop();
  105953. }
  105954. this._animatables.shift();
  105955. }
  105956. };
  105957. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  105958. /**
  105959. * Gets a value indicating if the user is moving the camera
  105960. */
  105961. get: function () {
  105962. if (!this._attachedCamera) {
  105963. return false;
  105964. }
  105965. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  105966. this._attachedCamera.inertialBetaOffset !== 0 ||
  105967. this._attachedCamera.inertialRadiusOffset !== 0 ||
  105968. this._attachedCamera.inertialPanningX !== 0 ||
  105969. this._attachedCamera.inertialPanningY !== 0 ||
  105970. this._isPointerDown;
  105971. },
  105972. enumerable: true,
  105973. configurable: true
  105974. });
  105975. /**
  105976. * The easing function used by animations
  105977. */
  105978. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  105979. /**
  105980. * The easing mode used by animations
  105981. */
  105982. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  105983. // Statics
  105984. /**
  105985. * The camera can move all the way towards the mesh.
  105986. */
  105987. FramingBehavior.IgnoreBoundsSizeMode = 0;
  105988. /**
  105989. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  105990. */
  105991. FramingBehavior.FitFrustumSidesMode = 1;
  105992. return FramingBehavior;
  105993. }());
  105994. BABYLON.FramingBehavior = FramingBehavior;
  105995. })(BABYLON || (BABYLON = {}));
  105996. //# sourceMappingURL=babylon.framingBehavior.js.map
  105997. var BABYLON;
  105998. (function (BABYLON) {
  105999. /**
  106000. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  106001. */
  106002. var BouncingBehavior = /** @class */ (function () {
  106003. function BouncingBehavior() {
  106004. /**
  106005. * The duration of the animation, in milliseconds
  106006. */
  106007. this.transitionDuration = 450;
  106008. /**
  106009. * Length of the distance animated by the transition when lower radius is reached
  106010. */
  106011. this.lowerRadiusTransitionRange = 2;
  106012. /**
  106013. * Length of the distance animated by the transition when upper radius is reached
  106014. */
  106015. this.upperRadiusTransitionRange = -2;
  106016. this._autoTransitionRange = false;
  106017. // Animations
  106018. this._radiusIsAnimating = false;
  106019. this._radiusBounceTransition = null;
  106020. this._animatables = new Array();
  106021. }
  106022. Object.defineProperty(BouncingBehavior.prototype, "name", {
  106023. get: function () {
  106024. return "Bouncing";
  106025. },
  106026. enumerable: true,
  106027. configurable: true
  106028. });
  106029. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  106030. /**
  106031. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  106032. */
  106033. get: function () {
  106034. return this._autoTransitionRange;
  106035. },
  106036. /**
  106037. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  106038. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  106039. */
  106040. set: function (value) {
  106041. var _this = this;
  106042. if (this._autoTransitionRange === value) {
  106043. return;
  106044. }
  106045. this._autoTransitionRange = value;
  106046. var camera = this._attachedCamera;
  106047. if (!camera) {
  106048. return;
  106049. }
  106050. if (value) {
  106051. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  106052. if (!mesh) {
  106053. return;
  106054. }
  106055. mesh.computeWorldMatrix(true);
  106056. var diagonal = mesh.getBoundingInfo().diagonalLength;
  106057. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  106058. _this.upperRadiusTransitionRange = diagonal * 0.05;
  106059. });
  106060. }
  106061. else if (this._onMeshTargetChangedObserver) {
  106062. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  106063. }
  106064. },
  106065. enumerable: true,
  106066. configurable: true
  106067. });
  106068. BouncingBehavior.prototype.init = function () {
  106069. // Do notihng
  106070. };
  106071. BouncingBehavior.prototype.attach = function (camera) {
  106072. var _this = this;
  106073. this._attachedCamera = camera;
  106074. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  106075. if (!_this._attachedCamera) {
  106076. return;
  106077. }
  106078. // Add the bounce animation to the lower radius limit
  106079. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  106080. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  106081. }
  106082. // Add the bounce animation to the upper radius limit
  106083. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  106084. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  106085. }
  106086. });
  106087. };
  106088. BouncingBehavior.prototype.detach = function () {
  106089. if (!this._attachedCamera) {
  106090. return;
  106091. }
  106092. if (this._onAfterCheckInputsObserver) {
  106093. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  106094. }
  106095. if (this._onMeshTargetChangedObserver) {
  106096. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  106097. }
  106098. this._attachedCamera = null;
  106099. };
  106100. /**
  106101. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  106102. * @param radiusLimit The limit to check against.
  106103. * @return Bool to indicate if at limit.
  106104. */
  106105. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  106106. if (!this._attachedCamera) {
  106107. return false;
  106108. }
  106109. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  106110. return true;
  106111. }
  106112. return false;
  106113. };
  106114. /**
  106115. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  106116. * @param radiusDelta The delta by which to animate to. Can be negative.
  106117. */
  106118. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  106119. var _this = this;
  106120. if (!this._attachedCamera) {
  106121. return;
  106122. }
  106123. if (!this._radiusBounceTransition) {
  106124. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  106125. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  106126. }
  106127. // Prevent zoom until bounce has completed
  106128. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  106129. this._attachedCamera.wheelPrecision = Infinity;
  106130. this._attachedCamera.inertialRadiusOffset = 0;
  106131. // Animate to the radius limit
  106132. this.stopAllAnimations();
  106133. this._radiusIsAnimating = true;
  106134. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  106135. if (animatable) {
  106136. this._animatables.push(animatable);
  106137. }
  106138. };
  106139. /**
  106140. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  106141. */
  106142. BouncingBehavior.prototype._clearAnimationLocks = function () {
  106143. this._radiusIsAnimating = false;
  106144. if (this._attachedCamera) {
  106145. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  106146. }
  106147. };
  106148. /**
  106149. * Stops and removes all animations that have been applied to the camera
  106150. */
  106151. BouncingBehavior.prototype.stopAllAnimations = function () {
  106152. if (this._attachedCamera) {
  106153. this._attachedCamera.animations = [];
  106154. }
  106155. while (this._animatables.length) {
  106156. this._animatables[0].onAnimationEnd = null;
  106157. this._animatables[0].stop();
  106158. this._animatables.shift();
  106159. }
  106160. };
  106161. /**
  106162. * The easing function used by animations
  106163. */
  106164. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  106165. /**
  106166. * The easing mode used by animations
  106167. */
  106168. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  106169. return BouncingBehavior;
  106170. }());
  106171. BABYLON.BouncingBehavior = BouncingBehavior;
  106172. })(BABYLON || (BABYLON = {}));
  106173. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  106174. var BABYLON;
  106175. (function (BABYLON) {
  106176. var AutoRotationBehavior = /** @class */ (function () {
  106177. function AutoRotationBehavior() {
  106178. this._zoomStopsAnimation = false;
  106179. this._idleRotationSpeed = 0.05;
  106180. this._idleRotationWaitTime = 2000;
  106181. this._idleRotationSpinupTime = 2000;
  106182. this._isPointerDown = false;
  106183. this._lastFrameTime = null;
  106184. this._lastInteractionTime = -Infinity;
  106185. this._cameraRotationSpeed = 0;
  106186. this._lastFrameRadius = 0;
  106187. }
  106188. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  106189. get: function () {
  106190. return "AutoRotation";
  106191. },
  106192. enumerable: true,
  106193. configurable: true
  106194. });
  106195. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  106196. /**
  106197. * Gets the flag that indicates if user zooming should stop animation.
  106198. */
  106199. get: function () {
  106200. return this._zoomStopsAnimation;
  106201. },
  106202. /**
  106203. * Sets the flag that indicates if user zooming should stop animation.
  106204. */
  106205. set: function (flag) {
  106206. this._zoomStopsAnimation = flag;
  106207. },
  106208. enumerable: true,
  106209. configurable: true
  106210. });
  106211. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  106212. /**
  106213. * Gets the default speed at which the camera rotates around the model.
  106214. */
  106215. get: function () {
  106216. return this._idleRotationSpeed;
  106217. },
  106218. /**
  106219. * Sets the default speed at which the camera rotates around the model.
  106220. */
  106221. set: function (speed) {
  106222. this._idleRotationSpeed = speed;
  106223. },
  106224. enumerable: true,
  106225. configurable: true
  106226. });
  106227. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  106228. /**
  106229. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  106230. */
  106231. get: function () {
  106232. return this._idleRotationWaitTime;
  106233. },
  106234. /**
  106235. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  106236. */
  106237. set: function (time) {
  106238. this._idleRotationWaitTime = time;
  106239. },
  106240. enumerable: true,
  106241. configurable: true
  106242. });
  106243. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  106244. /**
  106245. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  106246. */
  106247. get: function () {
  106248. return this._idleRotationSpinupTime;
  106249. },
  106250. /**
  106251. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  106252. */
  106253. set: function (time) {
  106254. this._idleRotationSpinupTime = time;
  106255. },
  106256. enumerable: true,
  106257. configurable: true
  106258. });
  106259. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  106260. /**
  106261. * Gets a value indicating if the camera is currently rotating because of this behavior
  106262. */
  106263. get: function () {
  106264. return Math.abs(this._cameraRotationSpeed) > 0;
  106265. },
  106266. enumerable: true,
  106267. configurable: true
  106268. });
  106269. AutoRotationBehavior.prototype.init = function () {
  106270. // Do notihng
  106271. };
  106272. AutoRotationBehavior.prototype.attach = function (camera) {
  106273. var _this = this;
  106274. this._attachedCamera = camera;
  106275. var scene = this._attachedCamera.getScene();
  106276. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  106277. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  106278. _this._isPointerDown = true;
  106279. return;
  106280. }
  106281. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  106282. _this._isPointerDown = false;
  106283. }
  106284. });
  106285. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  106286. var now = BABYLON.Tools.Now;
  106287. var dt = 0;
  106288. if (_this._lastFrameTime != null) {
  106289. dt = now - _this._lastFrameTime;
  106290. }
  106291. _this._lastFrameTime = now;
  106292. // Stop the animation if there is user interaction and the animation should stop for this interaction
  106293. _this._applyUserInteraction();
  106294. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  106295. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  106296. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  106297. // Step camera rotation by rotation speed
  106298. if (_this._attachedCamera) {
  106299. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  106300. }
  106301. });
  106302. };
  106303. AutoRotationBehavior.prototype.detach = function () {
  106304. if (!this._attachedCamera) {
  106305. return;
  106306. }
  106307. var scene = this._attachedCamera.getScene();
  106308. if (this._onPrePointerObservableObserver) {
  106309. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  106310. }
  106311. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  106312. this._attachedCamera = null;
  106313. };
  106314. /**
  106315. * Returns true if user is scrolling.
  106316. * @return true if user is scrolling.
  106317. */
  106318. AutoRotationBehavior.prototype._userIsZooming = function () {
  106319. if (!this._attachedCamera) {
  106320. return false;
  106321. }
  106322. return this._attachedCamera.inertialRadiusOffset !== 0;
  106323. };
  106324. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  106325. if (!this._attachedCamera) {
  106326. return false;
  106327. }
  106328. var zoomHasHitLimit = false;
  106329. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  106330. zoomHasHitLimit = true;
  106331. }
  106332. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  106333. this._lastFrameRadius = this._attachedCamera.radius;
  106334. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  106335. };
  106336. /**
  106337. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  106338. */
  106339. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  106340. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  106341. this._lastInteractionTime = BABYLON.Tools.Now;
  106342. }
  106343. };
  106344. // Tools
  106345. AutoRotationBehavior.prototype._userIsMoving = function () {
  106346. if (!this._attachedCamera) {
  106347. return false;
  106348. }
  106349. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  106350. this._attachedCamera.inertialBetaOffset !== 0 ||
  106351. this._attachedCamera.inertialRadiusOffset !== 0 ||
  106352. this._attachedCamera.inertialPanningX !== 0 ||
  106353. this._attachedCamera.inertialPanningY !== 0 ||
  106354. this._isPointerDown;
  106355. };
  106356. return AutoRotationBehavior;
  106357. }());
  106358. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  106359. })(BABYLON || (BABYLON = {}));
  106360. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  106361. var BABYLON;
  106362. (function (BABYLON) {
  106363. var NullEngineOptions = /** @class */ (function () {
  106364. function NullEngineOptions() {
  106365. this.renderWidth = 512;
  106366. this.renderHeight = 256;
  106367. this.textureSize = 512;
  106368. this.deterministicLockstep = false;
  106369. this.lockstepMaxSteps = 4;
  106370. }
  106371. return NullEngineOptions;
  106372. }());
  106373. BABYLON.NullEngineOptions = NullEngineOptions;
  106374. /**
  106375. * The null engine class provides support for headless version of babylon.js.
  106376. * This can be used in server side scenario or for testing purposes
  106377. */
  106378. var NullEngine = /** @class */ (function (_super) {
  106379. __extends(NullEngine, _super);
  106380. function NullEngine(options) {
  106381. if (options === void 0) { options = new NullEngineOptions(); }
  106382. var _this = _super.call(this, null) || this;
  106383. if (options.deterministicLockstep === undefined) {
  106384. options.deterministicLockstep = false;
  106385. }
  106386. if (options.lockstepMaxSteps === undefined) {
  106387. options.lockstepMaxSteps = 4;
  106388. }
  106389. _this._options = options;
  106390. // Init caps
  106391. // We consider we are on a webgl1 capable device
  106392. _this._caps = new BABYLON.EngineCapabilities();
  106393. _this._caps.maxTexturesImageUnits = 16;
  106394. _this._caps.maxVertexTextureImageUnits = 16;
  106395. _this._caps.maxTextureSize = 512;
  106396. _this._caps.maxCubemapTextureSize = 512;
  106397. _this._caps.maxRenderTextureSize = 512;
  106398. _this._caps.maxVertexAttribs = 16;
  106399. _this._caps.maxVaryingVectors = 16;
  106400. _this._caps.maxFragmentUniformVectors = 16;
  106401. _this._caps.maxVertexUniformVectors = 16;
  106402. // Extensions
  106403. _this._caps.standardDerivatives = false;
  106404. _this._caps.astc = null;
  106405. _this._caps.s3tc = null;
  106406. _this._caps.pvrtc = null;
  106407. _this._caps.etc1 = null;
  106408. _this._caps.etc2 = null;
  106409. _this._caps.textureAnisotropicFilterExtension = null;
  106410. _this._caps.maxAnisotropy = 0;
  106411. _this._caps.uintIndices = false;
  106412. _this._caps.fragmentDepthSupported = false;
  106413. _this._caps.highPrecisionShaderSupported = true;
  106414. _this._caps.colorBufferFloat = false;
  106415. _this._caps.textureFloat = false;
  106416. _this._caps.textureFloatLinearFiltering = false;
  106417. _this._caps.textureFloatRender = false;
  106418. _this._caps.textureHalfFloat = false;
  106419. _this._caps.textureHalfFloatLinearFiltering = false;
  106420. _this._caps.textureHalfFloatRender = false;
  106421. _this._caps.textureLOD = false;
  106422. _this._caps.drawBuffersExtension = false;
  106423. _this._caps.depthTextureExtension = false;
  106424. _this._caps.vertexArrayObject = false;
  106425. _this._caps.instancedArrays = false;
  106426. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  106427. // Wrappers
  106428. if (typeof URL === "undefined") {
  106429. URL = {
  106430. createObjectURL: function () { },
  106431. revokeObjectURL: function () { }
  106432. };
  106433. }
  106434. if (typeof Blob === "undefined") {
  106435. Blob = function () { };
  106436. }
  106437. return _this;
  106438. }
  106439. NullEngine.prototype.isDeterministicLockStep = function () {
  106440. return this._options.deterministicLockstep;
  106441. };
  106442. NullEngine.prototype.getLockstepMaxSteps = function () {
  106443. return this._options.lockstepMaxSteps;
  106444. };
  106445. NullEngine.prototype.getHardwareScalingLevel = function () {
  106446. return 1.0;
  106447. };
  106448. NullEngine.prototype.createVertexBuffer = function (vertices) {
  106449. return {
  106450. capacity: 0,
  106451. references: 1,
  106452. is32Bits: false
  106453. };
  106454. };
  106455. NullEngine.prototype.createIndexBuffer = function (indices) {
  106456. return {
  106457. capacity: 0,
  106458. references: 1,
  106459. is32Bits: false
  106460. };
  106461. };
  106462. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  106463. if (stencil === void 0) { stencil = false; }
  106464. };
  106465. NullEngine.prototype.getRenderWidth = function (useScreen) {
  106466. if (useScreen === void 0) { useScreen = false; }
  106467. if (!useScreen && this._currentRenderTarget) {
  106468. return this._currentRenderTarget.width;
  106469. }
  106470. return this._options.renderWidth;
  106471. };
  106472. NullEngine.prototype.getRenderHeight = function (useScreen) {
  106473. if (useScreen === void 0) { useScreen = false; }
  106474. if (!useScreen && this._currentRenderTarget) {
  106475. return this._currentRenderTarget.height;
  106476. }
  106477. return this._options.renderHeight;
  106478. };
  106479. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  106480. this._cachedViewport = viewport;
  106481. };
  106482. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  106483. return {
  106484. transformFeedback: null,
  106485. __SPECTOR_rebuildProgram: null
  106486. };
  106487. };
  106488. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  106489. return [];
  106490. };
  106491. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  106492. return [];
  106493. };
  106494. NullEngine.prototype.bindSamplers = function (effect) {
  106495. this._currentEffect = null;
  106496. };
  106497. NullEngine.prototype.enableEffect = function (effect) {
  106498. this._currentEffect = effect;
  106499. if (effect.onBind) {
  106500. effect.onBind(effect);
  106501. }
  106502. if (effect._onBindObservable) {
  106503. effect._onBindObservable.notifyObservers(effect);
  106504. }
  106505. };
  106506. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  106507. if (zOffset === void 0) { zOffset = 0; }
  106508. if (reverseSide === void 0) { reverseSide = false; }
  106509. };
  106510. NullEngine.prototype.setIntArray = function (uniform, array) {
  106511. };
  106512. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  106513. };
  106514. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  106515. };
  106516. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  106517. };
  106518. NullEngine.prototype.setFloatArray = function (uniform, array) {
  106519. };
  106520. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  106521. };
  106522. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  106523. };
  106524. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  106525. };
  106526. NullEngine.prototype.setArray = function (uniform, array) {
  106527. };
  106528. NullEngine.prototype.setArray2 = function (uniform, array) {
  106529. };
  106530. NullEngine.prototype.setArray3 = function (uniform, array) {
  106531. };
  106532. NullEngine.prototype.setArray4 = function (uniform, array) {
  106533. };
  106534. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  106535. };
  106536. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  106537. };
  106538. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  106539. };
  106540. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  106541. };
  106542. NullEngine.prototype.setFloat = function (uniform, value) {
  106543. };
  106544. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  106545. };
  106546. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  106547. };
  106548. NullEngine.prototype.setBool = function (uniform, bool) {
  106549. };
  106550. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  106551. };
  106552. NullEngine.prototype.setColor3 = function (uniform, color3) {
  106553. };
  106554. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  106555. };
  106556. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  106557. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  106558. if (this._alphaMode === mode) {
  106559. return;
  106560. }
  106561. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  106562. if (!noDepthWriteChange) {
  106563. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  106564. }
  106565. this._alphaMode = mode;
  106566. };
  106567. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  106568. };
  106569. NullEngine.prototype.wipeCaches = function (bruteForce) {
  106570. if (this.preventCacheWipeBetweenFrames) {
  106571. return;
  106572. }
  106573. this.resetTextureCache();
  106574. this._currentEffect = null;
  106575. if (bruteForce) {
  106576. this._currentProgram = null;
  106577. this._stencilState.reset();
  106578. this._depthCullingState.reset();
  106579. this._alphaState.reset();
  106580. }
  106581. this._cachedVertexBuffers = null;
  106582. this._cachedIndexBuffer = null;
  106583. this._cachedEffectForVertexBuffers = null;
  106584. };
  106585. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  106586. };
  106587. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  106588. };
  106589. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  106590. };
  106591. /** @hidden */
  106592. NullEngine.prototype._createTexture = function () {
  106593. return {};
  106594. };
  106595. /** @hidden */
  106596. NullEngine.prototype._releaseTexture = function (texture) {
  106597. };
  106598. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  106599. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  106600. if (onLoad === void 0) { onLoad = null; }
  106601. if (onError === void 0) { onError = null; }
  106602. if (buffer === void 0) { buffer = null; }
  106603. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  106604. var url = String(urlArg);
  106605. texture.url = url;
  106606. texture.generateMipMaps = !noMipmap;
  106607. texture.samplingMode = samplingMode;
  106608. texture.invertY = invertY;
  106609. texture.baseWidth = this._options.textureSize;
  106610. texture.baseHeight = this._options.textureSize;
  106611. texture.width = this._options.textureSize;
  106612. texture.height = this._options.textureSize;
  106613. if (format) {
  106614. texture.format = format;
  106615. }
  106616. texture.isReady = true;
  106617. if (onLoad) {
  106618. onLoad();
  106619. }
  106620. this._internalTexturesCache.push(texture);
  106621. return texture;
  106622. };
  106623. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  106624. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  106625. if (options !== undefined && typeof options === "object") {
  106626. fullOptions.generateMipMaps = options.generateMipMaps;
  106627. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  106628. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  106629. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  106630. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  106631. }
  106632. else {
  106633. fullOptions.generateMipMaps = options;
  106634. fullOptions.generateDepthBuffer = true;
  106635. fullOptions.generateStencilBuffer = false;
  106636. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  106637. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  106638. }
  106639. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  106640. var width = size.width || size;
  106641. var height = size.height || size;
  106642. texture._depthStencilBuffer = {};
  106643. texture._framebuffer = {};
  106644. texture.baseWidth = width;
  106645. texture.baseHeight = height;
  106646. texture.width = width;
  106647. texture.height = height;
  106648. texture.isReady = true;
  106649. texture.samples = 1;
  106650. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  106651. texture.samplingMode = fullOptions.samplingMode;
  106652. texture.type = fullOptions.type;
  106653. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  106654. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  106655. this._internalTexturesCache.push(texture);
  106656. return texture;
  106657. };
  106658. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  106659. texture.samplingMode = samplingMode;
  106660. };
  106661. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  106662. if (this._currentRenderTarget) {
  106663. this.unBindFramebuffer(this._currentRenderTarget);
  106664. }
  106665. this._currentRenderTarget = texture;
  106666. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  106667. if (this._cachedViewport && !forceFullscreenViewport) {
  106668. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  106669. }
  106670. };
  106671. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  106672. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  106673. this._currentRenderTarget = null;
  106674. if (onBeforeUnbind) {
  106675. if (texture._MSAAFramebuffer) {
  106676. this._currentFramebuffer = texture._framebuffer;
  106677. }
  106678. onBeforeUnbind();
  106679. }
  106680. this._currentFramebuffer = null;
  106681. };
  106682. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  106683. var vbo = {
  106684. capacity: 1,
  106685. references: 1,
  106686. is32Bits: false
  106687. };
  106688. return vbo;
  106689. };
  106690. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  106691. if (premulAlpha === void 0) { premulAlpha = false; }
  106692. };
  106693. /**
  106694. * @hidden
  106695. * Get the current error code of the webGL context
  106696. * @returns the error code
  106697. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  106698. */
  106699. NullEngine.prototype.getError = function () {
  106700. return 0;
  106701. };
  106702. /** @hidden */
  106703. NullEngine.prototype._getUnpackAlignement = function () {
  106704. return 1;
  106705. };
  106706. /** @hidden */
  106707. NullEngine.prototype._unpackFlipY = function (value) {
  106708. };
  106709. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  106710. if (offset === void 0) { offset = 0; }
  106711. };
  106712. /**
  106713. * Updates a dynamic vertex buffer.
  106714. * @param vertexBuffer the vertex buffer to update
  106715. * @param data the data used to update the vertex buffer
  106716. * @param byteOffset the byte offset of the data (optional)
  106717. * @param byteLength the byte length of the data (optional)
  106718. */
  106719. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  106720. };
  106721. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  106722. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  106723. this._boundTexturesCache[this._activeChannel] = texture;
  106724. return true;
  106725. }
  106726. return false;
  106727. };
  106728. /** @hidden */
  106729. NullEngine.prototype._bindTexture = function (channel, texture) {
  106730. if (channel < 0) {
  106731. return;
  106732. }
  106733. this._bindTextureDirectly(0, texture);
  106734. };
  106735. /** @hidden */
  106736. NullEngine.prototype._releaseBuffer = function (buffer) {
  106737. buffer.references--;
  106738. if (buffer.references === 0) {
  106739. return true;
  106740. }
  106741. return false;
  106742. };
  106743. NullEngine.prototype.releaseEffects = function () {
  106744. };
  106745. NullEngine.prototype.displayLoadingUI = function () {
  106746. };
  106747. NullEngine.prototype.hideLoadingUI = function () {
  106748. };
  106749. /** @hidden */
  106750. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  106751. if (faceIndex === void 0) { faceIndex = 0; }
  106752. if (lod === void 0) { lod = 0; }
  106753. };
  106754. /** @hidden */
  106755. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  106756. if (faceIndex === void 0) { faceIndex = 0; }
  106757. if (lod === void 0) { lod = 0; }
  106758. };
  106759. /** @hidden */
  106760. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  106761. if (faceIndex === void 0) { faceIndex = 0; }
  106762. if (lod === void 0) { lod = 0; }
  106763. };
  106764. /** @hidden */
  106765. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  106766. if (faceIndex === void 0) { faceIndex = 0; }
  106767. if (lod === void 0) { lod = 0; }
  106768. };
  106769. return NullEngine;
  106770. }(BABYLON.Engine));
  106771. BABYLON.NullEngine = NullEngine;
  106772. })(BABYLON || (BABYLON = {}));
  106773. //# sourceMappingURL=babylon.nullEngine.js.map
  106774. var BABYLON;
  106775. (function (BABYLON) {
  106776. /**
  106777. * This class can be used to get instrumentation data from a Babylon engine
  106778. */
  106779. var EngineInstrumentation = /** @class */ (function () {
  106780. function EngineInstrumentation(engine) {
  106781. this.engine = engine;
  106782. this._captureGPUFrameTime = false;
  106783. this._gpuFrameTime = new BABYLON.PerfCounter();
  106784. this._captureShaderCompilationTime = false;
  106785. this._shaderCompilationTime = new BABYLON.PerfCounter();
  106786. // Observers
  106787. this._onBeginFrameObserver = null;
  106788. this._onEndFrameObserver = null;
  106789. this._onBeforeShaderCompilationObserver = null;
  106790. this._onAfterShaderCompilationObserver = null;
  106791. }
  106792. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  106793. // Properties
  106794. /**
  106795. * Gets the perf counter used for GPU frame time
  106796. */
  106797. get: function () {
  106798. return this._gpuFrameTime;
  106799. },
  106800. enumerable: true,
  106801. configurable: true
  106802. });
  106803. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  106804. /**
  106805. * Gets the GPU frame time capture status
  106806. */
  106807. get: function () {
  106808. return this._captureGPUFrameTime;
  106809. },
  106810. /**
  106811. * Enable or disable the GPU frame time capture
  106812. */
  106813. set: function (value) {
  106814. var _this = this;
  106815. if (value === this._captureGPUFrameTime) {
  106816. return;
  106817. }
  106818. this._captureGPUFrameTime = value;
  106819. if (value) {
  106820. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  106821. if (!_this._gpuFrameTimeToken) {
  106822. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  106823. }
  106824. });
  106825. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  106826. if (!_this._gpuFrameTimeToken) {
  106827. return;
  106828. }
  106829. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  106830. if (time > -1) {
  106831. _this._gpuFrameTimeToken = null;
  106832. _this._gpuFrameTime.fetchNewFrame();
  106833. _this._gpuFrameTime.addCount(time, true);
  106834. }
  106835. });
  106836. }
  106837. else {
  106838. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106839. this._onBeginFrameObserver = null;
  106840. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106841. this._onEndFrameObserver = null;
  106842. }
  106843. },
  106844. enumerable: true,
  106845. configurable: true
  106846. });
  106847. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  106848. /**
  106849. * Gets the perf counter used for shader compilation time
  106850. */
  106851. get: function () {
  106852. return this._shaderCompilationTime;
  106853. },
  106854. enumerable: true,
  106855. configurable: true
  106856. });
  106857. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  106858. /**
  106859. * Gets the shader compilation time capture status
  106860. */
  106861. get: function () {
  106862. return this._captureShaderCompilationTime;
  106863. },
  106864. /**
  106865. * Enable or disable the shader compilation time capture
  106866. */
  106867. set: function (value) {
  106868. var _this = this;
  106869. if (value === this._captureShaderCompilationTime) {
  106870. return;
  106871. }
  106872. this._captureShaderCompilationTime = value;
  106873. if (value) {
  106874. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  106875. _this._shaderCompilationTime.fetchNewFrame();
  106876. _this._shaderCompilationTime.beginMonitoring();
  106877. });
  106878. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  106879. _this._shaderCompilationTime.endMonitoring();
  106880. });
  106881. }
  106882. else {
  106883. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106884. this._onBeforeShaderCompilationObserver = null;
  106885. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106886. this._onAfterShaderCompilationObserver = null;
  106887. }
  106888. },
  106889. enumerable: true,
  106890. configurable: true
  106891. });
  106892. EngineInstrumentation.prototype.dispose = function () {
  106893. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106894. this._onBeginFrameObserver = null;
  106895. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106896. this._onEndFrameObserver = null;
  106897. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106898. this._onBeforeShaderCompilationObserver = null;
  106899. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106900. this._onAfterShaderCompilationObserver = null;
  106901. this.engine = null;
  106902. };
  106903. return EngineInstrumentation;
  106904. }());
  106905. BABYLON.EngineInstrumentation = EngineInstrumentation;
  106906. })(BABYLON || (BABYLON = {}));
  106907. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  106908. var BABYLON;
  106909. (function (BABYLON) {
  106910. /**
  106911. * This class can be used to get instrumentation data from a Babylon engine
  106912. */
  106913. var SceneInstrumentation = /** @class */ (function () {
  106914. function SceneInstrumentation(scene) {
  106915. var _this = this;
  106916. this.scene = scene;
  106917. this._captureActiveMeshesEvaluationTime = false;
  106918. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  106919. this._captureRenderTargetsRenderTime = false;
  106920. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  106921. this._captureFrameTime = false;
  106922. this._frameTime = new BABYLON.PerfCounter();
  106923. this._captureRenderTime = false;
  106924. this._renderTime = new BABYLON.PerfCounter();
  106925. this._captureInterFrameTime = false;
  106926. this._interFrameTime = new BABYLON.PerfCounter();
  106927. this._captureParticlesRenderTime = false;
  106928. this._particlesRenderTime = new BABYLON.PerfCounter();
  106929. this._captureSpritesRenderTime = false;
  106930. this._spritesRenderTime = new BABYLON.PerfCounter();
  106931. this._capturePhysicsTime = false;
  106932. this._physicsTime = new BABYLON.PerfCounter();
  106933. this._captureAnimationsTime = false;
  106934. this._animationsTime = new BABYLON.PerfCounter();
  106935. this._captureCameraRenderTime = false;
  106936. this._cameraRenderTime = new BABYLON.PerfCounter();
  106937. // Observers
  106938. this._onBeforeActiveMeshesEvaluationObserver = null;
  106939. this._onAfterActiveMeshesEvaluationObserver = null;
  106940. this._onBeforeRenderTargetsRenderObserver = null;
  106941. this._onAfterRenderTargetsRenderObserver = null;
  106942. this._onAfterRenderObserver = null;
  106943. this._onBeforeDrawPhaseObserver = null;
  106944. this._onAfterDrawPhaseObserver = null;
  106945. this._onBeforeAnimationsObserver = null;
  106946. this._onBeforeParticlesRenderingObserver = null;
  106947. this._onAfterParticlesRenderingObserver = null;
  106948. this._onBeforeSpritesRenderingObserver = null;
  106949. this._onAfterSpritesRenderingObserver = null;
  106950. this._onBeforePhysicsObserver = null;
  106951. this._onAfterPhysicsObserver = null;
  106952. this._onAfterAnimationsObserver = null;
  106953. this._onBeforeCameraRenderObserver = null;
  106954. this._onAfterCameraRenderObserver = null;
  106955. // Before render
  106956. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  106957. if (_this._captureActiveMeshesEvaluationTime) {
  106958. _this._activeMeshesEvaluationTime.fetchNewFrame();
  106959. }
  106960. if (_this._captureRenderTargetsRenderTime) {
  106961. _this._renderTargetsRenderTime.fetchNewFrame();
  106962. }
  106963. if (_this._captureFrameTime) {
  106964. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  106965. _this._frameTime.beginMonitoring();
  106966. }
  106967. if (_this._captureInterFrameTime) {
  106968. _this._interFrameTime.endMonitoring();
  106969. }
  106970. if (_this._captureParticlesRenderTime) {
  106971. _this._particlesRenderTime.fetchNewFrame();
  106972. }
  106973. if (_this._captureSpritesRenderTime) {
  106974. _this._spritesRenderTime.fetchNewFrame();
  106975. }
  106976. if (_this._captureAnimationsTime) {
  106977. _this._animationsTime.beginMonitoring();
  106978. }
  106979. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  106980. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  106981. });
  106982. // After render
  106983. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  106984. if (_this._captureFrameTime) {
  106985. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  106986. _this._frameTime.endMonitoring();
  106987. }
  106988. if (_this._captureRenderTime) {
  106989. _this._renderTime.endMonitoring(false);
  106990. }
  106991. if (_this._captureInterFrameTime) {
  106992. _this._interFrameTime.beginMonitoring();
  106993. }
  106994. });
  106995. }
  106996. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  106997. // Properties
  106998. /**
  106999. * Gets the perf counter used for active meshes evaluation time
  107000. */
  107001. get: function () {
  107002. return this._activeMeshesEvaluationTime;
  107003. },
  107004. enumerable: true,
  107005. configurable: true
  107006. });
  107007. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  107008. /**
  107009. * Gets the active meshes evaluation time capture status
  107010. */
  107011. get: function () {
  107012. return this._captureActiveMeshesEvaluationTime;
  107013. },
  107014. /**
  107015. * Enable or disable the active meshes evaluation time capture
  107016. */
  107017. set: function (value) {
  107018. var _this = this;
  107019. if (value === this._captureActiveMeshesEvaluationTime) {
  107020. return;
  107021. }
  107022. this._captureActiveMeshesEvaluationTime = value;
  107023. if (value) {
  107024. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  107025. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  107026. _this._activeMeshesEvaluationTime.beginMonitoring();
  107027. });
  107028. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  107029. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  107030. _this._activeMeshesEvaluationTime.endMonitoring();
  107031. });
  107032. }
  107033. else {
  107034. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  107035. this._onBeforeActiveMeshesEvaluationObserver = null;
  107036. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  107037. this._onAfterActiveMeshesEvaluationObserver = null;
  107038. }
  107039. },
  107040. enumerable: true,
  107041. configurable: true
  107042. });
  107043. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  107044. /**
  107045. * Gets the perf counter used for render targets render time
  107046. */
  107047. get: function () {
  107048. return this._renderTargetsRenderTime;
  107049. },
  107050. enumerable: true,
  107051. configurable: true
  107052. });
  107053. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  107054. /**
  107055. * Gets the render targets render time capture status
  107056. */
  107057. get: function () {
  107058. return this._captureRenderTargetsRenderTime;
  107059. },
  107060. /**
  107061. * Enable or disable the render targets render time capture
  107062. */
  107063. set: function (value) {
  107064. var _this = this;
  107065. if (value === this._captureRenderTargetsRenderTime) {
  107066. return;
  107067. }
  107068. this._captureRenderTargetsRenderTime = value;
  107069. if (value) {
  107070. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  107071. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  107072. _this._renderTargetsRenderTime.beginMonitoring();
  107073. });
  107074. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  107075. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  107076. _this._renderTargetsRenderTime.endMonitoring(false);
  107077. });
  107078. }
  107079. else {
  107080. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  107081. this._onBeforeRenderTargetsRenderObserver = null;
  107082. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  107083. this._onAfterRenderTargetsRenderObserver = null;
  107084. }
  107085. },
  107086. enumerable: true,
  107087. configurable: true
  107088. });
  107089. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  107090. /**
  107091. * Gets the perf counter used for particles render time
  107092. */
  107093. get: function () {
  107094. return this._particlesRenderTime;
  107095. },
  107096. enumerable: true,
  107097. configurable: true
  107098. });
  107099. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  107100. /**
  107101. * Gets the particles render time capture status
  107102. */
  107103. get: function () {
  107104. return this._captureParticlesRenderTime;
  107105. },
  107106. /**
  107107. * Enable or disable the particles render time capture
  107108. */
  107109. set: function (value) {
  107110. var _this = this;
  107111. if (value === this._captureParticlesRenderTime) {
  107112. return;
  107113. }
  107114. this._captureParticlesRenderTime = value;
  107115. if (value) {
  107116. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  107117. BABYLON.Tools.StartPerformanceCounter("Particles");
  107118. _this._particlesRenderTime.beginMonitoring();
  107119. });
  107120. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  107121. BABYLON.Tools.EndPerformanceCounter("Particles");
  107122. _this._particlesRenderTime.endMonitoring(false);
  107123. });
  107124. }
  107125. else {
  107126. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  107127. this._onBeforeParticlesRenderingObserver = null;
  107128. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  107129. this._onAfterParticlesRenderingObserver = null;
  107130. }
  107131. },
  107132. enumerable: true,
  107133. configurable: true
  107134. });
  107135. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  107136. /**
  107137. * Gets the perf counter used for sprites render time
  107138. */
  107139. get: function () {
  107140. return this._spritesRenderTime;
  107141. },
  107142. enumerable: true,
  107143. configurable: true
  107144. });
  107145. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  107146. /**
  107147. * Gets the sprites render time capture status
  107148. */
  107149. get: function () {
  107150. return this._captureSpritesRenderTime;
  107151. },
  107152. /**
  107153. * Enable or disable the sprites render time capture
  107154. */
  107155. set: function (value) {
  107156. var _this = this;
  107157. if (value === this._captureSpritesRenderTime) {
  107158. return;
  107159. }
  107160. this._captureSpritesRenderTime = value;
  107161. if (!this.scene.spriteManagers) {
  107162. return;
  107163. }
  107164. if (value) {
  107165. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  107166. BABYLON.Tools.StartPerformanceCounter("Sprites");
  107167. _this._spritesRenderTime.beginMonitoring();
  107168. });
  107169. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  107170. BABYLON.Tools.EndPerformanceCounter("Sprites");
  107171. _this._spritesRenderTime.endMonitoring(false);
  107172. });
  107173. }
  107174. else {
  107175. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  107176. this._onBeforeSpritesRenderingObserver = null;
  107177. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  107178. this._onAfterSpritesRenderingObserver = null;
  107179. }
  107180. },
  107181. enumerable: true,
  107182. configurable: true
  107183. });
  107184. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  107185. /**
  107186. * Gets the perf counter used for physics time
  107187. */
  107188. get: function () {
  107189. return this._physicsTime;
  107190. },
  107191. enumerable: true,
  107192. configurable: true
  107193. });
  107194. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  107195. /**
  107196. * Gets the physics time capture status
  107197. */
  107198. get: function () {
  107199. return this._capturePhysicsTime;
  107200. },
  107201. /**
  107202. * Enable or disable the physics time capture
  107203. */
  107204. set: function (value) {
  107205. var _this = this;
  107206. if (value === this._capturePhysicsTime) {
  107207. return;
  107208. }
  107209. if (!this.scene.onBeforePhysicsObservable) {
  107210. return;
  107211. }
  107212. this._capturePhysicsTime = value;
  107213. if (value) {
  107214. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  107215. BABYLON.Tools.StartPerformanceCounter("Physics");
  107216. _this._physicsTime.beginMonitoring();
  107217. });
  107218. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  107219. BABYLON.Tools.EndPerformanceCounter("Physics");
  107220. _this._physicsTime.endMonitoring();
  107221. });
  107222. }
  107223. else {
  107224. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  107225. this._onBeforePhysicsObserver = null;
  107226. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  107227. this._onAfterPhysicsObserver = null;
  107228. }
  107229. },
  107230. enumerable: true,
  107231. configurable: true
  107232. });
  107233. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  107234. /**
  107235. * Gets the perf counter used for animations time
  107236. */
  107237. get: function () {
  107238. return this._animationsTime;
  107239. },
  107240. enumerable: true,
  107241. configurable: true
  107242. });
  107243. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  107244. /**
  107245. * Gets the animations time capture status
  107246. */
  107247. get: function () {
  107248. return this._captureAnimationsTime;
  107249. },
  107250. /**
  107251. * Enable or disable the animations time capture
  107252. */
  107253. set: function (value) {
  107254. var _this = this;
  107255. if (value === this._captureAnimationsTime) {
  107256. return;
  107257. }
  107258. this._captureAnimationsTime = value;
  107259. if (value) {
  107260. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  107261. _this._animationsTime.endMonitoring();
  107262. });
  107263. }
  107264. else {
  107265. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  107266. this._onAfterAnimationsObserver = null;
  107267. }
  107268. },
  107269. enumerable: true,
  107270. configurable: true
  107271. });
  107272. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  107273. /**
  107274. * Gets the perf counter used for frame time capture
  107275. */
  107276. get: function () {
  107277. return this._frameTime;
  107278. },
  107279. enumerable: true,
  107280. configurable: true
  107281. });
  107282. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  107283. /**
  107284. * Gets the frame time capture status
  107285. */
  107286. get: function () {
  107287. return this._captureFrameTime;
  107288. },
  107289. /**
  107290. * Enable or disable the frame time capture
  107291. */
  107292. set: function (value) {
  107293. this._captureFrameTime = value;
  107294. },
  107295. enumerable: true,
  107296. configurable: true
  107297. });
  107298. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  107299. /**
  107300. * Gets the perf counter used for inter-frames time capture
  107301. */
  107302. get: function () {
  107303. return this._interFrameTime;
  107304. },
  107305. enumerable: true,
  107306. configurable: true
  107307. });
  107308. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  107309. /**
  107310. * Gets the inter-frames time capture status
  107311. */
  107312. get: function () {
  107313. return this._captureInterFrameTime;
  107314. },
  107315. /**
  107316. * Enable or disable the inter-frames time capture
  107317. */
  107318. set: function (value) {
  107319. this._captureInterFrameTime = value;
  107320. },
  107321. enumerable: true,
  107322. configurable: true
  107323. });
  107324. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  107325. /**
  107326. * Gets the perf counter used for render time capture
  107327. */
  107328. get: function () {
  107329. return this._renderTime;
  107330. },
  107331. enumerable: true,
  107332. configurable: true
  107333. });
  107334. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  107335. /**
  107336. * Gets the render time capture status
  107337. */
  107338. get: function () {
  107339. return this._captureRenderTime;
  107340. },
  107341. /**
  107342. * Enable or disable the render time capture
  107343. */
  107344. set: function (value) {
  107345. var _this = this;
  107346. if (value === this._captureRenderTime) {
  107347. return;
  107348. }
  107349. this._captureRenderTime = value;
  107350. if (value) {
  107351. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  107352. _this._renderTime.beginMonitoring();
  107353. BABYLON.Tools.StartPerformanceCounter("Main render");
  107354. });
  107355. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  107356. _this._renderTime.endMonitoring(false);
  107357. BABYLON.Tools.EndPerformanceCounter("Main render");
  107358. });
  107359. }
  107360. else {
  107361. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  107362. this._onBeforeDrawPhaseObserver = null;
  107363. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  107364. this._onAfterDrawPhaseObserver = null;
  107365. }
  107366. },
  107367. enumerable: true,
  107368. configurable: true
  107369. });
  107370. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  107371. /**
  107372. * Gets the perf counter used for camera render time capture
  107373. */
  107374. get: function () {
  107375. return this._cameraRenderTime;
  107376. },
  107377. enumerable: true,
  107378. configurable: true
  107379. });
  107380. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  107381. /**
  107382. * Gets the camera render time capture status
  107383. */
  107384. get: function () {
  107385. return this._captureCameraRenderTime;
  107386. },
  107387. /**
  107388. * Enable or disable the camera render time capture
  107389. */
  107390. set: function (value) {
  107391. var _this = this;
  107392. if (value === this._captureCameraRenderTime) {
  107393. return;
  107394. }
  107395. this._captureCameraRenderTime = value;
  107396. if (value) {
  107397. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  107398. _this._cameraRenderTime.beginMonitoring();
  107399. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  107400. });
  107401. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  107402. _this._cameraRenderTime.endMonitoring(false);
  107403. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  107404. });
  107405. }
  107406. else {
  107407. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  107408. this._onBeforeCameraRenderObserver = null;
  107409. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  107410. this._onAfterCameraRenderObserver = null;
  107411. }
  107412. },
  107413. enumerable: true,
  107414. configurable: true
  107415. });
  107416. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  107417. /**
  107418. * Gets the perf counter used for draw calls
  107419. */
  107420. get: function () {
  107421. return this.scene.getEngine()._drawCalls;
  107422. },
  107423. enumerable: true,
  107424. configurable: true
  107425. });
  107426. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  107427. /**
  107428. * Gets the perf counter used for texture collisions
  107429. */
  107430. get: function () {
  107431. return this.scene.getEngine()._textureCollisions;
  107432. },
  107433. enumerable: true,
  107434. configurable: true
  107435. });
  107436. SceneInstrumentation.prototype.dispose = function () {
  107437. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  107438. this._onAfterRenderObserver = null;
  107439. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  107440. this._onBeforeActiveMeshesEvaluationObserver = null;
  107441. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  107442. this._onAfterActiveMeshesEvaluationObserver = null;
  107443. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  107444. this._onBeforeRenderTargetsRenderObserver = null;
  107445. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  107446. this._onAfterRenderTargetsRenderObserver = null;
  107447. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  107448. this._onBeforeAnimationsObserver = null;
  107449. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  107450. this._onBeforeParticlesRenderingObserver = null;
  107451. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  107452. this._onAfterParticlesRenderingObserver = null;
  107453. if (this._onBeforeSpritesRenderingObserver) {
  107454. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  107455. this._onBeforeSpritesRenderingObserver = null;
  107456. }
  107457. if (this._onAfterSpritesRenderingObserver) {
  107458. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  107459. this._onAfterSpritesRenderingObserver = null;
  107460. }
  107461. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  107462. this._onBeforeDrawPhaseObserver = null;
  107463. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  107464. this._onAfterDrawPhaseObserver = null;
  107465. if (this._onBeforePhysicsObserver) {
  107466. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  107467. this._onBeforePhysicsObserver = null;
  107468. }
  107469. if (this._onAfterPhysicsObserver) {
  107470. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  107471. this._onAfterPhysicsObserver = null;
  107472. }
  107473. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  107474. this._onAfterAnimationsObserver = null;
  107475. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  107476. this._onBeforeCameraRenderObserver = null;
  107477. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  107478. this._onAfterCameraRenderObserver = null;
  107479. this.scene = null;
  107480. };
  107481. return SceneInstrumentation;
  107482. }());
  107483. BABYLON.SceneInstrumentation = SceneInstrumentation;
  107484. })(BABYLON || (BABYLON = {}));
  107485. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  107486. var BABYLON;
  107487. (function (BABYLON) {
  107488. /**
  107489. * @hidden
  107490. **/
  107491. var _TimeToken = /** @class */ (function () {
  107492. function _TimeToken() {
  107493. this._timeElapsedQueryEnded = false;
  107494. }
  107495. return _TimeToken;
  107496. }());
  107497. BABYLON._TimeToken = _TimeToken;
  107498. })(BABYLON || (BABYLON = {}));
  107499. //# sourceMappingURL=babylon.timeToken.js.map
  107500. var BABYLON;
  107501. (function (BABYLON) {
  107502. /**
  107503. * Background material defines definition.
  107504. * @hidden Mainly internal Use
  107505. */
  107506. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  107507. __extends(BackgroundMaterialDefines, _super);
  107508. /**
  107509. * Constructor of the defines.
  107510. */
  107511. function BackgroundMaterialDefines() {
  107512. var _this = _super.call(this) || this;
  107513. /**
  107514. * True if the diffuse texture is in use.
  107515. */
  107516. _this.DIFFUSE = false;
  107517. /**
  107518. * The direct UV channel to use.
  107519. */
  107520. _this.DIFFUSEDIRECTUV = 0;
  107521. /**
  107522. * True if the diffuse texture is in gamma space.
  107523. */
  107524. _this.GAMMADIFFUSE = false;
  107525. /**
  107526. * True if the diffuse texture has opacity in the alpha channel.
  107527. */
  107528. _this.DIFFUSEHASALPHA = false;
  107529. /**
  107530. * True if you want the material to fade to transparent at grazing angle.
  107531. */
  107532. _this.OPACITYFRESNEL = false;
  107533. /**
  107534. * True if an extra blur needs to be added in the reflection.
  107535. */
  107536. _this.REFLECTIONBLUR = false;
  107537. /**
  107538. * True if you want the material to fade to reflection at grazing angle.
  107539. */
  107540. _this.REFLECTIONFRESNEL = false;
  107541. /**
  107542. * True if you want the material to falloff as far as you move away from the scene center.
  107543. */
  107544. _this.REFLECTIONFALLOFF = false;
  107545. /**
  107546. * False if the current Webgl implementation does not support the texture lod extension.
  107547. */
  107548. _this.TEXTURELODSUPPORT = false;
  107549. /**
  107550. * True to ensure the data are premultiplied.
  107551. */
  107552. _this.PREMULTIPLYALPHA = false;
  107553. /**
  107554. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  107555. */
  107556. _this.USERGBCOLOR = false;
  107557. /**
  107558. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  107559. * stays aligned with the desired configuration.
  107560. */
  107561. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  107562. /**
  107563. * True to add noise in order to reduce the banding effect.
  107564. */
  107565. _this.NOISE = false;
  107566. /**
  107567. * is the reflection texture in BGR color scheme?
  107568. * Mainly used to solve a bug in ios10 video tag
  107569. */
  107570. _this.REFLECTIONBGR = false;
  107571. _this.IMAGEPROCESSING = false;
  107572. _this.VIGNETTE = false;
  107573. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  107574. _this.VIGNETTEBLENDMODEOPAQUE = false;
  107575. _this.TONEMAPPING = false;
  107576. _this.TONEMAPPING_ACES = false;
  107577. _this.CONTRAST = false;
  107578. _this.COLORCURVES = false;
  107579. _this.COLORGRADING = false;
  107580. _this.COLORGRADING3D = false;
  107581. _this.SAMPLER3DGREENDEPTH = false;
  107582. _this.SAMPLER3DBGRMAP = false;
  107583. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  107584. _this.EXPOSURE = false;
  107585. // Reflection.
  107586. _this.REFLECTION = false;
  107587. _this.REFLECTIONMAP_3D = false;
  107588. _this.REFLECTIONMAP_SPHERICAL = false;
  107589. _this.REFLECTIONMAP_PLANAR = false;
  107590. _this.REFLECTIONMAP_CUBIC = false;
  107591. _this.REFLECTIONMAP_PROJECTION = false;
  107592. _this.REFLECTIONMAP_SKYBOX = false;
  107593. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  107594. _this.REFLECTIONMAP_EXPLICIT = false;
  107595. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  107596. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  107597. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  107598. _this.INVERTCUBICMAP = false;
  107599. _this.REFLECTIONMAP_OPPOSITEZ = false;
  107600. _this.LODINREFLECTIONALPHA = false;
  107601. _this.GAMMAREFLECTION = false;
  107602. _this.RGBDREFLECTION = false;
  107603. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  107604. // Default BJS.
  107605. _this.MAINUV1 = false;
  107606. _this.MAINUV2 = false;
  107607. _this.UV1 = false;
  107608. _this.UV2 = false;
  107609. _this.CLIPPLANE = false;
  107610. _this.CLIPPLANE2 = false;
  107611. _this.CLIPPLANE3 = false;
  107612. _this.CLIPPLANE4 = false;
  107613. _this.POINTSIZE = false;
  107614. _this.FOG = false;
  107615. _this.NORMAL = false;
  107616. _this.NUM_BONE_INFLUENCERS = 0;
  107617. _this.BonesPerMesh = 0;
  107618. _this.INSTANCES = false;
  107619. _this.SHADOWFLOAT = false;
  107620. _this.rebuild();
  107621. return _this;
  107622. }
  107623. return BackgroundMaterialDefines;
  107624. }(BABYLON.MaterialDefines));
  107625. /**
  107626. * Background material used to create an efficient environement around your scene.
  107627. */
  107628. var BackgroundMaterial = /** @class */ (function (_super) {
  107629. __extends(BackgroundMaterial, _super);
  107630. /**
  107631. * Instantiates a Background Material in the given scene
  107632. * @param name The friendly name of the material
  107633. * @param scene The scene to add the material to
  107634. */
  107635. function BackgroundMaterial(name, scene) {
  107636. var _this = _super.call(this, name, scene) || this;
  107637. /**
  107638. * Key light Color (multiply against the environement texture)
  107639. */
  107640. _this.primaryColor = BABYLON.Color3.White();
  107641. _this._primaryColorShadowLevel = 0;
  107642. _this._primaryColorHighlightLevel = 0;
  107643. /**
  107644. * Reflection Texture used in the material.
  107645. * Should be author in a specific way for the best result (refer to the documentation).
  107646. */
  107647. _this.reflectionTexture = null;
  107648. /**
  107649. * Reflection Texture level of blur.
  107650. *
  107651. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  107652. * texture twice.
  107653. */
  107654. _this.reflectionBlur = 0;
  107655. /**
  107656. * Diffuse Texture used in the material.
  107657. * Should be author in a specific way for the best result (refer to the documentation).
  107658. */
  107659. _this.diffuseTexture = null;
  107660. _this._shadowLights = null;
  107661. /**
  107662. * Specify the list of lights casting shadow on the material.
  107663. * All scene shadow lights will be included if null.
  107664. */
  107665. _this.shadowLights = null;
  107666. /**
  107667. * Helps adjusting the shadow to a softer level if required.
  107668. * 0 means black shadows and 1 means no shadows.
  107669. */
  107670. _this.shadowLevel = 0;
  107671. /**
  107672. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  107673. * It is usually zero but might be interesting to modify according to your setup.
  107674. */
  107675. _this.sceneCenter = BABYLON.Vector3.Zero();
  107676. /**
  107677. * This helps specifying that the material is falling off to the sky box at grazing angle.
  107678. * This helps ensuring a nice transition when the camera goes under the ground.
  107679. */
  107680. _this.opacityFresnel = true;
  107681. /**
  107682. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  107683. * This helps adding a mirror texture on the ground.
  107684. */
  107685. _this.reflectionFresnel = false;
  107686. /**
  107687. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  107688. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  107689. */
  107690. _this.reflectionFalloffDistance = 0.0;
  107691. /**
  107692. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  107693. */
  107694. _this.reflectionAmount = 1.0;
  107695. /**
  107696. * This specifies the weight of the reflection at grazing angle.
  107697. */
  107698. _this.reflectionReflectance0 = 0.05;
  107699. /**
  107700. * This specifies the weight of the reflection at a perpendicular point of view.
  107701. */
  107702. _this.reflectionReflectance90 = 0.5;
  107703. /**
  107704. * Helps to directly use the maps channels instead of their level.
  107705. */
  107706. _this.useRGBColor = true;
  107707. /**
  107708. * This helps reducing the banding effect that could occur on the background.
  107709. */
  107710. _this.enableNoise = false;
  107711. _this._fovMultiplier = 1.0;
  107712. /**
  107713. * Enable the FOV adjustment feature controlled by fovMultiplier.
  107714. */
  107715. _this.useEquirectangularFOV = false;
  107716. _this._maxSimultaneousLights = 4;
  107717. /**
  107718. * Number of Simultaneous lights allowed on the material.
  107719. */
  107720. _this.maxSimultaneousLights = 4;
  107721. /**
  107722. * Keep track of the image processing observer to allow dispose and replace.
  107723. */
  107724. _this._imageProcessingObserver = null;
  107725. /**
  107726. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  107727. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  107728. */
  107729. _this.switchToBGR = false;
  107730. // Temp values kept as cache in the material.
  107731. _this._renderTargets = new BABYLON.SmartArray(16);
  107732. _this._reflectionControls = BABYLON.Vector4.Zero();
  107733. _this._white = BABYLON.Color3.White();
  107734. _this._primaryShadowColor = BABYLON.Color3.Black();
  107735. _this._primaryHighlightColor = BABYLON.Color3.Black();
  107736. // Setup the default processing configuration to the scene.
  107737. _this._attachImageProcessingConfiguration(null);
  107738. _this.getRenderTargetTextures = function () {
  107739. _this._renderTargets.reset();
  107740. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  107741. _this._renderTargets.push(_this._diffuseTexture);
  107742. }
  107743. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  107744. _this._renderTargets.push(_this._reflectionTexture);
  107745. }
  107746. return _this._renderTargets;
  107747. };
  107748. return _this;
  107749. }
  107750. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  107751. /**
  107752. * Experimental Internal Use Only.
  107753. *
  107754. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  107755. * This acts as a helper to set the primary color to a more "human friendly" value.
  107756. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  107757. * output color as close as possible from the chosen value.
  107758. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  107759. * part of lighting setup.)
  107760. */
  107761. get: function () {
  107762. return this.__perceptualColor;
  107763. },
  107764. set: function (value) {
  107765. this.__perceptualColor = value;
  107766. this._computePrimaryColorFromPerceptualColor();
  107767. this._markAllSubMeshesAsLightsDirty();
  107768. },
  107769. enumerable: true,
  107770. configurable: true
  107771. });
  107772. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  107773. /**
  107774. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  107775. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  107776. */
  107777. get: function () {
  107778. return this._primaryColorShadowLevel;
  107779. },
  107780. set: function (value) {
  107781. this._primaryColorShadowLevel = value;
  107782. this._computePrimaryColors();
  107783. this._markAllSubMeshesAsLightsDirty();
  107784. },
  107785. enumerable: true,
  107786. configurable: true
  107787. });
  107788. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  107789. /**
  107790. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  107791. * The primary color is used at the level chosen to define what the white area would look.
  107792. */
  107793. get: function () {
  107794. return this._primaryColorHighlightLevel;
  107795. },
  107796. set: function (value) {
  107797. this._primaryColorHighlightLevel = value;
  107798. this._computePrimaryColors();
  107799. this._markAllSubMeshesAsLightsDirty();
  107800. },
  107801. enumerable: true,
  107802. configurable: true
  107803. });
  107804. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  107805. /**
  107806. * Sets the reflection reflectance fresnel values according to the default standard
  107807. * empirically know to work well :-)
  107808. */
  107809. set: function (value) {
  107810. var reflectionWeight = value;
  107811. if (reflectionWeight < 0.5) {
  107812. reflectionWeight = reflectionWeight * 2.0;
  107813. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  107814. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  107815. }
  107816. else {
  107817. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  107818. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  107819. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  107820. }
  107821. },
  107822. enumerable: true,
  107823. configurable: true
  107824. });
  107825. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  107826. /**
  107827. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107828. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  107829. * Recommended to be keep at 1.0 except for special cases.
  107830. */
  107831. get: function () {
  107832. return this._fovMultiplier;
  107833. },
  107834. set: function (value) {
  107835. if (isNaN(value)) {
  107836. value = 1.0;
  107837. }
  107838. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  107839. },
  107840. enumerable: true,
  107841. configurable: true
  107842. });
  107843. /**
  107844. * Attaches a new image processing configuration to the PBR Material.
  107845. * @param configuration (if null the scene configuration will be use)
  107846. */
  107847. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  107848. var _this = this;
  107849. if (configuration === this._imageProcessingConfiguration) {
  107850. return;
  107851. }
  107852. // Detaches observer.
  107853. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  107854. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  107855. }
  107856. // Pick the scene configuration if needed.
  107857. if (!configuration) {
  107858. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  107859. }
  107860. else {
  107861. this._imageProcessingConfiguration = configuration;
  107862. }
  107863. // Attaches observer.
  107864. if (this._imageProcessingConfiguration) {
  107865. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  107866. _this._computePrimaryColorFromPerceptualColor();
  107867. _this._markAllSubMeshesAsImageProcessingDirty();
  107868. });
  107869. }
  107870. };
  107871. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  107872. /**
  107873. * Gets the image processing configuration used either in this material.
  107874. */
  107875. get: function () {
  107876. return this._imageProcessingConfiguration;
  107877. },
  107878. /**
  107879. * Sets the Default image processing configuration used either in the this material.
  107880. *
  107881. * If sets to null, the scene one is in use.
  107882. */
  107883. set: function (value) {
  107884. this._attachImageProcessingConfiguration(value);
  107885. // Ensure the effect will be rebuilt.
  107886. this._markAllSubMeshesAsTexturesDirty();
  107887. },
  107888. enumerable: true,
  107889. configurable: true
  107890. });
  107891. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  107892. /**
  107893. * Gets wether the color curves effect is enabled.
  107894. */
  107895. get: function () {
  107896. return this.imageProcessingConfiguration.colorCurvesEnabled;
  107897. },
  107898. /**
  107899. * Sets wether the color curves effect is enabled.
  107900. */
  107901. set: function (value) {
  107902. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  107903. },
  107904. enumerable: true,
  107905. configurable: true
  107906. });
  107907. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  107908. /**
  107909. * Gets wether the color grading effect is enabled.
  107910. */
  107911. get: function () {
  107912. return this.imageProcessingConfiguration.colorGradingEnabled;
  107913. },
  107914. /**
  107915. * Gets wether the color grading effect is enabled.
  107916. */
  107917. set: function (value) {
  107918. this.imageProcessingConfiguration.colorGradingEnabled = value;
  107919. },
  107920. enumerable: true,
  107921. configurable: true
  107922. });
  107923. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  107924. /**
  107925. * Gets wether tonemapping is enabled or not.
  107926. */
  107927. get: function () {
  107928. return this._imageProcessingConfiguration.toneMappingEnabled;
  107929. },
  107930. /**
  107931. * Sets wether tonemapping is enabled or not
  107932. */
  107933. set: function (value) {
  107934. this._imageProcessingConfiguration.toneMappingEnabled = value;
  107935. },
  107936. enumerable: true,
  107937. configurable: true
  107938. });
  107939. ;
  107940. ;
  107941. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  107942. /**
  107943. * The camera exposure used on this material.
  107944. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107945. * This corresponds to a photographic exposure.
  107946. */
  107947. get: function () {
  107948. return this._imageProcessingConfiguration.exposure;
  107949. },
  107950. /**
  107951. * The camera exposure used on this material.
  107952. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107953. * This corresponds to a photographic exposure.
  107954. */
  107955. set: function (value) {
  107956. this._imageProcessingConfiguration.exposure = value;
  107957. },
  107958. enumerable: true,
  107959. configurable: true
  107960. });
  107961. ;
  107962. ;
  107963. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  107964. /**
  107965. * Gets The camera contrast used on this material.
  107966. */
  107967. get: function () {
  107968. return this._imageProcessingConfiguration.contrast;
  107969. },
  107970. /**
  107971. * Sets The camera contrast used on this material.
  107972. */
  107973. set: function (value) {
  107974. this._imageProcessingConfiguration.contrast = value;
  107975. },
  107976. enumerable: true,
  107977. configurable: true
  107978. });
  107979. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  107980. /**
  107981. * Gets the Color Grading 2D Lookup Texture.
  107982. */
  107983. get: function () {
  107984. return this._imageProcessingConfiguration.colorGradingTexture;
  107985. },
  107986. /**
  107987. * Sets the Color Grading 2D Lookup Texture.
  107988. */
  107989. set: function (value) {
  107990. this.imageProcessingConfiguration.colorGradingTexture = value;
  107991. },
  107992. enumerable: true,
  107993. configurable: true
  107994. });
  107995. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  107996. /**
  107997. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107998. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107999. * 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;
  108000. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  108001. */
  108002. get: function () {
  108003. return this.imageProcessingConfiguration.colorCurves;
  108004. },
  108005. /**
  108006. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  108007. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  108008. * 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;
  108009. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  108010. */
  108011. set: function (value) {
  108012. this.imageProcessingConfiguration.colorCurves = value;
  108013. },
  108014. enumerable: true,
  108015. configurable: true
  108016. });
  108017. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  108018. /**
  108019. * Gets a boolean indicating that current material needs to register RTT
  108020. */
  108021. get: function () {
  108022. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  108023. return true;
  108024. }
  108025. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  108026. return true;
  108027. }
  108028. return false;
  108029. },
  108030. enumerable: true,
  108031. configurable: true
  108032. });
  108033. /**
  108034. * The entire material has been created in order to prevent overdraw.
  108035. * @returns false
  108036. */
  108037. BackgroundMaterial.prototype.needAlphaTesting = function () {
  108038. return true;
  108039. };
  108040. /**
  108041. * The entire material has been created in order to prevent overdraw.
  108042. * @returns true if blending is enable
  108043. */
  108044. BackgroundMaterial.prototype.needAlphaBlending = function () {
  108045. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  108046. };
  108047. /**
  108048. * Checks wether the material is ready to be rendered for a given mesh.
  108049. * @param mesh The mesh to render
  108050. * @param subMesh The submesh to check against
  108051. * @param useInstances Specify wether or not the material is used with instances
  108052. * @returns true if all the dependencies are ready (Textures, Effects...)
  108053. */
  108054. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  108055. var _this = this;
  108056. if (useInstances === void 0) { useInstances = false; }
  108057. if (subMesh.effect && this.isFrozen) {
  108058. if (this._wasPreviouslyReady) {
  108059. return true;
  108060. }
  108061. }
  108062. if (!subMesh._materialDefines) {
  108063. subMesh._materialDefines = new BackgroundMaterialDefines();
  108064. }
  108065. var scene = this.getScene();
  108066. var defines = subMesh._materialDefines;
  108067. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  108068. if (defines._renderId === scene.getRenderId()) {
  108069. return true;
  108070. }
  108071. }
  108072. var engine = scene.getEngine();
  108073. // Lights
  108074. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  108075. defines._needNormals = true;
  108076. // Textures
  108077. if (defines._areTexturesDirty) {
  108078. defines._needUVs = false;
  108079. if (scene.texturesEnabled) {
  108080. if (scene.getEngine().getCaps().textureLOD) {
  108081. defines.TEXTURELODSUPPORT = true;
  108082. }
  108083. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  108084. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  108085. return false;
  108086. }
  108087. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  108088. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  108089. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  108090. defines.OPACITYFRESNEL = this._opacityFresnel;
  108091. }
  108092. else {
  108093. defines.DIFFUSE = false;
  108094. defines.DIFFUSEHASALPHA = false;
  108095. defines.GAMMADIFFUSE = false;
  108096. defines.OPACITYFRESNEL = false;
  108097. }
  108098. var reflectionTexture = this._reflectionTexture;
  108099. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  108100. if (!reflectionTexture.isReadyOrNotBlocking()) {
  108101. return false;
  108102. }
  108103. defines.REFLECTION = true;
  108104. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  108105. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  108106. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  108107. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  108108. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  108109. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  108110. defines.REFLECTIONBGR = this.switchToBGR;
  108111. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  108112. defines.INVERTCUBICMAP = true;
  108113. }
  108114. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  108115. switch (reflectionTexture.coordinatesMode) {
  108116. case BABYLON.Texture.EXPLICIT_MODE:
  108117. defines.REFLECTIONMAP_EXPLICIT = true;
  108118. break;
  108119. case BABYLON.Texture.PLANAR_MODE:
  108120. defines.REFLECTIONMAP_PLANAR = true;
  108121. break;
  108122. case BABYLON.Texture.PROJECTION_MODE:
  108123. defines.REFLECTIONMAP_PROJECTION = true;
  108124. break;
  108125. case BABYLON.Texture.SKYBOX_MODE:
  108126. defines.REFLECTIONMAP_SKYBOX = true;
  108127. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  108128. break;
  108129. case BABYLON.Texture.SPHERICAL_MODE:
  108130. defines.REFLECTIONMAP_SPHERICAL = true;
  108131. break;
  108132. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  108133. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  108134. break;
  108135. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  108136. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  108137. break;
  108138. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  108139. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  108140. break;
  108141. case BABYLON.Texture.CUBIC_MODE:
  108142. case BABYLON.Texture.INVCUBIC_MODE:
  108143. default:
  108144. defines.REFLECTIONMAP_CUBIC = true;
  108145. break;
  108146. }
  108147. if (this.reflectionFresnel) {
  108148. defines.REFLECTIONFRESNEL = true;
  108149. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  108150. this._reflectionControls.x = this.reflectionAmount;
  108151. this._reflectionControls.y = this.reflectionReflectance0;
  108152. this._reflectionControls.z = this.reflectionReflectance90;
  108153. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  108154. }
  108155. else {
  108156. defines.REFLECTIONFRESNEL = false;
  108157. defines.REFLECTIONFALLOFF = false;
  108158. }
  108159. }
  108160. else {
  108161. defines.REFLECTION = false;
  108162. defines.REFLECTIONFRESNEL = false;
  108163. defines.REFLECTIONFALLOFF = false;
  108164. defines.REFLECTIONBLUR = false;
  108165. defines.REFLECTIONMAP_3D = false;
  108166. defines.REFLECTIONMAP_SPHERICAL = false;
  108167. defines.REFLECTIONMAP_PLANAR = false;
  108168. defines.REFLECTIONMAP_CUBIC = false;
  108169. defines.REFLECTIONMAP_PROJECTION = false;
  108170. defines.REFLECTIONMAP_SKYBOX = false;
  108171. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  108172. defines.REFLECTIONMAP_EXPLICIT = false;
  108173. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  108174. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  108175. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  108176. defines.INVERTCUBICMAP = false;
  108177. defines.REFLECTIONMAP_OPPOSITEZ = false;
  108178. defines.LODINREFLECTIONALPHA = false;
  108179. defines.GAMMAREFLECTION = false;
  108180. defines.RGBDREFLECTION = false;
  108181. }
  108182. }
  108183. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  108184. defines.USERGBCOLOR = this._useRGBColor;
  108185. defines.NOISE = this._enableNoise;
  108186. }
  108187. if (defines._areLightsDirty) {
  108188. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  108189. }
  108190. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  108191. if (!this._imageProcessingConfiguration.isReady()) {
  108192. return false;
  108193. }
  108194. this._imageProcessingConfiguration.prepareDefines(defines);
  108195. }
  108196. // Misc.
  108197. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  108198. // Values that need to be evaluated on every frame
  108199. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  108200. // Attribs
  108201. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  108202. if (mesh) {
  108203. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  108204. mesh.createNormals(true);
  108205. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  108206. }
  108207. }
  108208. }
  108209. // Get correct effect
  108210. if (defines.isDirty) {
  108211. defines.markAsProcessed();
  108212. scene.resetCachedMaterial();
  108213. // Fallbacks
  108214. var fallbacks = new BABYLON.EffectFallbacks();
  108215. if (defines.FOG) {
  108216. fallbacks.addFallback(0, "FOG");
  108217. }
  108218. if (defines.POINTSIZE) {
  108219. fallbacks.addFallback(1, "POINTSIZE");
  108220. }
  108221. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  108222. if (defines.NUM_BONE_INFLUENCERS > 0) {
  108223. fallbacks.addCPUSkinningFallback(0, mesh);
  108224. }
  108225. //Attributes
  108226. var attribs = [BABYLON.VertexBuffer.PositionKind];
  108227. if (defines.NORMAL) {
  108228. attribs.push(BABYLON.VertexBuffer.NormalKind);
  108229. }
  108230. if (defines.UV1) {
  108231. attribs.push(BABYLON.VertexBuffer.UVKind);
  108232. }
  108233. if (defines.UV2) {
  108234. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  108235. }
  108236. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  108237. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  108238. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  108239. "vFogInfos", "vFogColor", "pointSize",
  108240. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  108241. "vPrimaryColor", "vPrimaryColorShadow",
  108242. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  108243. "shadowLevel", "alpha",
  108244. "vBackgroundCenter", "vReflectionControl",
  108245. "vDiffuseInfos", "diffuseMatrix",
  108246. ];
  108247. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  108248. var uniformBuffers = ["Material", "Scene"];
  108249. if (BABYLON.ImageProcessingConfiguration) {
  108250. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  108251. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  108252. }
  108253. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  108254. uniformsNames: uniforms,
  108255. uniformBuffersNames: uniformBuffers,
  108256. samplers: samplers,
  108257. defines: defines,
  108258. maxSimultaneousLights: this._maxSimultaneousLights
  108259. });
  108260. var onCompiled = function (effect) {
  108261. if (_this.onCompiled) {
  108262. _this.onCompiled(effect);
  108263. }
  108264. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  108265. };
  108266. var join = defines.toString();
  108267. subMesh.setEffect(scene.getEngine().createEffect("background", {
  108268. attributes: attribs,
  108269. uniformsNames: uniforms,
  108270. uniformBuffersNames: uniformBuffers,
  108271. samplers: samplers,
  108272. defines: join,
  108273. fallbacks: fallbacks,
  108274. onCompiled: onCompiled,
  108275. onError: this.onError,
  108276. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  108277. }, engine), defines);
  108278. this.buildUniformLayout();
  108279. }
  108280. if (!subMesh.effect || !subMesh.effect.isReady()) {
  108281. return false;
  108282. }
  108283. defines._renderId = scene.getRenderId();
  108284. this._wasPreviouslyReady = true;
  108285. return true;
  108286. };
  108287. /**
  108288. * Compute the primary color according to the chosen perceptual color.
  108289. */
  108290. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  108291. if (!this.__perceptualColor) {
  108292. return;
  108293. }
  108294. this._primaryColor.copyFrom(this.__perceptualColor);
  108295. // Revert gamma space.
  108296. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  108297. // Revert image processing configuration.
  108298. if (this._imageProcessingConfiguration) {
  108299. // Revert Exposure.
  108300. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  108301. }
  108302. this._computePrimaryColors();
  108303. };
  108304. /**
  108305. * Compute the highlights and shadow colors according to their chosen levels.
  108306. */
  108307. BackgroundMaterial.prototype._computePrimaryColors = function () {
  108308. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  108309. return;
  108310. }
  108311. // Find the highlight color based on the configuration.
  108312. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  108313. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  108314. // Find the shadow color based on the configuration.
  108315. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  108316. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  108317. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  108318. };
  108319. /**
  108320. * Build the uniform buffer used in the material.
  108321. */
  108322. BackgroundMaterial.prototype.buildUniformLayout = function () {
  108323. // Order is important !
  108324. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  108325. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  108326. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  108327. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  108328. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  108329. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  108330. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  108331. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  108332. this._uniformBuffer.addUniform("pointSize", 1);
  108333. this._uniformBuffer.addUniform("shadowLevel", 1);
  108334. this._uniformBuffer.addUniform("alpha", 1);
  108335. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  108336. this._uniformBuffer.addUniform("vReflectionControl", 4);
  108337. this._uniformBuffer.create();
  108338. };
  108339. /**
  108340. * Unbind the material.
  108341. */
  108342. BackgroundMaterial.prototype.unbind = function () {
  108343. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  108344. this._uniformBuffer.setTexture("diffuseSampler", null);
  108345. }
  108346. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  108347. this._uniformBuffer.setTexture("reflectionSampler", null);
  108348. }
  108349. _super.prototype.unbind.call(this);
  108350. };
  108351. /**
  108352. * Bind only the world matrix to the material.
  108353. * @param world The world matrix to bind.
  108354. */
  108355. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  108356. this._activeEffect.setMatrix("world", world);
  108357. };
  108358. /**
  108359. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  108360. * @param world The world matrix to bind.
  108361. * @param subMesh The submesh to bind for.
  108362. */
  108363. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  108364. var scene = this.getScene();
  108365. var defines = subMesh._materialDefines;
  108366. if (!defines) {
  108367. return;
  108368. }
  108369. var effect = subMesh.effect;
  108370. if (!effect) {
  108371. return;
  108372. }
  108373. this._activeEffect = effect;
  108374. // Matrices
  108375. this.bindOnlyWorldMatrix(world);
  108376. // Bones
  108377. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  108378. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  108379. if (mustRebind) {
  108380. this._uniformBuffer.bindToEffect(effect, "Material");
  108381. this.bindViewProjection(effect);
  108382. var reflectionTexture = this._reflectionTexture;
  108383. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  108384. // Texture uniforms
  108385. if (scene.texturesEnabled) {
  108386. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  108387. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  108388. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  108389. }
  108390. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  108391. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  108392. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  108393. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  108394. }
  108395. }
  108396. if (this.shadowLevel > 0) {
  108397. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  108398. }
  108399. this._uniformBuffer.updateFloat("alpha", this.alpha);
  108400. // Point size
  108401. if (this.pointsCloud) {
  108402. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  108403. }
  108404. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  108405. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  108406. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  108407. }
  108408. else {
  108409. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  108410. }
  108411. }
  108412. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  108413. // Textures
  108414. if (scene.texturesEnabled) {
  108415. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  108416. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  108417. }
  108418. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  108419. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  108420. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  108421. }
  108422. else if (!defines.REFLECTIONBLUR) {
  108423. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  108424. }
  108425. else {
  108426. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  108427. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  108428. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  108429. }
  108430. if (defines.REFLECTIONFRESNEL) {
  108431. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  108432. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  108433. }
  108434. }
  108435. }
  108436. // Clip plane
  108437. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  108438. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  108439. }
  108440. if (mustRebind || !this.isFrozen) {
  108441. if (scene.lightsEnabled) {
  108442. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  108443. }
  108444. // View
  108445. this.bindView(effect);
  108446. // Fog
  108447. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  108448. // image processing
  108449. if (this._imageProcessingConfiguration) {
  108450. this._imageProcessingConfiguration.bind(this._activeEffect);
  108451. }
  108452. }
  108453. this._uniformBuffer.update();
  108454. this._afterBind(mesh, this._activeEffect);
  108455. };
  108456. /**
  108457. * Dispose the material.
  108458. * @param forceDisposeEffect Force disposal of the associated effect.
  108459. * @param forceDisposeTextures Force disposal of the associated textures.
  108460. */
  108461. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  108462. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  108463. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  108464. if (forceDisposeTextures) {
  108465. if (this.diffuseTexture) {
  108466. this.diffuseTexture.dispose();
  108467. }
  108468. if (this.reflectionTexture) {
  108469. this.reflectionTexture.dispose();
  108470. }
  108471. }
  108472. this._renderTargets.dispose();
  108473. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  108474. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  108475. }
  108476. _super.prototype.dispose.call(this, forceDisposeEffect);
  108477. };
  108478. /**
  108479. * Clones the material.
  108480. * @param name The cloned name.
  108481. * @returns The cloned material.
  108482. */
  108483. BackgroundMaterial.prototype.clone = function (name) {
  108484. var _this = this;
  108485. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  108486. };
  108487. /**
  108488. * Serializes the current material to its JSON representation.
  108489. * @returns The JSON representation.
  108490. */
  108491. BackgroundMaterial.prototype.serialize = function () {
  108492. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  108493. serializationObject.customType = "BABYLON.BackgroundMaterial";
  108494. return serializationObject;
  108495. };
  108496. /**
  108497. * Gets the class name of the material
  108498. * @returns "BackgroundMaterial"
  108499. */
  108500. BackgroundMaterial.prototype.getClassName = function () {
  108501. return "BackgroundMaterial";
  108502. };
  108503. /**
  108504. * Parse a JSON input to create back a background material.
  108505. * @param source The JSON data to parse
  108506. * @param scene The scene to create the parsed material in
  108507. * @param rootUrl The root url of the assets the material depends upon
  108508. * @returns the instantiated BackgroundMaterial.
  108509. */
  108510. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  108511. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  108512. };
  108513. /**
  108514. * Standard reflectance value at parallel view angle.
  108515. */
  108516. BackgroundMaterial.StandardReflectance0 = 0.05;
  108517. /**
  108518. * Standard reflectance value at grazing angle.
  108519. */
  108520. BackgroundMaterial.StandardReflectance90 = 0.5;
  108521. __decorate([
  108522. BABYLON.serializeAsColor3()
  108523. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  108524. __decorate([
  108525. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  108526. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  108527. __decorate([
  108528. BABYLON.serializeAsColor3()
  108529. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  108530. __decorate([
  108531. BABYLON.serialize()
  108532. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  108533. __decorate([
  108534. BABYLON.serialize()
  108535. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  108536. __decorate([
  108537. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  108538. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  108539. __decorate([
  108540. BABYLON.serializeAsTexture()
  108541. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  108542. __decorate([
  108543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108544. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  108545. __decorate([
  108546. BABYLON.serialize()
  108547. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  108548. __decorate([
  108549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108550. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  108551. __decorate([
  108552. BABYLON.serializeAsTexture()
  108553. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  108554. __decorate([
  108555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108556. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  108557. __decorate([
  108558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108559. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  108560. __decorate([
  108561. BABYLON.serialize()
  108562. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  108563. __decorate([
  108564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108565. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  108566. __decorate([
  108567. BABYLON.serializeAsVector3()
  108568. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  108569. __decorate([
  108570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108571. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  108572. __decorate([
  108573. BABYLON.serialize()
  108574. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  108575. __decorate([
  108576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108577. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  108578. __decorate([
  108579. BABYLON.serialize()
  108580. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  108581. __decorate([
  108582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108583. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  108584. __decorate([
  108585. BABYLON.serialize()
  108586. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  108587. __decorate([
  108588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108589. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  108590. __decorate([
  108591. BABYLON.serialize()
  108592. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  108593. __decorate([
  108594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108595. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  108596. __decorate([
  108597. BABYLON.serialize()
  108598. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  108599. __decorate([
  108600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108601. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  108602. __decorate([
  108603. BABYLON.serialize()
  108604. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  108605. __decorate([
  108606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108607. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  108608. __decorate([
  108609. BABYLON.serialize()
  108610. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  108611. __decorate([
  108612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108613. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  108614. __decorate([
  108615. BABYLON.serialize()
  108616. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  108617. __decorate([
  108618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108619. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  108620. __decorate([
  108621. BABYLON.serialize()
  108622. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  108623. __decorate([
  108624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108625. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  108626. __decorate([
  108627. BABYLON.serializeAsImageProcessingConfiguration()
  108628. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  108629. return BackgroundMaterial;
  108630. }(BABYLON.PushMaterial));
  108631. BABYLON.BackgroundMaterial = BackgroundMaterial;
  108632. })(BABYLON || (BABYLON = {}));
  108633. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  108634. var __assign = (this && this.__assign) || function () {
  108635. __assign = Object.assign || function(t) {
  108636. for (var s, i = 1, n = arguments.length; i < n; i++) {
  108637. s = arguments[i];
  108638. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  108639. t[p] = s[p];
  108640. }
  108641. return t;
  108642. };
  108643. return __assign.apply(this, arguments);
  108644. };
  108645. var BABYLON;
  108646. (function (BABYLON) {
  108647. /**
  108648. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  108649. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  108650. * It also helps with the default setup of your imageProcessing configuration.
  108651. */
  108652. var EnvironmentHelper = /** @class */ (function () {
  108653. /**
  108654. * constructor
  108655. * @param options
  108656. * @param scene The scene to add the material to
  108657. */
  108658. function EnvironmentHelper(options, scene) {
  108659. var _this = this;
  108660. this._errorHandler = function (message, exception) {
  108661. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  108662. };
  108663. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  108664. this._scene = scene;
  108665. this.onErrorObservable = new BABYLON.Observable();
  108666. this._setupBackground();
  108667. this._setupImageProcessing();
  108668. }
  108669. /**
  108670. * Creates the default options for the helper.
  108671. */
  108672. EnvironmentHelper._getDefaultOptions = function () {
  108673. return {
  108674. createGround: true,
  108675. groundSize: 15,
  108676. groundTexture: this._groundTextureCDNUrl,
  108677. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  108678. groundOpacity: 0.9,
  108679. enableGroundShadow: true,
  108680. groundShadowLevel: 0.5,
  108681. enableGroundMirror: false,
  108682. groundMirrorSizeRatio: 0.3,
  108683. groundMirrorBlurKernel: 64,
  108684. groundMirrorAmount: 1,
  108685. groundMirrorFresnelWeight: 1,
  108686. groundMirrorFallOffDistance: 0,
  108687. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  108688. groundYBias: 0.00001,
  108689. createSkybox: true,
  108690. skyboxSize: 20,
  108691. skyboxTexture: this._skyboxTextureCDNUrl,
  108692. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  108693. backgroundYRotation: 0,
  108694. sizeAuto: true,
  108695. rootPosition: BABYLON.Vector3.Zero(),
  108696. setupImageProcessing: true,
  108697. environmentTexture: this._environmentTextureCDNUrl,
  108698. cameraExposure: 0.8,
  108699. cameraContrast: 1.2,
  108700. toneMappingEnabled: true,
  108701. };
  108702. };
  108703. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  108704. /**
  108705. * Gets the root mesh created by the helper.
  108706. */
  108707. get: function () {
  108708. return this._rootMesh;
  108709. },
  108710. enumerable: true,
  108711. configurable: true
  108712. });
  108713. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  108714. /**
  108715. * Gets the skybox created by the helper.
  108716. */
  108717. get: function () {
  108718. return this._skybox;
  108719. },
  108720. enumerable: true,
  108721. configurable: true
  108722. });
  108723. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  108724. /**
  108725. * Gets the skybox texture created by the helper.
  108726. */
  108727. get: function () {
  108728. return this._skyboxTexture;
  108729. },
  108730. enumerable: true,
  108731. configurable: true
  108732. });
  108733. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  108734. /**
  108735. * Gets the skybox material created by the helper.
  108736. */
  108737. get: function () {
  108738. return this._skyboxMaterial;
  108739. },
  108740. enumerable: true,
  108741. configurable: true
  108742. });
  108743. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  108744. /**
  108745. * Gets the ground mesh created by the helper.
  108746. */
  108747. get: function () {
  108748. return this._ground;
  108749. },
  108750. enumerable: true,
  108751. configurable: true
  108752. });
  108753. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  108754. /**
  108755. * Gets the ground texture created by the helper.
  108756. */
  108757. get: function () {
  108758. return this._groundTexture;
  108759. },
  108760. enumerable: true,
  108761. configurable: true
  108762. });
  108763. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  108764. /**
  108765. * Gets the ground mirror created by the helper.
  108766. */
  108767. get: function () {
  108768. return this._groundMirror;
  108769. },
  108770. enumerable: true,
  108771. configurable: true
  108772. });
  108773. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  108774. /**
  108775. * Gets the ground mirror render list to helps pushing the meshes
  108776. * you wish in the ground reflection.
  108777. */
  108778. get: function () {
  108779. if (this._groundMirror) {
  108780. return this._groundMirror.renderList;
  108781. }
  108782. return null;
  108783. },
  108784. enumerable: true,
  108785. configurable: true
  108786. });
  108787. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  108788. /**
  108789. * Gets the ground material created by the helper.
  108790. */
  108791. get: function () {
  108792. return this._groundMaterial;
  108793. },
  108794. enumerable: true,
  108795. configurable: true
  108796. });
  108797. /**
  108798. * Updates the background according to the new options
  108799. * @param options
  108800. */
  108801. EnvironmentHelper.prototype.updateOptions = function (options) {
  108802. var newOptions = __assign({}, this._options, options);
  108803. if (this._ground && !newOptions.createGround) {
  108804. this._ground.dispose();
  108805. this._ground = null;
  108806. }
  108807. if (this._groundMaterial && !newOptions.createGround) {
  108808. this._groundMaterial.dispose();
  108809. this._groundMaterial = null;
  108810. }
  108811. if (this._groundTexture) {
  108812. if (this._options.groundTexture != newOptions.groundTexture) {
  108813. this._groundTexture.dispose();
  108814. this._groundTexture = null;
  108815. }
  108816. }
  108817. if (this._skybox && !newOptions.createSkybox) {
  108818. this._skybox.dispose();
  108819. this._skybox = null;
  108820. }
  108821. if (this._skyboxMaterial && !newOptions.createSkybox) {
  108822. this._skyboxMaterial.dispose();
  108823. this._skyboxMaterial = null;
  108824. }
  108825. if (this._skyboxTexture) {
  108826. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  108827. this._skyboxTexture.dispose();
  108828. this._skyboxTexture = null;
  108829. }
  108830. }
  108831. if (this._groundMirror && !newOptions.enableGroundMirror) {
  108832. this._groundMirror.dispose();
  108833. this._groundMirror = null;
  108834. }
  108835. if (this._scene.environmentTexture) {
  108836. if (this._options.environmentTexture != newOptions.environmentTexture) {
  108837. this._scene.environmentTexture.dispose();
  108838. }
  108839. }
  108840. this._options = newOptions;
  108841. this._setupBackground();
  108842. this._setupImageProcessing();
  108843. };
  108844. /**
  108845. * Sets the primary color of all the available elements.
  108846. * @param color the main color to affect to the ground and the background
  108847. */
  108848. EnvironmentHelper.prototype.setMainColor = function (color) {
  108849. if (this.groundMaterial) {
  108850. this.groundMaterial.primaryColor = color;
  108851. }
  108852. if (this.skyboxMaterial) {
  108853. this.skyboxMaterial.primaryColor = color;
  108854. }
  108855. if (this.groundMirror) {
  108856. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  108857. }
  108858. };
  108859. /**
  108860. * Setup the image processing according to the specified options.
  108861. */
  108862. EnvironmentHelper.prototype._setupImageProcessing = function () {
  108863. if (this._options.setupImageProcessing) {
  108864. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  108865. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  108866. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  108867. this._setupEnvironmentTexture();
  108868. }
  108869. };
  108870. /**
  108871. * Setup the environment texture according to the specified options.
  108872. */
  108873. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  108874. if (this._scene.environmentTexture) {
  108875. return;
  108876. }
  108877. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  108878. this._scene.environmentTexture = this._options.environmentTexture;
  108879. return;
  108880. }
  108881. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  108882. this._scene.environmentTexture = environmentTexture;
  108883. };
  108884. /**
  108885. * Setup the background according to the specified options.
  108886. */
  108887. EnvironmentHelper.prototype._setupBackground = function () {
  108888. if (!this._rootMesh) {
  108889. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  108890. }
  108891. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  108892. var sceneSize = this._getSceneSize();
  108893. if (this._options.createGround) {
  108894. this._setupGround(sceneSize);
  108895. this._setupGroundMaterial();
  108896. this._setupGroundDiffuseTexture();
  108897. if (this._options.enableGroundMirror) {
  108898. this._setupGroundMirrorTexture(sceneSize);
  108899. }
  108900. this._setupMirrorInGroundMaterial();
  108901. }
  108902. if (this._options.createSkybox) {
  108903. this._setupSkybox(sceneSize);
  108904. this._setupSkyboxMaterial();
  108905. this._setupSkyboxReflectionTexture();
  108906. }
  108907. this._rootMesh.position.x = sceneSize.rootPosition.x;
  108908. this._rootMesh.position.z = sceneSize.rootPosition.z;
  108909. this._rootMesh.position.y = sceneSize.rootPosition.y;
  108910. };
  108911. /**
  108912. * Get the scene sizes according to the setup.
  108913. */
  108914. EnvironmentHelper.prototype._getSceneSize = function () {
  108915. var _this = this;
  108916. var groundSize = this._options.groundSize;
  108917. var skyboxSize = this._options.skyboxSize;
  108918. var rootPosition = this._options.rootPosition;
  108919. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  108920. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108921. }
  108922. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  108923. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  108924. });
  108925. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  108926. if (this._options.sizeAuto) {
  108927. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  108928. this._scene.activeCamera.upperRadiusLimit) {
  108929. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  108930. skyboxSize = groundSize;
  108931. }
  108932. var sceneDiagonalLenght = sceneDiagonal.length();
  108933. if (sceneDiagonalLenght > groundSize) {
  108934. groundSize = sceneDiagonalLenght * 2;
  108935. skyboxSize = groundSize;
  108936. }
  108937. // 10 % bigger.
  108938. groundSize *= 1.1;
  108939. skyboxSize *= 1.5;
  108940. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  108941. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  108942. }
  108943. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108944. };
  108945. /**
  108946. * Setup the ground according to the specified options.
  108947. */
  108948. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  108949. var _this = this;
  108950. if (!this._ground || this._ground.isDisposed()) {
  108951. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  108952. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  108953. this._ground.parent = this._rootMesh;
  108954. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  108955. }
  108956. this._ground.receiveShadows = this._options.enableGroundShadow;
  108957. };
  108958. /**
  108959. * Setup the ground material according to the specified options.
  108960. */
  108961. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  108962. if (!this._groundMaterial) {
  108963. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  108964. }
  108965. this._groundMaterial.alpha = this._options.groundOpacity;
  108966. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  108967. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  108968. this._groundMaterial.primaryColor = this._options.groundColor;
  108969. this._groundMaterial.useRGBColor = false;
  108970. this._groundMaterial.enableNoise = true;
  108971. if (this._ground) {
  108972. this._ground.material = this._groundMaterial;
  108973. }
  108974. };
  108975. /**
  108976. * Setup the ground diffuse texture according to the specified options.
  108977. */
  108978. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  108979. if (!this._groundMaterial) {
  108980. return;
  108981. }
  108982. if (this._groundTexture) {
  108983. return;
  108984. }
  108985. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  108986. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  108987. return;
  108988. }
  108989. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108990. diffuseTexture.gammaSpace = false;
  108991. diffuseTexture.hasAlpha = true;
  108992. this._groundMaterial.diffuseTexture = diffuseTexture;
  108993. };
  108994. /**
  108995. * Setup the ground mirror texture according to the specified options.
  108996. */
  108997. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  108998. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108999. if (!this._groundMirror) {
  109000. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  109001. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  109002. this._groundMirror.anisotropicFilteringLevel = 1;
  109003. this._groundMirror.wrapU = wrapping;
  109004. this._groundMirror.wrapV = wrapping;
  109005. this._groundMirror.gammaSpace = false;
  109006. if (this._groundMirror.renderList) {
  109007. for (var i = 0; i < this._scene.meshes.length; i++) {
  109008. var mesh = this._scene.meshes[i];
  109009. if (mesh !== this._ground &&
  109010. mesh !== this._skybox &&
  109011. mesh !== this._rootMesh) {
  109012. this._groundMirror.renderList.push(mesh);
  109013. }
  109014. }
  109015. }
  109016. }
  109017. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  109018. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  109019. };
  109020. /**
  109021. * Setup the ground to receive the mirror texture.
  109022. */
  109023. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  109024. if (this._groundMaterial) {
  109025. this._groundMaterial.reflectionTexture = this._groundMirror;
  109026. this._groundMaterial.reflectionFresnel = true;
  109027. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  109028. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  109029. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  109030. }
  109031. };
  109032. /**
  109033. * Setup the skybox according to the specified options.
  109034. */
  109035. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  109036. var _this = this;
  109037. if (!this._skybox || this._skybox.isDisposed()) {
  109038. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  109039. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  109040. }
  109041. this._skybox.parent = this._rootMesh;
  109042. };
  109043. /**
  109044. * Setup the skybox material according to the specified options.
  109045. */
  109046. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  109047. if (!this._skybox) {
  109048. return;
  109049. }
  109050. if (!this._skyboxMaterial) {
  109051. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  109052. }
  109053. this._skyboxMaterial.useRGBColor = false;
  109054. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  109055. this._skyboxMaterial.enableNoise = true;
  109056. this._skybox.material = this._skyboxMaterial;
  109057. };
  109058. /**
  109059. * Setup the skybox reflection texture according to the specified options.
  109060. */
  109061. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  109062. if (!this._skyboxMaterial) {
  109063. return;
  109064. }
  109065. if (this._skyboxTexture) {
  109066. return;
  109067. }
  109068. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  109069. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  109070. return;
  109071. }
  109072. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  109073. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109074. this._skyboxTexture.gammaSpace = false;
  109075. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  109076. };
  109077. /**
  109078. * Dispose all the elements created by the Helper.
  109079. */
  109080. EnvironmentHelper.prototype.dispose = function () {
  109081. if (this._groundMaterial) {
  109082. this._groundMaterial.dispose(true, true);
  109083. }
  109084. if (this._skyboxMaterial) {
  109085. this._skyboxMaterial.dispose(true, true);
  109086. }
  109087. this._rootMesh.dispose(false);
  109088. };
  109089. /**
  109090. * Default ground texture URL.
  109091. */
  109092. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  109093. /**
  109094. * Default skybox texture URL.
  109095. */
  109096. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  109097. /**
  109098. * Default environment texture URL.
  109099. */
  109100. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  109101. return EnvironmentHelper;
  109102. }());
  109103. BABYLON.EnvironmentHelper = EnvironmentHelper;
  109104. })(BABYLON || (BABYLON = {}));
  109105. //# sourceMappingURL=babylon.environmentHelper.js.map
  109106. var BABYLON;
  109107. (function (BABYLON) {
  109108. /** Internal class used to store shapes for emitters */
  109109. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  109110. function ParticleSystemSetEmitterCreationOptions() {
  109111. }
  109112. return ParticleSystemSetEmitterCreationOptions;
  109113. }());
  109114. /**
  109115. * Represents a set of particle systems working together to create a specific effect
  109116. */
  109117. var ParticleSystemSet = /** @class */ (function () {
  109118. function ParticleSystemSet() {
  109119. /**
  109120. * Gets the particle system list
  109121. */
  109122. this.systems = new Array();
  109123. }
  109124. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  109125. /**
  109126. * Gets the emitter node used with this set
  109127. */
  109128. get: function () {
  109129. return this._emitterNode;
  109130. },
  109131. enumerable: true,
  109132. configurable: true
  109133. });
  109134. /**
  109135. * Creates a new emitter mesh as a sphere
  109136. * @param options defines the options used to create the sphere
  109137. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  109138. * @param scene defines the hosting scene
  109139. */
  109140. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  109141. if (this._emitterNode) {
  109142. this._emitterNode.dispose();
  109143. }
  109144. this._emitterCreationOptions = {
  109145. kind: "Sphere",
  109146. options: options,
  109147. renderingGroupId: renderingGroupId
  109148. };
  109149. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  109150. emitterMesh.renderingGroupId = renderingGroupId;
  109151. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  109152. material.emissiveColor = options.color;
  109153. emitterMesh.material = material;
  109154. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  109155. var system = _a[_i];
  109156. system.emitter = emitterMesh;
  109157. }
  109158. this._emitterNode = emitterMesh;
  109159. };
  109160. /**
  109161. * Starts all particle systems of the set
  109162. * @param emitter defines an optional mesh to use as emitter for the particle systems
  109163. */
  109164. ParticleSystemSet.prototype.start = function (emitter) {
  109165. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  109166. var system = _a[_i];
  109167. if (emitter) {
  109168. system.emitter = emitter;
  109169. }
  109170. system.start();
  109171. }
  109172. };
  109173. /**
  109174. * Release all associated resources
  109175. */
  109176. ParticleSystemSet.prototype.dispose = function () {
  109177. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  109178. var system = _a[_i];
  109179. system.dispose();
  109180. }
  109181. this.systems = [];
  109182. if (this._emitterNode) {
  109183. this._emitterNode.dispose();
  109184. this._emitterNode = null;
  109185. }
  109186. };
  109187. /**
  109188. * Serialize the set into a JSON compatible object
  109189. * @returns a JSON compatible representation of the set
  109190. */
  109191. ParticleSystemSet.prototype.serialize = function () {
  109192. var result = {};
  109193. result.systems = [];
  109194. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  109195. var system = _a[_i];
  109196. result.systems.push(system.serialize());
  109197. }
  109198. if (this._emitterNode) {
  109199. result.emitter = this._emitterCreationOptions;
  109200. }
  109201. return result;
  109202. };
  109203. /**
  109204. * Parse a new ParticleSystemSet from a serialized source
  109205. * @param data defines a JSON compatible representation of the set
  109206. * @param scene defines the hosting scene
  109207. * @param gpu defines if we want GPU particles or CPU particles
  109208. * @returns a new ParticleSystemSet
  109209. */
  109210. ParticleSystemSet.Parse = function (data, scene, gpu) {
  109211. if (gpu === void 0) { gpu = false; }
  109212. var result = new ParticleSystemSet();
  109213. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  109214. scene = scene || BABYLON.Engine.LastCreatedScene;
  109215. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  109216. var system = _a[_i];
  109217. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  109218. }
  109219. if (data.emitter) {
  109220. var options = data.emitter.options;
  109221. switch (data.emitter.kind) {
  109222. case "Sphere":
  109223. result.setEmitterAsSphere({
  109224. diameter: options.diameter,
  109225. segments: options.segments,
  109226. color: BABYLON.Color3.FromArray(options.color)
  109227. }, data.emitter.renderingGroupId, scene);
  109228. break;
  109229. }
  109230. }
  109231. return result;
  109232. };
  109233. return ParticleSystemSet;
  109234. }());
  109235. BABYLON.ParticleSystemSet = ParticleSystemSet;
  109236. })(BABYLON || (BABYLON = {}));
  109237. //# sourceMappingURL=babylon.particleSystemSet.js.map
  109238. var BABYLON;
  109239. (function (BABYLON) {
  109240. /**
  109241. * This class is made for on one-liner static method to help creating particle system set.
  109242. */
  109243. var ParticleHelper = /** @class */ (function () {
  109244. function ParticleHelper() {
  109245. }
  109246. /**
  109247. * Create a default particle system that you can tweak
  109248. * @param emitter defines the emitter to use
  109249. * @param capacity defines the system capacity (default is 500 particles)
  109250. * @param scene defines the hosting scene
  109251. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  109252. * @returns the new Particle system
  109253. */
  109254. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  109255. if (capacity === void 0) { capacity = 500; }
  109256. if (useGPU === void 0) { useGPU = false; }
  109257. var system;
  109258. if (useGPU) {
  109259. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  109260. }
  109261. else {
  109262. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  109263. }
  109264. system.emitter = emitter;
  109265. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  109266. system.createConeEmitter(0.1, Math.PI / 4);
  109267. // Particle color
  109268. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  109269. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  109270. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  109271. // Particle Size
  109272. system.minSize = 0.1;
  109273. system.maxSize = 0.1;
  109274. // Emission speed
  109275. system.minEmitPower = 2;
  109276. system.maxEmitPower = 2;
  109277. // Update speed
  109278. system.updateSpeed = 1 / 60;
  109279. system.emitRate = 30;
  109280. return system;
  109281. };
  109282. /**
  109283. * This is the main static method (one-liner) of this helper to create different particle systems
  109284. * @param type This string represents the type to the particle system to create
  109285. * @param scene The scene where the particle system should live
  109286. * @param gpu If the system will use gpu
  109287. * @returns the ParticleSystemSet created
  109288. */
  109289. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  109290. if (gpu === void 0) { gpu = false; }
  109291. if (!scene) {
  109292. scene = BABYLON.Engine.LastCreatedScene;
  109293. ;
  109294. }
  109295. var token = {};
  109296. scene._addPendingData(token);
  109297. return new Promise(function (resolve, reject) {
  109298. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  109299. scene._removePendingData(token);
  109300. return reject("Particle system with GPU is not supported.");
  109301. }
  109302. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  109303. scene._removePendingData(token);
  109304. var newData = JSON.parse(data.toString());
  109305. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  109306. }, undefined, undefined, undefined, function (req, exception) {
  109307. scene._removePendingData(token);
  109308. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  109309. });
  109310. });
  109311. };
  109312. /**
  109313. * Static function used to export a particle system to a ParticleSystemSet variable.
  109314. * Please note that the emitter shape is not exported
  109315. * @param system defines the particle systems to export
  109316. */
  109317. ParticleHelper.ExportSet = function (systems) {
  109318. var set = new BABYLON.ParticleSystemSet();
  109319. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  109320. var system = systems_1[_i];
  109321. set.systems.push(system);
  109322. }
  109323. return set;
  109324. };
  109325. /**
  109326. * Gets or sets base Assets URL
  109327. */
  109328. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  109329. return ParticleHelper;
  109330. }());
  109331. BABYLON.ParticleHelper = ParticleHelper;
  109332. })(BABYLON || (BABYLON = {}));
  109333. //# sourceMappingURL=babylon.particleHelper.js.map
  109334. var BABYLON;
  109335. (function (BABYLON) {
  109336. /**
  109337. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  109338. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  109339. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  109340. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  109341. */
  109342. var VideoDome = /** @class */ (function (_super) {
  109343. __extends(VideoDome, _super);
  109344. /**
  109345. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  109346. * @param name Element's name, child elements will append suffixes for their own names.
  109347. * @param urlsOrVideo defines the url(s) or the video element to use
  109348. * @param options An object containing optional or exposed sub element properties
  109349. */
  109350. function VideoDome(name, urlsOrVideo, options, scene) {
  109351. var _this = _super.call(this, name, scene) || this;
  109352. _this._useDirectMapping = false;
  109353. // set defaults and manage values
  109354. name = name || "videoDome";
  109355. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  109356. options.clickToPlay = Boolean(options.clickToPlay);
  109357. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  109358. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  109359. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  109360. if (options.useDirectMapping === undefined) {
  109361. _this._useDirectMapping = true;
  109362. }
  109363. else {
  109364. _this._useDirectMapping = options.useDirectMapping;
  109365. }
  109366. _this._setReady(false);
  109367. // create
  109368. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  109369. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  109370. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  109371. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  109372. texture.onLoadObservable.addOnce(function () {
  109373. _this._setReady(true);
  109374. });
  109375. // configure material
  109376. material.useEquirectangularFOV = true;
  109377. material.fovMultiplier = 1.0;
  109378. material.opacityFresnel = false;
  109379. if (_this._useDirectMapping) {
  109380. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109381. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109382. material.diffuseTexture = texture;
  109383. }
  109384. else {
  109385. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  109386. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109387. material.reflectionTexture = texture;
  109388. }
  109389. // configure mesh
  109390. _this._mesh.material = material;
  109391. _this._mesh.parent = _this;
  109392. // optional configuration
  109393. if (options.clickToPlay) {
  109394. scene.onPointerUp = function () {
  109395. _this._videoTexture.video.play();
  109396. };
  109397. }
  109398. return _this;
  109399. }
  109400. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  109401. /**
  109402. * Gets the video texture being displayed on the sphere
  109403. */
  109404. get: function () {
  109405. return this._videoTexture;
  109406. },
  109407. enumerable: true,
  109408. configurable: true
  109409. });
  109410. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  109411. /**
  109412. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  109413. * Also see the options.resolution property.
  109414. */
  109415. get: function () {
  109416. return this._material.fovMultiplier;
  109417. },
  109418. set: function (value) {
  109419. this._material.fovMultiplier = value;
  109420. },
  109421. enumerable: true,
  109422. configurable: true
  109423. });
  109424. /**
  109425. * Releases resources associated with this node.
  109426. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  109427. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  109428. */
  109429. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  109430. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  109431. this._videoTexture.dispose();
  109432. this._mesh.dispose();
  109433. this._material.dispose();
  109434. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  109435. };
  109436. return VideoDome;
  109437. }(BABYLON.TransformNode));
  109438. BABYLON.VideoDome = VideoDome;
  109439. })(BABYLON || (BABYLON = {}));
  109440. //# sourceMappingURL=babylon.videoDome.js.map
  109441. var BABYLON;
  109442. (function (BABYLON) {
  109443. /**
  109444. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  109445. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  109446. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  109447. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  109448. */
  109449. var PhotoDome = /** @class */ (function (_super) {
  109450. __extends(PhotoDome, _super);
  109451. /**
  109452. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  109453. * @param name Element's name, child elements will append suffixes for their own names.
  109454. * @param urlsOfPhoto defines the url of the photo to display
  109455. * @param options defines an object containing optional or exposed sub element properties
  109456. * @param onError defines a callback called when an error occured while loading the texture
  109457. */
  109458. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  109459. if (onError === void 0) { onError = null; }
  109460. var _this = _super.call(this, name, scene) || this;
  109461. _this._useDirectMapping = false;
  109462. /**
  109463. * Observable raised when an error occured while loading the 360 image
  109464. */
  109465. _this.onLoadErrorObservable = new BABYLON.Observable();
  109466. // set defaults and manage values
  109467. name = name || "photoDome";
  109468. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  109469. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  109470. if (options.useDirectMapping === undefined) {
  109471. _this._useDirectMapping = true;
  109472. }
  109473. else {
  109474. _this._useDirectMapping = options.useDirectMapping;
  109475. }
  109476. _this._setReady(false);
  109477. // create
  109478. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  109479. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  109480. // configure material
  109481. material.opacityFresnel = false;
  109482. material.useEquirectangularFOV = true;
  109483. material.fovMultiplier = 1.0;
  109484. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  109485. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  109486. if (onError) {
  109487. onError(message, exception);
  109488. }
  109489. });
  109490. _this.photoTexture.onLoadObservable.addOnce(function () {
  109491. _this._setReady(true);
  109492. });
  109493. // configure mesh
  109494. _this._mesh.material = material;
  109495. _this._mesh.parent = _this;
  109496. return _this;
  109497. }
  109498. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  109499. /**
  109500. * Gets or sets the texture being displayed on the sphere
  109501. */
  109502. get: function () {
  109503. return this._photoTexture;
  109504. },
  109505. set: function (value) {
  109506. if (this._photoTexture === value) {
  109507. return;
  109508. }
  109509. this._photoTexture = value;
  109510. if (this._useDirectMapping) {
  109511. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109512. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109513. this._material.diffuseTexture = this._photoTexture;
  109514. }
  109515. else {
  109516. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  109517. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109518. this._material.reflectionTexture = this._photoTexture;
  109519. }
  109520. },
  109521. enumerable: true,
  109522. configurable: true
  109523. });
  109524. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  109525. /**
  109526. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  109527. * Also see the options.resolution property.
  109528. */
  109529. get: function () {
  109530. return this._material.fovMultiplier;
  109531. },
  109532. set: function (value) {
  109533. this._material.fovMultiplier = value;
  109534. },
  109535. enumerable: true,
  109536. configurable: true
  109537. });
  109538. /**
  109539. * Releases resources associated with this node.
  109540. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  109541. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  109542. */
  109543. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  109544. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  109545. this._photoTexture.dispose();
  109546. this._mesh.dispose();
  109547. this._material.dispose();
  109548. this.onLoadErrorObservable.clear();
  109549. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  109550. };
  109551. return PhotoDome;
  109552. }(BABYLON.TransformNode));
  109553. BABYLON.PhotoDome = PhotoDome;
  109554. })(BABYLON || (BABYLON = {}));
  109555. //# sourceMappingURL=babylon.photoDome.js.map
  109556. var BABYLON;
  109557. (function (BABYLON) {
  109558. BABYLON.Engine.prototype.createQuery = function () {
  109559. return this._gl.createQuery();
  109560. };
  109561. BABYLON.Engine.prototype.deleteQuery = function (query) {
  109562. this._gl.deleteQuery(query);
  109563. return this;
  109564. };
  109565. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  109566. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  109567. };
  109568. BABYLON.Engine.prototype.getQueryResult = function (query) {
  109569. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  109570. };
  109571. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  109572. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  109573. this._gl.beginQuery(glAlgorithm, query);
  109574. return this;
  109575. };
  109576. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  109577. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  109578. this._gl.endQuery(glAlgorithm);
  109579. return this;
  109580. };
  109581. BABYLON.Engine.prototype._createTimeQuery = function () {
  109582. var timerQuery = this.getCaps().timerQuery;
  109583. if (timerQuery.createQueryEXT) {
  109584. return timerQuery.createQueryEXT();
  109585. }
  109586. return this.createQuery();
  109587. };
  109588. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  109589. var timerQuery = this.getCaps().timerQuery;
  109590. if (timerQuery.deleteQueryEXT) {
  109591. timerQuery.deleteQueryEXT(query);
  109592. return;
  109593. }
  109594. this.deleteQuery(query);
  109595. };
  109596. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  109597. var timerQuery = this.getCaps().timerQuery;
  109598. if (timerQuery.getQueryObjectEXT) {
  109599. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  109600. }
  109601. return this.getQueryResult(query);
  109602. };
  109603. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  109604. var timerQuery = this.getCaps().timerQuery;
  109605. if (timerQuery.getQueryObjectEXT) {
  109606. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  109607. }
  109608. return this.isQueryResultAvailable(query);
  109609. };
  109610. BABYLON.Engine.prototype.startTimeQuery = function () {
  109611. var caps = this.getCaps();
  109612. var timerQuery = caps.timerQuery;
  109613. if (!timerQuery) {
  109614. return null;
  109615. }
  109616. var token = new BABYLON._TimeToken();
  109617. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  109618. if (caps.canUseTimestampForTimerQuery) {
  109619. token._startTimeQuery = this._createTimeQuery();
  109620. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  109621. }
  109622. else {
  109623. if (this._currentNonTimestampToken) {
  109624. return this._currentNonTimestampToken;
  109625. }
  109626. token._timeElapsedQuery = this._createTimeQuery();
  109627. if (timerQuery.beginQueryEXT) {
  109628. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  109629. }
  109630. else {
  109631. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  109632. }
  109633. this._currentNonTimestampToken = token;
  109634. }
  109635. return token;
  109636. };
  109637. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  109638. var caps = this.getCaps();
  109639. var timerQuery = caps.timerQuery;
  109640. if (!timerQuery || !token) {
  109641. return -1;
  109642. }
  109643. if (caps.canUseTimestampForTimerQuery) {
  109644. if (!token._startTimeQuery) {
  109645. return -1;
  109646. }
  109647. if (!token._endTimeQuery) {
  109648. token._endTimeQuery = this._createTimeQuery();
  109649. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  109650. }
  109651. }
  109652. else if (!token._timeElapsedQueryEnded) {
  109653. if (!token._timeElapsedQuery) {
  109654. return -1;
  109655. }
  109656. if (timerQuery.endQueryEXT) {
  109657. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  109658. }
  109659. else {
  109660. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  109661. }
  109662. token._timeElapsedQueryEnded = true;
  109663. }
  109664. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  109665. var available = false;
  109666. if (token._endTimeQuery) {
  109667. available = this._getTimeQueryAvailability(token._endTimeQuery);
  109668. }
  109669. else if (token._timeElapsedQuery) {
  109670. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  109671. }
  109672. if (available && !disjoint) {
  109673. var result = 0;
  109674. if (caps.canUseTimestampForTimerQuery) {
  109675. if (!token._startTimeQuery || !token._endTimeQuery) {
  109676. return -1;
  109677. }
  109678. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  109679. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  109680. result = timeEnd - timeStart;
  109681. this._deleteTimeQuery(token._startTimeQuery);
  109682. this._deleteTimeQuery(token._endTimeQuery);
  109683. token._startTimeQuery = null;
  109684. token._endTimeQuery = null;
  109685. }
  109686. else {
  109687. if (!token._timeElapsedQuery) {
  109688. return -1;
  109689. }
  109690. result = this._getTimeQueryResult(token._timeElapsedQuery);
  109691. this._deleteTimeQuery(token._timeElapsedQuery);
  109692. token._timeElapsedQuery = null;
  109693. token._timeElapsedQueryEnded = false;
  109694. this._currentNonTimestampToken = null;
  109695. }
  109696. return result;
  109697. }
  109698. return -1;
  109699. };
  109700. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  109701. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  109702. };
  109703. // We also need to update AbstractMesh as there is a portion of the code there
  109704. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  109705. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  109706. this._isOccluded = false;
  109707. return;
  109708. }
  109709. var engine = this.getEngine();
  109710. if (engine.webGLVersion < 2) {
  109711. this._isOccluded = false;
  109712. return;
  109713. }
  109714. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  109715. this._isOccluded = false;
  109716. return;
  109717. }
  109718. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  109719. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  109720. if (isOcclusionQueryAvailable) {
  109721. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  109722. this._isOcclusionQueryInProgress = false;
  109723. this._occlusionInternalRetryCounter = 0;
  109724. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  109725. }
  109726. else {
  109727. this._occlusionInternalRetryCounter++;
  109728. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  109729. this._isOcclusionQueryInProgress = false;
  109730. this._occlusionInternalRetryCounter = 0;
  109731. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  109732. // if strict continue the last state of the object.
  109733. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  109734. }
  109735. else {
  109736. return;
  109737. }
  109738. }
  109739. }
  109740. var scene = this.getScene();
  109741. if (scene.getBoundingBoxRenderer) {
  109742. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  109743. if (!this._occlusionQuery) {
  109744. this._occlusionQuery = engine.createQuery();
  109745. }
  109746. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  109747. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  109748. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  109749. this._isOcclusionQueryInProgress = true;
  109750. }
  109751. };
  109752. })(BABYLON || (BABYLON = {}));
  109753. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  109754. var BABYLON;
  109755. (function (BABYLON) {
  109756. /**
  109757. * Class used to generate noise procedural textures
  109758. */
  109759. var NoiseProceduralTexture = /** @class */ (function (_super) {
  109760. __extends(NoiseProceduralTexture, _super);
  109761. /**
  109762. * Creates a new NoiseProceduralTexture
  109763. * @param name defines the name fo the texture
  109764. * @param size defines the size of the texture (default is 256)
  109765. * @param scene defines the hosting scene
  109766. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  109767. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  109768. */
  109769. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  109770. if (size === void 0) { size = 256; }
  109771. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  109772. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  109773. _this._time = 0;
  109774. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  109775. _this.brightness = 0.2;
  109776. /** Defines the number of octaves to process */
  109777. _this.octaves = 3;
  109778. /** Defines the level of persistence (0.8 by default) */
  109779. _this.persistence = 0.8;
  109780. /** Gets or sets animation speed factor (default is 1) */
  109781. _this.animationSpeedFactor = 1;
  109782. _this._updateShaderUniforms();
  109783. return _this;
  109784. }
  109785. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  109786. var scene = this.getScene();
  109787. if (!scene) {
  109788. return;
  109789. }
  109790. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  109791. this.setFloat("brightness", this.brightness);
  109792. this.setFloat("persistence", this.persistence);
  109793. this.setFloat("timeScale", this._time);
  109794. };
  109795. NoiseProceduralTexture.prototype._getDefines = function () {
  109796. return "#define OCTAVES " + (this.octaves | 0);
  109797. };
  109798. /** Generate the current state of the procedural texture */
  109799. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  109800. this._updateShaderUniforms();
  109801. _super.prototype.render.call(this, useCameraPostProcess);
  109802. };
  109803. /**
  109804. * Serializes this noise procedural texture
  109805. * @returns a serialized noise procedural texture object
  109806. */
  109807. NoiseProceduralTexture.prototype.serialize = function () {
  109808. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  109809. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  109810. return serializationObject;
  109811. };
  109812. /**
  109813. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  109814. * @param parsedTexture defines parsed texture data
  109815. * @param scene defines the current scene
  109816. * @param rootUrl defines the root URL containing noise procedural texture information
  109817. * @returns a parsed NoiseProceduralTexture
  109818. */
  109819. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  109820. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  109821. return texture;
  109822. };
  109823. return NoiseProceduralTexture;
  109824. }(BABYLON.ProceduralTexture));
  109825. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  109826. })(BABYLON || (BABYLON = {}));
  109827. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  109828. var __assign = (this && this.__assign) || function () {
  109829. __assign = Object.assign || function(t) {
  109830. for (var s, i = 1, n = arguments.length; i < n; i++) {
  109831. s = arguments[i];
  109832. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  109833. t[p] = s[p];
  109834. }
  109835. return t;
  109836. };
  109837. return __assign.apply(this, arguments);
  109838. };
  109839. var BABYLON;
  109840. (function (BABYLON) {
  109841. /**
  109842. * This can helps recording videos from BabylonJS.
  109843. * This is based on the available WebRTC functionalities of the browser.
  109844. *
  109845. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  109846. */
  109847. var VideoRecorder = /** @class */ (function () {
  109848. /**
  109849. * Create a new VideoCapture object which can help converting what you see in Babylon to
  109850. * a video file.
  109851. * @param engine Defines the BabylonJS Engine you wish to record
  109852. * @param options Defines options that can be used to customized the capture
  109853. */
  109854. function VideoRecorder(engine, options) {
  109855. if (options === void 0) { options = null; }
  109856. if (!VideoRecorder.IsSupported(engine)) {
  109857. throw "Your browser does not support recording so far.";
  109858. }
  109859. var canvas = engine.getRenderingCanvas();
  109860. if (!canvas) {
  109861. throw "The babylon engine must have a canvas to be recorded";
  109862. }
  109863. this._canvas = canvas;
  109864. this._canvas.isRecording = false;
  109865. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  109866. var stream = this._canvas.captureStream(this._options.fps);
  109867. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  109868. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  109869. this._mediaRecorder.onerror = this._handleError.bind(this);
  109870. this._mediaRecorder.onstop = this._handleStop.bind(this);
  109871. }
  109872. /**
  109873. * Returns wehther or not the VideoRecorder is available in your browser.
  109874. * @param engine Defines the Babylon Engine to check the support for
  109875. * @returns true if supported otherwise false
  109876. */
  109877. VideoRecorder.IsSupported = function (engine) {
  109878. var canvas = engine.getRenderingCanvas();
  109879. return (!!canvas && typeof canvas.captureStream === "function");
  109880. };
  109881. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  109882. /**
  109883. * True wether a recording is already in progress.
  109884. */
  109885. get: function () {
  109886. return !!this._canvas && this._canvas.isRecording;
  109887. },
  109888. enumerable: true,
  109889. configurable: true
  109890. });
  109891. /**
  109892. * Stops the current recording before the default capture timeout passed in the startRecording
  109893. * functions.
  109894. */
  109895. VideoRecorder.prototype.stopRecording = function () {
  109896. if (!this._canvas || !this._mediaRecorder) {
  109897. return;
  109898. }
  109899. if (!this.isRecording) {
  109900. return;
  109901. }
  109902. this._canvas.isRecording = false;
  109903. this._mediaRecorder.stop();
  109904. };
  109905. /**
  109906. * Starts recording the canvas for a max duration specified in parameters.
  109907. * @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.
  109908. * @param maxDuration Defines the maximum recording time in seconds.
  109909. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  109910. * @return a promise callback at the end of the recording with the video data in Blob.
  109911. */
  109912. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  109913. var _this = this;
  109914. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  109915. if (maxDuration === void 0) { maxDuration = 7; }
  109916. if (!this._canvas || !this._mediaRecorder) {
  109917. throw "Recorder has already been disposed";
  109918. }
  109919. if (this.isRecording) {
  109920. throw "Recording already in progress";
  109921. }
  109922. if (maxDuration > 0) {
  109923. setTimeout(function () {
  109924. _this.stopRecording();
  109925. }, maxDuration * 1000);
  109926. }
  109927. this._fileName = fileName;
  109928. this._recordedChunks = [];
  109929. this._resolve = null;
  109930. this._reject = null;
  109931. this._canvas.isRecording = true;
  109932. this._mediaRecorder.start(this._options.recordChunckSize);
  109933. return new Promise(function (resolve, reject) {
  109934. _this._resolve = resolve;
  109935. _this._reject = reject;
  109936. });
  109937. };
  109938. /**
  109939. * Releases internal resources used during the recording.
  109940. */
  109941. VideoRecorder.prototype.dispose = function () {
  109942. this._canvas = null;
  109943. this._mediaRecorder = null;
  109944. this._recordedChunks = [];
  109945. this._fileName = null;
  109946. this._resolve = null;
  109947. this._reject = null;
  109948. };
  109949. VideoRecorder.prototype._handleDataAvailable = function (event) {
  109950. if (event.data.size > 0) {
  109951. this._recordedChunks.push(event.data);
  109952. }
  109953. };
  109954. VideoRecorder.prototype._handleError = function (event) {
  109955. this.stopRecording();
  109956. if (this._reject) {
  109957. this._reject(event.error);
  109958. }
  109959. else {
  109960. throw new event.error;
  109961. }
  109962. };
  109963. VideoRecorder.prototype._handleStop = function () {
  109964. this.stopRecording();
  109965. var superBuffer = new Blob(this._recordedChunks);
  109966. if (this._resolve) {
  109967. this._resolve(superBuffer);
  109968. }
  109969. window.URL.createObjectURL(superBuffer);
  109970. if (this._fileName) {
  109971. BABYLON.Tools.Download(superBuffer, this._fileName);
  109972. }
  109973. };
  109974. VideoRecorder._defaultOptions = {
  109975. mimeType: "video/webm",
  109976. fps: 25,
  109977. recordChunckSize: 3000
  109978. };
  109979. return VideoRecorder;
  109980. }());
  109981. BABYLON.VideoRecorder = VideoRecorder;
  109982. })(BABYLON || (BABYLON = {}));
  109983. //# sourceMappingURL=babylon.videoRecorder.js.map
  109984. var BABYLON;
  109985. (function (BABYLON) {
  109986. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  109987. if (replace === void 0) { replace = false; }
  109988. // Dispose existing light in replace mode.
  109989. if (replace) {
  109990. if (this.lights) {
  109991. for (var i = 0; i < this.lights.length; i++) {
  109992. this.lights[i].dispose();
  109993. }
  109994. }
  109995. }
  109996. // Light
  109997. if (this.lights.length === 0) {
  109998. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  109999. }
  110000. };
  110001. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  110002. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  110003. if (replace === void 0) { replace = false; }
  110004. if (attachCameraControls === void 0) { attachCameraControls = false; }
  110005. // Dispose existing camera in replace mode.
  110006. if (replace) {
  110007. if (this.activeCamera) {
  110008. this.activeCamera.dispose();
  110009. this.activeCamera = null;
  110010. }
  110011. }
  110012. // Camera
  110013. if (!this.activeCamera) {
  110014. var worldExtends = this.getWorldExtends();
  110015. var worldSize = worldExtends.max.subtract(worldExtends.min);
  110016. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  110017. var camera;
  110018. var radius = worldSize.length() * 1.5;
  110019. // empty scene scenario!
  110020. if (!isFinite(radius)) {
  110021. radius = 1;
  110022. worldCenter.copyFromFloats(0, 0, 0);
  110023. }
  110024. if (createArcRotateCamera) {
  110025. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  110026. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  110027. arcRotateCamera.wheelPrecision = 100 / radius;
  110028. camera = arcRotateCamera;
  110029. }
  110030. else {
  110031. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  110032. freeCamera.setTarget(worldCenter);
  110033. camera = freeCamera;
  110034. }
  110035. camera.minZ = radius * 0.01;
  110036. camera.maxZ = radius * 1000;
  110037. camera.speed = radius * 0.2;
  110038. this.activeCamera = camera;
  110039. var canvas = this.getEngine().getRenderingCanvas();
  110040. if (attachCameraControls && canvas) {
  110041. camera.attachControl(canvas);
  110042. }
  110043. }
  110044. };
  110045. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  110046. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  110047. if (replace === void 0) { replace = false; }
  110048. if (attachCameraControls === void 0) { attachCameraControls = false; }
  110049. this.createDefaultLight(replace);
  110050. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  110051. };
  110052. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  110053. if (pbr === void 0) { pbr = false; }
  110054. if (scale === void 0) { scale = 1000; }
  110055. if (blur === void 0) { blur = 0; }
  110056. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  110057. if (!environmentTexture) {
  110058. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  110059. return null;
  110060. }
  110061. if (setGlobalEnvTexture) {
  110062. if (environmentTexture) {
  110063. this.environmentTexture = environmentTexture;
  110064. }
  110065. }
  110066. // Skybox
  110067. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  110068. if (pbr) {
  110069. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  110070. hdrSkyboxMaterial.backFaceCulling = false;
  110071. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  110072. if (hdrSkyboxMaterial.reflectionTexture) {
  110073. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  110074. }
  110075. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  110076. hdrSkyboxMaterial.disableLighting = true;
  110077. hdrSkyboxMaterial.twoSidedLighting = true;
  110078. hdrSkybox.infiniteDistance = true;
  110079. hdrSkybox.material = hdrSkyboxMaterial;
  110080. }
  110081. else {
  110082. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  110083. skyboxMaterial.backFaceCulling = false;
  110084. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  110085. if (skyboxMaterial.reflectionTexture) {
  110086. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  110087. }
  110088. skyboxMaterial.disableLighting = true;
  110089. hdrSkybox.infiniteDistance = true;
  110090. hdrSkybox.material = skyboxMaterial;
  110091. }
  110092. return hdrSkybox;
  110093. };
  110094. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  110095. if (BABYLON.EnvironmentHelper) {
  110096. return new BABYLON.EnvironmentHelper(options, this);
  110097. }
  110098. return null;
  110099. };
  110100. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  110101. if (webVROptions === void 0) { webVROptions = {}; }
  110102. return new BABYLON.VRExperienceHelper(this, webVROptions);
  110103. };
  110104. })(BABYLON || (BABYLON = {}));
  110105. //# sourceMappingURL=babylon.sceneHelpers.js.map
  110106. 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=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-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#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\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 NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\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#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\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(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\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"};
  110107. 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};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  110108. globalObject["BABYLON"] = BABYLON;
  110109. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var serializeAsCameraReference = BABYLON.serializeAsCameraReference;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var ColorGradient = BABYLON.ColorGradient;var Color3Gradient = BABYLON.Color3Gradient;var FactorGradient = BABYLON.FactorGradient;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var SceneComponentConstants = BABYLON.SceneComponentConstants;var Stage = BABYLON.Stage;var AbstractScene = BABYLON.AbstractScene;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var SpriteSceneComponent = BABYLON.SpriteSceneComponent;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var BaseParticleSystem = BABYLON.BaseParticleSystem;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var CylinderParticleEmitter = BABYLON.CylinderParticleEmitter;var CylinderDirectedParticleEmitter = BABYLON.CylinderDirectedParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var HemisphericParticleEmitter = BABYLON.HemisphericParticleEmitter;var PointParticleEmitter = BABYLON.PointParticleEmitter;var SubEmitter = BABYLON.SubEmitter;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var StringDictionary = BABYLON.StringDictionary;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var WeightedSound = BABYLON.WeightedSound;var AudioSceneComponent = BABYLON.AudioSceneComponent;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var CubeTexture = BABYLON.CubeTexture;var RawCubeTexture = BABYLON.RawCubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var RawTexture3D = BABYLON.RawTexture3D;var PostProcessManager = BABYLON.PostProcessManager;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var ShadowGeneratorSceneComponent = BABYLON.ShadowGeneratorSceneComponent;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var ProceduralTextureSceneComponent = BABYLON.ProceduralTextureSceneComponent;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var GamepadSystemSceneComponent = BABYLON.GamepadSystemSceneComponent;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderPipelineManagerSceneComponent = BABYLON.PostProcessRenderPipelineManagerSceneComponent;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var DepthRendererSceneComponent = BABYLON.DepthRendererSceneComponent;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var GeometryBufferRendererSceneComponent = BABYLON.GeometryBufferRendererSceneComponent;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var GrainPostProcess = BABYLON.GrainPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcessOptions = BABYLON.DepthOfFieldMergePostProcessOptions;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var BloomMergePostProcess = BABYLON.BloomMergePostProcess;var ExtractHighlightsPostProcess = BABYLON.ExtractHighlightsPostProcess;var BloomEffect = BABYLON.BloomEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var ImageProcessingConfigurationDefines = BABYLON.ImageProcessingConfigurationDefines;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystemSceneComponent = BABYLON.LensFlareSystemSceneComponent;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var PhysicsEngineSceneComponent = BABYLON.PhysicsEngineSceneComponent;var DDSTools = BABYLON.DDSTools;var TGATools = BABYLON.TGATools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var EnvironmentTextureTools = BABYLON.EnvironmentTextureTools;var UtilityLayerRenderer = BABYLON.UtilityLayerRenderer;var PointerDragBehavior = BABYLON.PointerDragBehavior;var MultiPointerScaleBehavior = BABYLON.MultiPointerScaleBehavior;var SixDofDragBehavior = BABYLON.SixDofDragBehavior;var AttachToBoxBehavior = BABYLON.AttachToBoxBehavior;var FadeInOutBehavior = BABYLON.FadeInOutBehavior;var Gizmo = BABYLON.Gizmo;var AxisDragGizmo = BABYLON.AxisDragGizmo;var AxisScaleGizmo = BABYLON.AxisScaleGizmo;var PlaneRotationGizmo = BABYLON.PlaneRotationGizmo;var PositionGizmo = BABYLON.PositionGizmo;var RotationGizmo = BABYLON.RotationGizmo;var ScaleGizmo = BABYLON.ScaleGizmo;var BoundingBoxGizmo = BABYLON.BoundingBoxGizmo;var GizmoManager = BABYLON.GizmoManager;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var OctreeSceneComponent = BABYLON.OctreeSceneComponent;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var SimplicationQueueSceneComponent = BABYLON.SimplicationQueueSceneComponent;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var LineEdgesRenderer = BABYLON.LineEdgesRenderer;var EffectLayerSceneComponent = BABYLON.EffectLayerSceneComponent;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var LayerSceneComponent = BABYLON.LayerSceneComponent;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var ParticleSystemSet = BABYLON.ParticleSystemSet;var ParticleHelper = BABYLON.ParticleHelper;var VideoDome = BABYLON.VideoDome;var PhotoDome = BABYLON.PhotoDome;var NoiseProceduralTexture = BABYLON.NoiseProceduralTexture;var VideoRecorder = BABYLON.VideoRecorder;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var SubEmitterType = BABYLON.SubEmitterType ;var Debug = BABYLON.Debug ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  110110. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,serializeAsCameraReference,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,ColorGradient,Color3Gradient,FactorGradient,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,SceneComponentConstants,Stage,AbstractScene,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PerformanceMonitor,RollingAverage,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,SpriteManager,Sprite,SpriteSceneComponent,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,BaseParticleSystem,ParticleSystem,BoxParticleEmitter,CylinderParticleEmitter,CylinderDirectedParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,HemisphericParticleEmitter,PointParticleEmitter,SubEmitter,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,StringDictionary,RayHelper,DebugLayer,BoundingBoxRenderer,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,WeightedSound,AudioSceneComponent,PlaySoundAction,StopSoundAction,CubeTexture,RawCubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,RawTexture3D,PostProcessManager,PostProcess,PassPostProcess,ShadowGenerator,ShadowGeneratorSceneComponent,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,ProceduralTextureSceneComponent,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,GamepadSystemSceneComponent,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderPipelineManagerSceneComponent,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,DepthRendererSceneComponent,GeometryBufferRenderer,GeometryBufferRendererSceneComponent,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,GrainPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcessOptions,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,BloomMergePostProcess,ExtractHighlightsPostProcess,BloomEffect,DefaultRenderingPipeline,ImageProcessingConfigurationDefines,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,HDRTools,HDRCubeTexture,PanoramaToCubeMapTools,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystemSceneComponent,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,PhysicsEngineSceneComponent,DDSTools,TGATools,KhronosTextureContainer,EnvironmentTextureTools,UtilityLayerRenderer,PointerDragBehavior,MultiPointerScaleBehavior,SixDofDragBehavior,AttachToBoxBehavior,FadeInOutBehavior,Gizmo,AxisDragGizmo,AxisScaleGizmo,PlaneRotationGizmo,PositionGizmo,RotationGizmo,ScaleGizmo,BoundingBoxGizmo,GizmoManager,MorphTarget,MorphTargetManager,Octree,OctreeBlock,OctreeSceneComponent,AnaglyphPostProcess,AnaglyphArcRotateCamera,AnaglyphFreeCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicInterlacePostProcess,StereoscopicArcRotateCamera,StereoscopicFreeCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRDistortionCorrectionPostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationArcRotateCamera,VRDeviceOrientationGamepadCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,SimplicationQueueSceneComponent,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,LineEdgesRenderer,EffectLayerSceneComponent,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,LayerSceneComponent,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,ParticleSystemSet,ParticleHelper,VideoDome,PhotoDome,NoiseProceduralTexture,VideoRecorder,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,SubEmitterType ,Debug ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,JoystickAxis ,SimplificationType ,AssetTaskState };